优化飞书通讯录同步
This commit is contained in:
1 parent
0a83dfb7be
commit
3a3f0d2585
160 files changed
+7662
-6382
No files matched your search
@@ -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.
|
||||
@@ -50,19 +50,10 @@
|
||||
|
||||
<!-- Database -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</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>
|
||||
@@ -121,17 +112,6 @@
|
||||
<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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, Object> 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<String,Object> 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<String,Object> map, String... keys) { for (String k:keys) if(map.get(k)!=null)return map.get(k); return null; }
|
||||
private String text(Map<String,Object> map,String...keys){Object v=first(map,keys);return v==null?null:String.valueOf(v);}
|
||||
@SuppressWarnings("unchecked") private Map<String,Object> map(Object v){return v instanceof Map?(Map<String,Object>)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);}
|
||||
}
|
||||
@@ -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<String, String> buildForm(ReimApplication app, SysUser applicant,
|
||||
SysDepartment department, SysExpenseType expenseType,
|
||||
List<ReimExpenseItem> items) {
|
||||
Map<String, String> form = new HashMap<>();
|
||||
Map<String, String> 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> body = Collections.singletonMap("approval_code", approvalCode());
|
||||
try {
|
||||
ResponseEntity<JsonNode> 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<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("该申请已有未完成的飞书同步记录,请稍后重试");
|
||||
}
|
||||
}
|
||||
/** 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<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);
|
||||
SysDepartment department = application.getDepartmentId() == null ? null
|
||||
: sysDepartmentRepository.findById(application.getDepartmentId()).orElse(null);
|
||||
SysExpenseType expenseType = application.getExpenseTypeId() == null ? null
|
||||
: sysExpenseTypeRepository.findById(application.getExpenseTypeId()).orElse(null);
|
||||
List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(applicationId);
|
||||
String formJson = FeishuApprovalFormBuilder.buildFormJson(
|
||||
FeishuApprovalFormBuilder.buildForm(application, applicant, department, expenseType, items));
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("approval_code", intendedApprovalCode);
|
||||
body.put("user_id", applicant.getFeishuUserId() == null ? "" : applicant.getFeishuUserId());
|
||||
body.put("open_id", applicant.getFeishuOpenId() == null ? "" : applicant.getFeishuOpenId());
|
||||
body.put("form", formJson); body.put("uuid", requestUuid);
|
||||
try {
|
||||
String json = JSON.writeValueAsString(body);
|
||||
if (json.length() > 200000) throw new BusinessException("飞书审批表单过大", 400);
|
||||
return json;
|
||||
} catch (BusinessException e) { throw e; }
|
||||
catch (Exception e) { throw new BusinessException("飞书审批表单生成失败", 500); }
|
||||
}
|
||||
|
||||
/** Sends the exact persisted body. No application or directory data is reloaded here. */
|
||||
public String createApprovalInstanceRemote(String persistedPayload, String requestUuid) {
|
||||
if (!StringUtils.hasText(persistedPayload) || !StringUtils.hasText(requestUuid))
|
||||
throw new BusinessException("飞书审批创建参数无效", 400);
|
||||
Map<String,Object> body;
|
||||
try { body = JSON.readValue(persistedPayload, new TypeReference<Map<String,Object>>() {}); }
|
||||
catch (Exception e) { throw new BusinessException("飞书审批创建载荷无效", 500); }
|
||||
if (!Objects.equals(requestUuid, body.get("uuid"))) throw new BusinessException("飞书审批创建载荷不匹配", 500);
|
||||
HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(feishuAuthService.getTenantAccessToken());
|
||||
headers.setContentType(MediaType.APPLICATION_JSON); headers.set("X-Request-ID", requestUuid);
|
||||
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);
|
||||
FEISHU_OPEN_API + "/approval/openapi/v2/instance/create", HttpMethod.POST,
|
||||
new HttpEntity<>(body, headers), FeishuApprovalResponse.class);
|
||||
FeishuApprovalResponse value = response.getBody();
|
||||
if (value == null) throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试");
|
||||
if (value.getCode() != 0) throw new BusinessException("创建飞书审批失败: " + value.getMsg(), 502);
|
||||
if (value.getData() == null || !StringUtils.hasText(value.getData().getInstanceCode()))
|
||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试");
|
||||
String instance = value.getData().getInstanceCode().trim();
|
||||
if (instance.length() > 200)
|
||||
throw new FeishuCreateOutcomeUnknownException("飞书已响应创建但实例标识无效,禁止修改原申请");
|
||||
return instance;
|
||||
} catch (FeishuCreateOutcomeUnknownException e) {
|
||||
throw e;
|
||||
} catch (BusinessException e) { throw e;
|
||||
} catch (RestClientResponseException e) {
|
||||
int status = e.getRawStatusCode();
|
||||
if (status == 408 || status == 409 || status == 425 || status == 429 || status >= 500)
|
||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
||||
if (status >= 400 && status < 500)
|
||||
throw new BusinessException("飞书拒绝创建审批实例", 502);
|
||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
||||
} catch (Exception e) {
|
||||
log.error("创建飞书审批实例失败: applicationNo={}", application.getApplicationNo(), e);
|
||||
throw new BusinessException("创建飞书审批失败,请稍后重试");
|
||||
log.warn("飞书审批远程创建失败: {}", e.getClass().getSimpleName());
|
||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,8 +284,7 @@ public class FeishuApprovalService {
|
||||
*/
|
||||
@Transactional
|
||||
public void syncApprovalResult(String instanceCode, String status, String comment) {
|
||||
IntFeishuApproval syncRecord = intFeishuApprovalRepository
|
||||
.findByFeishuInstanceCodeForUpdate(instanceCode)
|
||||
IntFeishuApproval candidate = intFeishuApprovalRepository.findByFeishuInstanceCode(instanceCode)
|
||||
.orElseThrow(() -> new BusinessException("未找到对应的审批同步记录"));
|
||||
|
||||
String normalizedStatus = normalizeApprovalStatus(status);
|
||||
@@ -282,6 +295,11 @@ public class FeishuApprovalService {
|
||||
|
||||
// Terminal records are monotonic. This prevents a delayed PENDING
|
||||
// callback from reopening an already approved/rejected application.
|
||||
ReimApplication application = reimApplicationRepository.findByIdForUpdate(candidate.getApplicationId())
|
||||
.orElseThrow(() -> new BusinessException("未找到对应的报销申请"));
|
||||
IntFeishuApproval syncRecord = intFeishuApprovalRepository.findByApplicationIdForUpdate(candidate.getApplicationId())
|
||||
.filter(value -> Objects.equals(instanceCode, value.getFeishuInstanceCode()))
|
||||
.orElseThrow(() -> new BusinessException("审批实例已不是当前申请", 409));
|
||||
String previousStatus = normalizeApprovalStatus(syncRecord.getStatus());
|
||||
if (isTerminal(previousStatus)) {
|
||||
log.info("忽略终态后的旧飞书审批事件: instanceCode={}, oldStatus={}, status={}",
|
||||
@@ -289,9 +307,6 @@ public class FeishuApprovalService {
|
||||
return;
|
||||
}
|
||||
|
||||
ReimApplication application = reimApplicationRepository.findById(syncRecord.getApplicationId())
|
||||
.orElseThrow(() -> new BusinessException("未找到对应的报销申请"));
|
||||
|
||||
// 更新同步记录
|
||||
syncRecord.setStatus(normalizedStatus);
|
||||
syncRecord.setSyncedAt(LocalDateTime.now());
|
||||
@@ -318,8 +333,7 @@ public class FeishuApprovalService {
|
||||
}
|
||||
reimApplicationRepository.save(application);
|
||||
|
||||
log.info("飞书审批同步成功: instanceCode={}, status={}, comment={}",
|
||||
instanceCode, normalizedStatus, comment);
|
||||
log.info("飞书审批同步成功: instanceCode={}, status={}", instanceCode, normalizedStatus);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -346,7 +360,6 @@ public class FeishuApprovalService {
|
||||
* - approval_instance: 审批实例状态变更
|
||||
* - approval_task: 审批任务变更
|
||||
*/
|
||||
@Transactional
|
||||
public void handleApprovalEvent(Map<String, Object> eventData) {
|
||||
String eventType = (String) eventData.get("event_type");
|
||||
if (eventType == null) {
|
||||
@@ -379,12 +392,23 @@ public class FeishuApprovalService {
|
||||
}
|
||||
if (instance == null) return;
|
||||
|
||||
String instanceCode = (String) instance.get("instance_code");
|
||||
String status = (String) instance.get("status");
|
||||
String comment = (String) instance.get("comment");
|
||||
String instanceCode = text(instance, "instance_code", "instanceCode");
|
||||
String status = text(instance, "status");
|
||||
String comment = text(instance, "comment");
|
||||
|
||||
if (instanceCode != null && status != null) {
|
||||
syncApprovalResult(instanceCode, status, comment);
|
||||
String authoritative = normalizeApprovalStatus(status);
|
||||
LocalDateTime eventTime = parseTime(firstValue(instance, "update_time", "action_time", "timestamp"));
|
||||
if (isTerminal(authoritative)) {
|
||||
FeishuApprovalResponse detail = getApprovalInstanceDetail(instanceCode);
|
||||
if (detail == null || detail.getData() == null
|
||||
|| normalizeApprovalStatus(detail.getData().getStatus()) == null)
|
||||
throw new BusinessException("无法确认飞书审批终态,请稍后重试", 503);
|
||||
authoritative = normalizeApprovalStatus(detail.getData().getStatus());
|
||||
eventTime = LocalDateTime.now();
|
||||
}
|
||||
if (eventStateService != null) eventStateService.applyInstanceStatus(instanceCode, authoritative, eventTime);
|
||||
else syncApprovalResult(instanceCode, authoritative, comment);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,12 +416,96 @@ public class FeishuApprovalService {
|
||||
* 处理审批任务变更事件
|
||||
*/
|
||||
private void handleTaskChange(Map<String, Object> eventData) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> task = (Map<String, Object>) eventData.get("task");
|
||||
Map<String, Object> task = nestedMap(eventData.get("task"));
|
||||
if (task == null && eventData.containsKey("instance_code")) task = eventData;
|
||||
if (task == null) return;
|
||||
if (eventStateService != null) { eventStateService.applyTask(task); return; }
|
||||
if (timelineNodeRepository == null) return;
|
||||
String instanceCode = text(task, "instance_code", "instanceCode");
|
||||
if (!StringUtils.hasText(instanceCode)) return;
|
||||
IntFeishuApproval approval = intFeishuApprovalRepository.findByFeishuInstanceCodeForUpdate(instanceCode)
|
||||
.orElseThrow(() -> new BusinessException("飞书审批映射尚未就绪", 503));
|
||||
|
||||
String instanceCode = (String) task.get("instance_code");
|
||||
log.info("审批任务变更: instanceCode={}", instanceCode);
|
||||
String taskId = text(task, "task_id", "taskId", "id");
|
||||
String nodeKey = text(task, "node_id", "nodeId", "node_key", "approval_node_id");
|
||||
String taskKey = StringUtils.hasText(taskId) ? "TASK:" + taskId
|
||||
: "ACTUAL:" + (StringUtils.hasText(nodeKey) ? nodeKey : "unknown");
|
||||
FeishuInstanceTimelineNode row = timelineNodeRepository
|
||||
.findByFeishuApprovalIdAndInstanceCodeAndTimelineKey(approval.getId(), instanceCode, taskKey).orElse(null);
|
||||
if (row == null && StringUtils.hasText(taskId)) {
|
||||
row = timelineNodeRepository.findByFeishuApprovalIdAndInstanceCodeAndTaskId(approval.getId(), instanceCode, taskId).orElse(null);
|
||||
}
|
||||
if (row == null && StringUtils.hasText(nodeKey)) {
|
||||
FeishuInstanceTimelineNode planned = timelineNodeRepository
|
||||
.findFirstByFeishuApprovalIdAndInstanceCodeAndNodeKeyOrderByIdAsc(approval.getId(), instanceCode, nodeKey).orElse(null);
|
||||
if (planned != null && !StringUtils.hasText(planned.getTaskId())) row = planned;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
if (row == null) {
|
||||
row = FeishuInstanceTimelineNode.builder().feishuApprovalId(approval.getId())
|
||||
.instanceCode(instanceCode).timelineKey(taskKey).nodeKey(nodeKey).planned(false).createdAt(now).build();
|
||||
}
|
||||
String incoming = normalizeTaskStatus(text(task, "status", "task_status", "taskStatus"));
|
||||
if (!wouldRegress(row.getStatus(), incoming) && incoming != null) row.setStatus(incoming);
|
||||
row.setTaskId(taskId);
|
||||
row.setPlanned(false);
|
||||
String nodeName = text(task, "node_name", "nodeName", "name");
|
||||
if (StringUtils.hasText(nodeName)) row.setNodeName(nodeName);
|
||||
String approver = text(task, "approver_name", "user_name", "approver", "operator_name");
|
||||
Map<String, Object> user = nestedMap(task.get("user"));
|
||||
if (!StringUtils.hasText(approver) && user != null) approver = text(user, "name", "en_name");
|
||||
if (StringUtils.hasText(approver)) row.setApproverLabel(approver);
|
||||
String comment = text(task, "comment", "opinion", "reason");
|
||||
if (comment != null) row.setComment(comment);
|
||||
LocalDateTime actionTime = parseTime(firstValue(task, "action_time", "end_time", "update_time", "create_time"));
|
||||
if (actionTime != null && (row.getActionTime() == null || !actionTime.isBefore(row.getActionTime()))) {
|
||||
row.setActionTime(actionTime);
|
||||
}
|
||||
row.setUpdatedAt(now);
|
||||
timelineNodeRepository.save(row);
|
||||
log.info("飞书审批任务进度已更新: status={}", row.getStatus());
|
||||
}
|
||||
|
||||
private Object firstValue(Map<String, Object> map, String... keys) {
|
||||
for (String key : keys) if (map.get(key) != null) return map.get(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
private String text(Map<String, Object> map, String... keys) {
|
||||
Object value = firstValue(map, keys);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
private String normalizeTaskStatus(String status) {
|
||||
if (!StringUtils.hasText(status)) return null;
|
||||
String value = status.trim().toUpperCase(Locale.ROOT);
|
||||
if ("CANCELED".equals(value)) return "CANCELLED";
|
||||
if ("DONE".equals(value) || "COMPLETED".equals(value) || "PASS".equals(value)) return "APPROVED";
|
||||
return value.length() <= 50 ? value : null;
|
||||
}
|
||||
|
||||
private boolean wouldRegress(String current, String incoming) {
|
||||
if (incoming == null) return true;
|
||||
return isTerminalTask(current) && !isTerminalTask(incoming);
|
||||
}
|
||||
|
||||
private boolean isTerminalTask(String status) {
|
||||
return "APPROVED".equals(status) || "REJECTED".equals(status)
|
||||
|| "CANCELLED".equals(status) || "TRANSFERRED".equals(status);
|
||||
}
|
||||
|
||||
private LocalDateTime parseTime(Object value) {
|
||||
if (value == null) return null;
|
||||
try {
|
||||
if (value instanceof Number || String.valueOf(value).matches("\\d+")) {
|
||||
long epoch = Long.parseLong(String.valueOf(value));
|
||||
if (epoch > 100000000000L) epoch /= 1000L;
|
||||
return LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(epoch), java.time.ZoneOffset.UTC);
|
||||
}
|
||||
return LocalDateTime.parse(String.valueOf(value));
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String approvalCode() {
|
||||
@@ -411,16 +519,6 @@ public class FeishuApprovalService {
|
||||
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;
|
||||
@@ -442,8 +540,4 @@ public class FeishuApprovalService {
|
||||
|| ApprovalStatus.CANCELLED.name().equals(status);
|
||||
}
|
||||
|
||||
private boolean isRetryableTerminal(String status) {
|
||||
return ApprovalStatus.REJECTED.name().equals(status)
|
||||
|| ApprovalStatus.CANCELLED.name().equals(status);
|
||||
}
|
||||
}
|
||||
@@ -173,12 +173,12 @@ public class FeishuAuthService {
|
||||
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.getCode() != 0) throw new BusinessException("飞书授权失败,请稍后重试");
|
||||
if (tokenResponse.getData() == null || !StringUtils.hasText(tokenResponse.getData().getAccessToken()))
|
||||
throw new BusinessException("飞书授权未返回有效令牌");
|
||||
return tokenResponse;
|
||||
} catch (Exception e) {
|
||||
log.error("飞书获取access_token失败", e);
|
||||
log.warn("Feishu OAuth token exchange failed");
|
||||
throw new BusinessException("飞书授权失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
@@ -198,9 +198,8 @@ public class FeishuAuthService {
|
||||
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());
|
||||
}
|
||||
if (userResponse == null || userResponse.getCode() != 0 || userResponse.getData() == null)
|
||||
throw new BusinessException("获取用户信息失败");
|
||||
|
||||
FeishuUserInfo userInfo = new FeishuUserInfo();
|
||||
userInfo.setOpenId(userResponse.getData().getOpenId());
|
||||
@@ -211,7 +210,7 @@ public class FeishuAuthService {
|
||||
userInfo.setMobile(userResponse.getData().getMobile());
|
||||
return userInfo;
|
||||
} catch (Exception e) {
|
||||
log.error("获取飞书用户信息失败", e);
|
||||
log.warn("Feishu OAuth user-info request failed");
|
||||
throw new BusinessException("获取用户信息失败");
|
||||
}
|
||||
}
|
||||
@@ -294,7 +293,7 @@ public class FeishuAuthService {
|
||||
.build();
|
||||
SysUser saved = sysUserRepository.save(user);
|
||||
if (saved != null) user = saved;
|
||||
log.info("自动创建 Feishu EMPLOYEE 用户: openId={}, employeeNo={}, name={}", openId, number, user.getRealName());
|
||||
log.info("Feishu OAuth provisioned an employee account");
|
||||
// Flush so the subsequent lookup sees the new record
|
||||
sysUserRepository.flush();
|
||||
return user;
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.finance.system.entity.FeishuDefinitionSyncFence;
|
||||
import com.finance.system.repository.FeishuDefinitionSyncFenceRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FeishuDefinitionGenerationService {
|
||||
private final FeishuDefinitionSyncFenceRepository fences;
|
||||
|
||||
@Transactional
|
||||
public long reserve() {
|
||||
FeishuDefinitionSyncFence fence = fences.findByIdForUpdate(FeishuDefinitionSyncFence.SINGLETON_ID)
|
||||
.orElseGet(() -> FeishuDefinitionSyncFence.builder()
|
||||
.id(FeishuDefinitionSyncFence.SINGLETON_ID).generation(0L).build());
|
||||
long generation = fence.getGeneration() + 1;
|
||||
fence.setGeneration(generation);
|
||||
fences.save(fence);
|
||||
return generation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.finance.system.util.Sha256;
|
||||
import lombok.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Converts the known v1/v2 approval-definition envelopes into one stable model. */
|
||||
@Component
|
||||
public class FeishuDefinitionNormalizer {
|
||||
private static final int MAX_NODES = 100;
|
||||
private static final int MAX_APPROVERS = 50;
|
||||
|
||||
public NormalizedDefinition normalize(JsonNode response, String configuredApprovalCode) {
|
||||
JsonNode data = response == null ? null : response.path("data");
|
||||
if (data == null || data.isMissingNode() || data.isNull()) data = response;
|
||||
JsonNode nodesJson = findNodeArray(data, 0);
|
||||
if (nodesJson == null || !nodesJson.isArray() || nodesJson.size() == 0) {
|
||||
throw new IllegalArgumentException("Feishu approval definition has no usable nodes");
|
||||
}
|
||||
String code = displayText(findDeep(data, 0, "approval_code", "approvalCode"));
|
||||
if (!StringUtils.hasText(code)) code = configuredApprovalCode;
|
||||
if (!StringUtils.hasText(code)) throw new IllegalArgumentException("Feishu approval code is missing");
|
||||
String name = displayText(findDeep(data, 0, "approval_name", "approvalName"));
|
||||
code = bounded(code, 200);
|
||||
name = bounded(name, 300);
|
||||
|
||||
List<NormalizedNode> nodes = new ArrayList<>();
|
||||
int order = 1;
|
||||
for (JsonNode raw : nodesJson) {
|
||||
if (order > MAX_NODES) throw new IllegalArgumentException("too many Feishu approval nodes");
|
||||
if (!raw.isObject()) continue;
|
||||
String key = firstText(raw, "node_id", "nodeId", "id", "key", "node_key");
|
||||
if (!StringUtils.hasText(key)) key = "node-" + order;
|
||||
key = bounded(key, 300);
|
||||
String nodeName = displayText(first(raw, "node_name", "nodeName", "name", "title"));
|
||||
if (!StringUtils.hasText(nodeName)) nodeName = "审批节点 " + order;
|
||||
nodeName = bounded(nodeName, 300);
|
||||
String rawType = firstText(raw, "node_type", "nodeType", "type");
|
||||
String mode = firstText(raw, "approval_mode", "approvalMode", "mode");
|
||||
if (!StringUtils.hasText(mode) && ("AND".equalsIgnoreCase(rawType) || "OR".equalsIgnoreCase(rawType))) {
|
||||
mode = rawType.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
List<NormalizedApprover> approvers = normalizeApprovers(raw);
|
||||
boolean dynamic = isDynamicNode(raw, approvers);
|
||||
if (approvers.isEmpty()) {
|
||||
approvers.add(new NormalizedApprover("FEISHU", null,
|
||||
"提交时由飞书解析", true));
|
||||
dynamic = true;
|
||||
}
|
||||
nodes.add(new NormalizedNode(order++, key, nodeName, bounded(rawType, 80), bounded(mode, 80), dynamic, approvers));
|
||||
}
|
||||
if (nodes.isEmpty()) throw new IllegalArgumentException("Feishu approval definition has no usable nodes");
|
||||
NormalizedDefinition definition = new NormalizedDefinition(code, name, nodes, null);
|
||||
definition.setFingerprint(fingerprint(definition));
|
||||
return definition;
|
||||
}
|
||||
|
||||
private List<NormalizedApprover> normalizeApprovers(JsonNode node) {
|
||||
JsonNode values = first(node, "approvers", "approver", "approver_list", "approverList", "assignees");
|
||||
List<NormalizedApprover> result = new ArrayList<>();
|
||||
if (values == null) return result;
|
||||
Iterable<JsonNode> iterable = values.isArray() ? values : Collections.singletonList(values);
|
||||
for (JsonNode value : iterable) {
|
||||
if (result.size() >= MAX_APPROVERS) throw new IllegalArgumentException("too many Feishu approvers");
|
||||
if (value == null || value.isNull()) continue;
|
||||
if (value.isTextual()) {
|
||||
result.add(new NormalizedApprover("USER", value.asText(), value.asText(), false));
|
||||
continue;
|
||||
}
|
||||
String type = firstText(value, "type", "approver_type", "approverType");
|
||||
String ref = firstText(value, "user_id", "userId", "open_id", "role_id", "roleId", "id");
|
||||
String label = displayText(first(value, "name", "user_name", "role_name", "label", "title"));
|
||||
boolean dynamic = !isFixedPerson(type, ref);
|
||||
if (!StringUtils.hasText(label)) label = dynamic ? dynamicLabel(type) : "指定审批人";
|
||||
if (dynamic && !label.contains("提交时")) label += "(提交时由飞书解析)";
|
||||
result.add(new NormalizedApprover(bounded(type, 80), bounded(ref, 300), bounded(label, 300), dynamic));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean isDynamicNode(JsonNode node, List<NormalizedApprover> approvers) {
|
||||
String type = firstText(node, "node_type", "nodeType", "type");
|
||||
if (type != null && (type.toUpperCase(Locale.ROOT).contains("CONDITION")
|
||||
|| type.toUpperCase(Locale.ROOT).contains("ROUTE"))) return true;
|
||||
for (NormalizedApprover approver : approvers) if (approver.isDynamic()) return true;
|
||||
return node.has("condition") || node.has("conditions") || node.has("control");
|
||||
}
|
||||
|
||||
private boolean isFixedPerson(String type, String ref) {
|
||||
if (!StringUtils.hasText(ref)) return false;
|
||||
String normalized = type == null ? "" : type.toUpperCase(Locale.ROOT);
|
||||
return normalized.isEmpty() || normalized.contains("USER") || normalized.contains("PERSON");
|
||||
}
|
||||
|
||||
private String dynamicLabel(String type) {
|
||||
String value = type == null ? "" : type.toUpperCase(Locale.ROOT);
|
||||
if (value.contains("MANAGER") || value.contains("LEADER")) return "部门负责人";
|
||||
if (value.contains("ROLE")) return "角色审批人";
|
||||
if (value.contains("FREE")) return "发起人选择审批人";
|
||||
return "飞书动态审批人";
|
||||
}
|
||||
|
||||
private JsonNode findNodeArray(JsonNode node, int depth) {
|
||||
if (node == null || depth > 5) return null;
|
||||
for (String key : Arrays.asList("node_list", "nodeList", "approval_nodes", "approvalNodes", "nodes")) {
|
||||
JsonNode candidate = node.get(key);
|
||||
if (candidate != null && candidate.isArray()) return candidate;
|
||||
}
|
||||
for (String key : Arrays.asList("approval", "definition", "process", "flow", "approval_definition")) {
|
||||
JsonNode nested = node.get(key);
|
||||
JsonNode found = findNodeArray(nested, depth + 1);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private JsonNode findDeep(JsonNode node, int depth, String... names) {
|
||||
if (node == null || depth > 5) return null;
|
||||
JsonNode direct = first(node, names);
|
||||
if (direct != null) return direct;
|
||||
for (String key : Arrays.asList("approval", "definition", "process", "flow", "approval_definition")) {
|
||||
JsonNode found = findDeep(node.get(key), depth + 1, names);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String fingerprint(NormalizedDefinition definition) {
|
||||
StringBuilder canonical = new StringBuilder();
|
||||
append(canonical, definition.getApprovalCode());
|
||||
append(canonical, definition.getApprovalName());
|
||||
for (NormalizedNode node : definition.getNodes()) {
|
||||
append(canonical, String.valueOf(node.getOrder())); append(canonical, node.getNodeKey());
|
||||
append(canonical, node.getNodeName()); append(canonical, node.getNodeType());
|
||||
append(canonical, node.getApprovalMode()); append(canonical, String.valueOf(node.isDynamic()));
|
||||
for (NormalizedApprover approver : node.getApprovers()) {
|
||||
append(canonical, approver.getType()); append(canonical, approver.getRef());
|
||||
append(canonical, approver.getLabel()); append(canonical, String.valueOf(approver.isDynamic()));
|
||||
}
|
||||
}
|
||||
return Sha256.hex(canonical.toString());
|
||||
}
|
||||
|
||||
private void append(StringBuilder target, String value) {
|
||||
String safe = value == null ? "" : value;
|
||||
target.append(safe.length()).append(':').append(safe).append('|');
|
||||
}
|
||||
|
||||
private JsonNode first(JsonNode node, String... names) {
|
||||
if (node == null) return null;
|
||||
for (String name : names) {
|
||||
JsonNode value = node.get(name);
|
||||
if (value != null && !value.isNull() && !value.isMissingNode()) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String firstText(JsonNode node, String... names) { return displayText(first(node, names)); }
|
||||
|
||||
private String displayText(JsonNode value) {
|
||||
if (value == null || value.isNull()) return null;
|
||||
if (value.isValueNode()) return value.asText();
|
||||
for (String key : Arrays.asList("zh_cn", "zh-CN", "text", "value", "name")) {
|
||||
JsonNode nested = value.get(key);
|
||||
if (nested != null && nested.isValueNode()) return nested.asText();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String bounded(String value, int max) {
|
||||
return value == null ? null : value.substring(0, Math.min(max, value.length()));
|
||||
}
|
||||
|
||||
@Data @AllArgsConstructor
|
||||
public static class NormalizedDefinition {
|
||||
private String approvalCode;
|
||||
private String approvalName;
|
||||
private List<NormalizedNode> nodes;
|
||||
private String fingerprint;
|
||||
}
|
||||
@Data @AllArgsConstructor
|
||||
public static class NormalizedNode {
|
||||
private int order; private String nodeKey; private String nodeName; private String nodeType;
|
||||
private String approvalMode; private boolean dynamic; private List<NormalizedApprover> approvers;
|
||||
}
|
||||
@Data @AllArgsConstructor
|
||||
public static class NormalizedApprover {
|
||||
private String type; private String ref; private String label; private boolean dynamic;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.finance.system.adapter.feishu.FeishuDefinitionNormalizer.*;
|
||||
import com.finance.system.dto.FeishuDefinitionSyncResult;
|
||||
import com.finance.system.entity.*;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FeishuDefinitionSnapshotWriter {
|
||||
private final FeishuApprovalDefinitionSnapshotRepository snapshots;
|
||||
private final FeishuApprovalDefinitionNodeRepository nodes;
|
||||
private final FeishuApprovalDefinitionApproverRepository approvers;
|
||||
private final FeishuDefinitionSyncFenceRepository fences;
|
||||
|
||||
@Transactional
|
||||
public FeishuDefinitionSyncResult replace(NormalizedDefinition definition, LocalDateTime fetchedAt, long generation) {
|
||||
FeishuDefinitionSyncFence fence = fences.findByIdForUpdate(FeishuDefinitionSyncFence.SINGLETON_ID)
|
||||
.orElseThrow(() -> new IllegalStateException("definition sync fence missing"));
|
||||
if (!Objects.equals(fence.getGeneration(), generation)) {
|
||||
throw new BusinessException("本次同步已被更新的审批定义同步取代,请刷新后重试", 409);
|
||||
}
|
||||
FeishuApprovalDefinitionSnapshot current = snapshots
|
||||
.findById(FeishuApprovalDefinitionSnapshot.CURRENT_ID).orElse(null);
|
||||
if (current != null && definition.getFingerprint().equals(current.getFingerprint())) {
|
||||
current.setFetchedAt(fetchedAt);
|
||||
current.setUpdatedAt(fetchedAt);
|
||||
current.setApprovalCode(definition.getApprovalCode());
|
||||
current.setApprovalName(definition.getApprovalName());
|
||||
snapshots.save(current);
|
||||
return result(definition, fetchedAt, false);
|
||||
}
|
||||
|
||||
List<FeishuApprovalDefinitionNode> oldNodes = nodes
|
||||
.findBySnapshotIdOrderByNodeOrderAsc(FeishuApprovalDefinitionSnapshot.CURRENT_ID);
|
||||
List<Long> oldIds = new ArrayList<>();
|
||||
for (FeishuApprovalDefinitionNode node : oldNodes) oldIds.add(node.getId());
|
||||
if (!oldIds.isEmpty()) approvers.deleteByNodeIdIn(oldIds);
|
||||
nodes.deleteBySnapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID);
|
||||
|
||||
LocalDateTime createdAt = current == null ? fetchedAt : current.getCreatedAt();
|
||||
snapshots.save(FeishuApprovalDefinitionSnapshot.builder()
|
||||
.id(FeishuApprovalDefinitionSnapshot.CURRENT_ID)
|
||||
.approvalCode(definition.getApprovalCode()).approvalName(definition.getApprovalName())
|
||||
.fingerprint(definition.getFingerprint()).fetchedAt(fetchedAt)
|
||||
.createdAt(createdAt).updatedAt(fetchedAt).build());
|
||||
|
||||
for (NormalizedNode source : definition.getNodes()) {
|
||||
FeishuApprovalDefinitionNode node = nodes.saveAndFlush(FeishuApprovalDefinitionNode.builder()
|
||||
.snapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID).nodeOrder(source.getOrder())
|
||||
.nodeKey(source.getNodeKey()).nodeName(source.getNodeName()).nodeType(source.getNodeType())
|
||||
.approvalMode(source.getApprovalMode()).dynamic(source.isDynamic()).build());
|
||||
int order = 1;
|
||||
for (NormalizedApprover sourceApprover : source.getApprovers()) {
|
||||
approvers.save(FeishuApprovalDefinitionApprover.builder().nodeId(node.getId())
|
||||
.approverOrder(order++).approverType(sourceApprover.getType())
|
||||
.approverRef(sourceApprover.getRef()).approverLabel(sourceApprover.getLabel())
|
||||
.dynamic(sourceApprover.isDynamic()).build());
|
||||
}
|
||||
}
|
||||
return result(definition, fetchedAt, true);
|
||||
}
|
||||
|
||||
private FeishuDefinitionSyncResult result(NormalizedDefinition definition,
|
||||
LocalDateTime fetchedAt, boolean changed) {
|
||||
return FeishuDefinitionSyncResult.builder().fingerprint(definition.getFingerprint())
|
||||
.fetchedAt(fetchedAt).nodeCount(definition.getNodes().size()).changed(changed).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.finance.system.dto.FeishuDefinitionSyncResult;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FeishuDefinitionSyncService {
|
||||
private final FeishuApprovalService remote;
|
||||
private final FeishuDefinitionNormalizer normalizer;
|
||||
private final FeishuDefinitionSnapshotWriter writer;
|
||||
private final FeishuDefinitionGenerationService generations;
|
||||
|
||||
/** Network I/O intentionally completes before the transactional writer is entered. */
|
||||
public FeishuDefinitionSyncResult sync() {
|
||||
if (!remote.isApprovalEnabledAndConfigured()) {
|
||||
throw new BusinessException("飞书审批未配置,无法同步", 409);
|
||||
}
|
||||
long generation = generations.reserve();
|
||||
try {
|
||||
JsonNode response = remote.fetchApprovalDefinitionJson();
|
||||
FeishuDefinitionNormalizer.NormalizedDefinition definition =
|
||||
normalizer.normalize(response, remote.getConfiguredApprovalCode());
|
||||
return writer.replace(definition, LocalDateTime.now(), generation);
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
// The writer was never called (or its transaction rolled back), so the
|
||||
// last known-good snapshot remains available.
|
||||
throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502);
|
||||
}
|
||||
}
|
||||
}
|
||||
+388
-28
@@ -5,56 +5,416 @@ 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 org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
@Service
|
||||
public class FeishuDirectoryAccessService {
|
||||
private static final int MAX_CONCURRENT_CANDIDATE_SEARCHES = 8;
|
||||
private final FeishuTenantTokenService tokens;
|
||||
private final FeishuDirectorySettings settings;
|
||||
private final Environment environment;
|
||||
private final JdbcTemplate jdbc;
|
||||
private final FeishuDirectoryTime time;
|
||||
private final TransactionTemplate observation;
|
||||
private final TransactionTemplate candidateSearch;
|
||||
private final Semaphore candidateSearchPermits = new Semaphore(MAX_CONCURRENT_CANDIDATE_SEARCHES, true);
|
||||
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;
|
||||
org.springframework.transaction.PlatformTransactionManager manager, FeishuDirectoryTime time) {
|
||||
this.tokens = tokens; this.environment = environment; this.jdbc = jdbc; this.time = time;
|
||||
this.observation = new TransactionTemplate(manager);
|
||||
this.observation.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
this.observation.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
|
||||
this.observation.setTimeout(10);
|
||||
this.candidateSearch = new TransactionTemplate(manager);
|
||||
this.candidateSearch.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
this.candidateSearch.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
this.candidateSearch.setReadOnly(true);
|
||||
this.candidateSearch.setTimeout(30);
|
||||
}
|
||||
public boolean allowed(SysUser user) {
|
||||
if (user == null || !"ACTIVE".equalsIgnoreCase(user.getStatus())) return false;
|
||||
if (user == null) return false;
|
||||
if (Arrays.stream(environment.getActiveProfiles()).anyMatch("local"::equalsIgnoreCase)
|
||||
&& blank(user.getFeishuOpenId()) && blank(user.getFeishuUserId())) return true;
|
||||
&& blank(user.getFeishuOpenId()) && blank(user.getFeishuUserId()))
|
||||
return "ACTIVE".equalsIgnoreCase(user.getStatus());
|
||||
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; }
|
||||
if (user == null || user.getId() == null || jdbc == null) return false;
|
||||
DirectoryObservation captured=captureObservation(Collections.singleton(user.getId()));
|
||||
return directoryAllowed(user,captured);
|
||||
}
|
||||
public void requireAllowed(SysUser user) { if (!allowed(user)) throw denied(); }
|
||||
public void requireSynced(SysUser user) {
|
||||
if (!directoryAllowed(user) || user.getDirectoryLastSeenRunId() == null) throw denied();
|
||||
if (!directoryAllowed(user)) throw denied();
|
||||
}
|
||||
private boolean currentSnapshotMatches(SysUser user) {
|
||||
if (jdbc == null) return false;
|
||||
|
||||
/** For a caller whose current transaction already owns the directory singleton lock. */
|
||||
public boolean allowedUnderDirectoryLock(SysUser user) {
|
||||
if (user == null || user.getId() == null || jdbc == null) return false;
|
||||
Map<String,Object> state=com.finance.system.service.FeishuDirectoryLock.acquire(jdbc);
|
||||
java.util.List<Map<String,Object>> rows=authorizationRows(user.getId());
|
||||
if(rows.size()!=1)return false;
|
||||
Map<String,Object> current=rows.get(0);
|
||||
if(Arrays.stream(environment.getActiveProfiles()).anyMatch("local"::equalsIgnoreCase)
|
||||
&&blank(string(current.get("feishu_open_id")))&&blank(string(current.get("feishu_user_id"))))
|
||||
return "ACTIVE".equalsIgnoreCase(string(current.get("status")));
|
||||
return evaluateDirectory(state,current);
|
||||
}
|
||||
|
||||
/** Existing-transaction variant; never opens REQUIRES_NEW. */
|
||||
public boolean directoryAllowedUnderDirectoryLock(SysUser user) {
|
||||
if (user == null || user.getId() == null || jdbc == null) return false;
|
||||
Map<String,Object> state=com.finance.system.service.FeishuDirectoryLock.acquire(jdbc);
|
||||
java.util.List<Map<String,Object>> rows=authorizationRows(user.getId());
|
||||
return rows.size()==1&&evaluateDirectory(state,rows.get(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the published pointer and current account rows in one short,
|
||||
* non-locking transaction. Publication changes between either SELECT are
|
||||
* detected by the duplicated context/run identifiers and fail closed.
|
||||
*/
|
||||
public DirectoryObservation captureObservation(Collection<Long> userIds) {
|
||||
if (jdbc == null) return null;
|
||||
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; }
|
||||
return observation.execute(status -> {
|
||||
Map<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||
Map<Long,Map<String,Object>> usersById=new LinkedHashMap<>();
|
||||
List<Long> ids=new ArrayList<>();
|
||||
if(userIds!=null)for(Long id:userIds)if(id!=null&&!ids.contains(id))ids.add(id);
|
||||
if(!ids.isEmpty()){
|
||||
StringBuilder placeholders=new StringBuilder();
|
||||
for(int i=0;i<ids.size();i++){if(i>0)placeholders.append(',');placeholders.append('?');}
|
||||
String sql="SELECT id,status,feishu_open_id,feishu_user_id,directory_status,directory_context,directory_verified_at,directory_last_seen_run_id FROM sys_user WHERE id IN ("+placeholders+")";
|
||||
for(Map<String,Object> row:jdbc.queryForList(sql,ids.toArray())){
|
||||
Object id=row.get("id");
|
||||
if(id instanceof Number)usersById.put(((Number)id).longValue(),row);
|
||||
}
|
||||
}
|
||||
return new DirectoryObservation(state,usersById);
|
||||
});
|
||||
} catch (RuntimeException ignored) { return null; }
|
||||
}
|
||||
|
||||
public boolean directoryAllowed(SysUser user, DirectoryObservation captured) {
|
||||
if (user == null || user.getId() == null || captured == null) return false;
|
||||
Map<String,Object> current=captured.usersById.get(user.getId());
|
||||
return current!=null&&evaluateDirectory(captured.state,current);
|
||||
}
|
||||
|
||||
public void requireAllowedUnderDirectoryLock(SysUser user){if(!allowedUnderDirectoryLock(user))throw denied();}
|
||||
public void requireSyncedUnderDirectoryLock(SysUser user){if(!directoryAllowedUnderDirectoryLock(user))throw denied();}
|
||||
|
||||
private java.util.List<Map<String,Object>> authorizationRows(Long id){return jdbc.queryForList("SELECT id,status,feishu_open_id,feishu_user_id,directory_status,directory_context,directory_verified_at,directory_last_seen_run_id FROM sys_user WHERE id=?",id);}
|
||||
private boolean evaluateDirectory(Map<String,Object> state,Map<String,Object> current){
|
||||
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
|
||||
if(!publication.isAvailable()||current==null)return false;
|
||||
String context=publication.getSuccessfulContext();
|
||||
return "ACTIVE".equalsIgnoreCase(string(current.get("status")))&&!blank(string(current.get("feishu_open_id")))
|
||||
&&"ELIGIBLE".equalsIgnoreCase(string(current.get("directory_status")))
|
||||
&&context.equals(string(current.get("directory_context")))
|
||||
&&publication.getRevision().equals(string(current.get("directory_last_seen_run_id")));
|
||||
}
|
||||
|
||||
/** Compatibility state: every available publication is FRESH regardless of age or current configuration. */
|
||||
public String snapshotState() {
|
||||
return snapshotState(captureObservation(Collections.<Long>emptyList()));
|
||||
}
|
||||
|
||||
public String snapshotState(DirectoryObservation captured) {
|
||||
return captured==null ? "UNAVAILABLE"
|
||||
: FeishuDirectoryPublication.classify(captured.state,time).getSnapshotState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the atomic current directory. The revision and rows are read in
|
||||
* one bounded observation transaction. Any inability to capture that view
|
||||
* is represented as UNAVAILABLE rather than as an authoritative empty set.
|
||||
*/
|
||||
public CandidateSearch searchPublishedCandidates(Long targetGroupId, String normalizedQuery, int fetchLimit) {
|
||||
return searchPublishedCandidates(targetGroupId, normalizedQuery, fetchLimit, false);
|
||||
}
|
||||
|
||||
public CandidateSearch searchPublishedCandidates(Long targetGroupId, String normalizedQuery, int fetchLimit,
|
||||
boolean includeSensitiveFields) {
|
||||
if (jdbc == null || fetchLimit < 1) return CandidateSearch.unavailable();
|
||||
if (!candidateSearchPermits.tryAcquire()) return CandidateSearch.unavailable();
|
||||
String query = normalizedQuery == null ? "" : normalizedQuery.toLowerCase(Locale.ROOT);
|
||||
try {
|
||||
CandidateSearch result = candidateSearch.execute(status -> {
|
||||
Map<String,Object> state = jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||
FeishuDirectoryPublication publication = FeishuDirectoryPublication.classify(state,time);
|
||||
if (!publication.isAvailable()) return CandidateSearch.empty(publication);
|
||||
String generation = publication.getRevision();
|
||||
String context = publication.getSuccessfulContext();
|
||||
|
||||
// Directory-first: every valid row in the immutable published
|
||||
// generation is a candidate, independent of employment policy
|
||||
// and independent of whether a local account already exists.
|
||||
StringBuilder sql = new StringBuilder("SELECT gu.open_id,gu.user_id,gu.name,gu.employee_no,gu.eligible,")
|
||||
.append("open_owner.id AS open_owner_id,open_owner.status AS local_status,")
|
||||
.append("open_owner.feishu_user_id AS local_user_id,")
|
||||
.append("gm.group_id AS assigned_group_id ")
|
||||
.append("FROM feishu_directory_user gu ")
|
||||
.append("LEFT JOIN sys_user open_owner ON open_owner.feishu_open_id=gu.open_id ")
|
||||
.append("LEFT JOIN sys_user_group_member gm ON gm.user_id=open_owner.id ")
|
||||
.append("WHERE gu.context=? ");
|
||||
List<Object> args = new ArrayList<>();
|
||||
args.add(context);
|
||||
if (!blank(query)) {
|
||||
sql.append("AND ");
|
||||
appendCandidateSearchPredicate(sql, args, "%" + escapeLike(query) + "%", includeSensitiveFields);
|
||||
}
|
||||
if (!includeSensitiveFields) {
|
||||
// page.users readers may inspect already-provisioned local
|
||||
// people, but cannot enumerate the tenant directory.
|
||||
sql.append("AND open_owner.id IS NOT NULL ")
|
||||
.append("AND (gu.user_id IS NULL OR TRIM(gu.user_id)='' OR open_owner.feishu_user_id IS NULL ")
|
||||
.append("OR TRIM(open_owner.feishu_user_id)='' OR open_owner.feishu_user_id=gu.user_id) ");
|
||||
}
|
||||
sql.append("AND (gm.group_id IS NULL OR gm.group_id<>?) ")
|
||||
.append("ORDER BY CASE WHEN gm.group_id IS NULL THEN 0 ELSE 1 END,gu.open_id LIMIT ?");
|
||||
args.add(targetGroupId); args.add(fetchLimit);
|
||||
List<Map<String,Object>> rows = jdbc.queryForList(sql.toString(), args.toArray());
|
||||
Map<String,List<String>> departments = currentDepartments(rows);
|
||||
Map<String,DirectoryCandidate> candidates = new LinkedHashMap<>();
|
||||
for (Map<String,Object> row : rows) {
|
||||
String openId = string(row.get("open_id"));
|
||||
String userId = nullable(row.get("user_id"));
|
||||
Long openOwner = nullableLong(row.get("open_owner_id"));
|
||||
String counterpart = nullable(row.get("local_user_id"));
|
||||
boolean conflict = openOwner != null && !blank(counterpart)&&!blank(userId)&&!userId.equals(counterpart);
|
||||
candidates.putIfAbsent(openId, new DirectoryCandidate(conflict ? null : openOwner, string(row.get("name")),
|
||||
nullable(row.get("employee_no")), departments.getOrDefault(openId, Collections.<String>emptyList()),
|
||||
booleanValue(row.get("eligible")), nullableLong(row.get("assigned_group_id")),
|
||||
generation, openId, userId, nullable(row.get("local_status")), conflict));
|
||||
}
|
||||
Map<String,Object> finalState = jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||
if (!publicationStable(state, finalState)
|
||||
|| !generation.equals(string(finalState.get("last_successful_run_id")))) {
|
||||
return CandidateSearch.unavailable();
|
||||
}
|
||||
return new CandidateSearch(publication, new ArrayList<>(candidates.values()), context, false);
|
||||
});
|
||||
if (result == null) return CandidateSearch.unavailable();
|
||||
if (result.additionsAllowed && !revalidatePublishedCandidateSnapshot(result)) {
|
||||
return CandidateSearch.unavailable();
|
||||
}
|
||||
result.contextState = contextState(result.context);
|
||||
return result;
|
||||
} catch (RuntimeException ignored) {
|
||||
return CandidateSearch.unavailable();
|
||||
} finally {
|
||||
// The permit covers both snapshot transaction and post-transaction
|
||||
// revalidation and must be returned for every failure path.
|
||||
candidateSearchPermits.release();
|
||||
}
|
||||
}
|
||||
|
||||
/** Revalidate outside REPEATABLE_READ so a publication committed during the scan is observable. */
|
||||
private boolean revalidatePublishedCandidateSnapshot(CandidateSearch captured) {
|
||||
Boolean stable = observation.execute(status -> {
|
||||
Map<String,Object> current = jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||
return captured.generation.equals(string(current.get("last_successful_run_id")))
|
||||
&& captured.context.equals(string(current.get("successful_context")))
|
||||
&& java.util.Objects.equals(captured.successfulAt,
|
||||
time.instant(current.get("last_successful_at")));
|
||||
});
|
||||
return Boolean.TRUE.equals(stable);
|
||||
}
|
||||
|
||||
private Map<String,List<String>> currentDepartments(List<Map<String,Object>> users) {
|
||||
Set<String> openIds = new LinkedHashSet<>();
|
||||
for (Map<String,Object> user : users) {
|
||||
String open = string(user.get("open_id"));
|
||||
if (!blank(open)) openIds.add(open);
|
||||
}
|
||||
if (openIds.isEmpty()) return Collections.emptyMap();
|
||||
StringBuilder placeholders = new StringBuilder();
|
||||
List<Object> args = new ArrayList<>();
|
||||
for (String open : openIds) {
|
||||
if (placeholders.length() > 0) placeholders.append(',');
|
||||
placeholders.append('?'); args.add(open);
|
||||
}
|
||||
String sql = "SELECT gud.open_id,gd.name FROM feishu_directory_user_department gud "
|
||||
+ "JOIN feishu_directory_department gd ON gd.open_department_id=gud.open_department_id WHERE gud.open_id IN ("
|
||||
+ placeholders + ") ORDER BY gd.sort_order,gd.open_department_id";
|
||||
Map<String,List<String>> result = new LinkedHashMap<>();
|
||||
for (Map<String,Object> row : jdbc.queryForList(sql, args.toArray())) {
|
||||
result.computeIfAbsent(string(row.get("open_id")), key -> new ArrayList<>()).add(string(row.get("name")));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String escapeLike(String value) {
|
||||
return value.replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||
}
|
||||
private static void appendCandidateSearchPredicate(StringBuilder sql, List<Object> args, String like,
|
||||
boolean includeSensitiveFields) {
|
||||
sql.append("(LOWER(gu.name) LIKE ? ESCAPE '!' ");
|
||||
args.add(like);
|
||||
if (includeSensitiveFields) {
|
||||
sql.append("OR LOWER(gu.open_id) LIKE ? ESCAPE '!' ")
|
||||
.append("OR LOWER(gu.mobile) LIKE ? ESCAPE '!' ");
|
||||
args.add(like); args.add(like);
|
||||
}
|
||||
sql.append("OR LOWER(gu.employee_no) LIKE ? ESCAPE '!' OR EXISTS (SELECT 1 ")
|
||||
.append("FROM feishu_directory_user_department gud ")
|
||||
.append("JOIN feishu_directory_department gd ON gd.open_department_id=gud.open_department_id ")
|
||||
.append("WHERE gud.open_id=gu.open_id AND LOWER(gd.name) LIKE ? ESCAPE '!')) ");
|
||||
args.add(like); args.add(like);
|
||||
}
|
||||
private static String nullable(Object value) { return value == null ? null : String.valueOf(value); }
|
||||
private static Long nullableLong(Object value) { return value instanceof Number ? ((Number) value).longValue() : null; }
|
||||
private static boolean booleanValue(Object value) {
|
||||
return Boolean.TRUE.equals(value) || value instanceof Number && ((Number) value).intValue() != 0
|
||||
|| "true".equalsIgnoreCase(String.valueOf(value));
|
||||
}
|
||||
private static int intValue(Object value) { return value instanceof Number ? ((Number) value).intValue() : 0; }
|
||||
private boolean publicationStable(Map<String,Object> before, Map<String,Object> after) {
|
||||
if (before == null || after == null) return false;
|
||||
for (String key : Arrays.asList("last_successful_run_id", "successful_context")) {
|
||||
if (!string(before.get(key)).equals(string(after.get(key)))) return false;
|
||||
}
|
||||
Instant beforeAt = time.instant(before.get("last_successful_at"));
|
||||
Instant afterAt = time.instant(after.get("last_successful_at"));
|
||||
return java.util.Objects.equals(beforeAt, afterAt);
|
||||
}
|
||||
|
||||
/** Current configuration is diagnostic only and never participates in a directory decision. */
|
||||
private String contextState(String successfulContext) {
|
||||
if (blank(successfulContext) || tokens == null) return "UNKNOWN";
|
||||
try {
|
||||
String current = tokens.capture().fingerprint;
|
||||
return successfulContext.equals(current) ? "MATCH" : "CHANGED";
|
||||
} catch (RuntimeException ignored) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
public static final class CandidateSearch {
|
||||
private final String snapshotState;
|
||||
private final String availabilityState;
|
||||
private final boolean additionsAllowed;
|
||||
private final List<DirectoryCandidate> candidates;
|
||||
private final String generation;
|
||||
private final String currentRevision;
|
||||
private final String context;
|
||||
private final Instant successfulAt;
|
||||
private final boolean blockedMatchesPresent;
|
||||
private String contextState;
|
||||
private CandidateSearch(String snapshotState, List<DirectoryCandidate> candidates) {
|
||||
this(snapshotState, candidates, null, null, null, false);
|
||||
}
|
||||
private CandidateSearch(String snapshotState, List<DirectoryCandidate> candidates,
|
||||
String generation, String context, Instant successfulAt,
|
||||
boolean blockedMatchesPresent) {
|
||||
this.snapshotState = snapshotState;
|
||||
this.availabilityState = "FRESH".equals(snapshotState) ? "AVAILABLE"
|
||||
: "NEVER_SYNCED".equals(snapshotState) ? "NEVER_SYNCED" : "UNAVAILABLE";
|
||||
this.additionsAllowed = "AVAILABLE".equals(availabilityState);
|
||||
this.candidates = Collections.unmodifiableList(new ArrayList<>(candidates));
|
||||
this.generation = generation;
|
||||
this.currentRevision = generation;
|
||||
this.context = context;
|
||||
this.successfulAt = successfulAt;
|
||||
this.blockedMatchesPresent = blockedMatchesPresent;
|
||||
this.contextState = "UNKNOWN";
|
||||
}
|
||||
private CandidateSearch(FeishuDirectoryPublication publication, List<DirectoryCandidate> candidates,
|
||||
String context, boolean blockedMatchesPresent) {
|
||||
this(publication.getSnapshotState(), candidates, publication.getRevision(), context,
|
||||
publication.getSuccessfulAt(), blockedMatchesPresent);
|
||||
}
|
||||
private static CandidateSearch empty(FeishuDirectoryPublication publication) {
|
||||
return new CandidateSearch(publication, Collections.<DirectoryCandidate>emptyList(), null, false);
|
||||
}
|
||||
private static CandidateSearch empty(String state) { return new CandidateSearch(state, Collections.<DirectoryCandidate>emptyList()); }
|
||||
private static CandidateSearch unavailable() { return empty("UNAVAILABLE"); }
|
||||
public static CandidateSearch of(String state, List<DirectoryCandidate> candidates) {
|
||||
return new CandidateSearch(state, candidates == null
|
||||
? Collections.<DirectoryCandidate>emptyList() : candidates);
|
||||
}
|
||||
public static CandidateSearch of(String state, List<DirectoryCandidate> candidates,
|
||||
boolean blockedMatchesPresent) {
|
||||
return new CandidateSearch(state, candidates == null
|
||||
? Collections.<DirectoryCandidate>emptyList() : candidates,
|
||||
null, null, null, blockedMatchesPresent);
|
||||
}
|
||||
public String getSnapshotState() { return snapshotState; }
|
||||
public String getAvailabilityState() { return availabilityState; }
|
||||
public boolean isAdditionsAllowed() { return additionsAllowed; }
|
||||
public String getCurrentRevision() { return currentRevision; }
|
||||
public String getContextState() { return contextState; }
|
||||
public List<DirectoryCandidate> getCandidates() { return candidates; }
|
||||
public boolean isBlockedMatchesPresent() { return blockedMatchesPresent; }
|
||||
}
|
||||
|
||||
public static final class DirectoryCandidate {
|
||||
private final Long localUserId;
|
||||
private final String name;
|
||||
private final String employeeNo;
|
||||
private final List<String> departmentNames;
|
||||
private final boolean eligible;
|
||||
private final Long assignedGroupId;
|
||||
private final String generationId;
|
||||
private final String openId;
|
||||
private final String userId;
|
||||
private final String localStatus;
|
||||
private final boolean identityConflict;
|
||||
public DirectoryCandidate(Long localUserId, String name, String employeeNo,
|
||||
List<String> departmentNames, boolean eligible) {
|
||||
this(localUserId, name, employeeNo, departmentNames, eligible, null);
|
||||
}
|
||||
public DirectoryCandidate(Long localUserId, String name, String employeeNo,
|
||||
List<String> departmentNames, boolean eligible, Long assignedGroupId) {
|
||||
this(localUserId, name, employeeNo, departmentNames, eligible, assignedGroupId,
|
||||
null, null, null, localUserId == null ? null : "ACTIVE", false);
|
||||
}
|
||||
public DirectoryCandidate(Long localUserId, String name, String employeeNo,
|
||||
List<String> departmentNames, boolean eligible, Long assignedGroupId,
|
||||
String generationId, String openId, String userId,
|
||||
String localStatus, boolean identityConflict) {
|
||||
this.localUserId=localUserId; this.name=name; this.employeeNo=employeeNo;
|
||||
this.departmentNames=Collections.unmodifiableList(new ArrayList<>(departmentNames)); this.eligible=eligible;
|
||||
this.assignedGroupId=assignedGroupId;
|
||||
this.generationId=generationId; this.openId=openId; this.userId=userId;
|
||||
this.localStatus=localStatus; this.identityConflict=identityConflict;
|
||||
}
|
||||
public Long getLocalUserId() { return localUserId; }
|
||||
public String getName() { return name; }
|
||||
public String getEmployeeNo() { return employeeNo; }
|
||||
public List<String> getDepartmentNames() { return departmentNames; }
|
||||
public boolean isEligible() { return eligible; }
|
||||
public Long getAssignedGroupId() { return assignedGroupId; }
|
||||
public String getGenerationId() { return generationId; }
|
||||
public String getOpenId() { return openId; }
|
||||
public String getUserId() { return userId; }
|
||||
public String getLocalStatus() { return localStatus; }
|
||||
public boolean isIdentityConflict() { return identityConflict; }
|
||||
}
|
||||
|
||||
private static String string(Object value){return value==null?"":String.valueOf(value);}
|
||||
|
||||
public static final class DirectoryObservation {
|
||||
private final Map<String,Object> state;
|
||||
private final Map<Long,Map<String,Object>> usersById;
|
||||
private DirectoryObservation(Map<String,Object> state,Map<Long,Map<String,Object>> usersById){
|
||||
this.state=state;this.usersById=usersById;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean blank(String value) { return value == null || value.trim().isEmpty(); }
|
||||
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.finance.system.dto.DirectoryIdentityDto;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import com.finance.system.service.FeishuDirectoryLock;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.PreparedStatementCreator;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Resolves published directory identities to ordinary local accounts. This
|
||||
* component deliberately has no independent transaction boundary: account
|
||||
* provisioning and group membership replacement commit or roll back together.
|
||||
*/
|
||||
@Service
|
||||
public class FeishuDirectoryBindingProvisioner {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final FeishuDirectoryTime time;
|
||||
public FeishuDirectoryBindingProvisioner(JdbcTemplate jdbc, FeishuDirectoryTime time) {
|
||||
this.jdbc = jdbc;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public List<Long> resolveForExplicitBinding(Collection<DirectoryIdentityDto> identities) {
|
||||
if (identities == null || identities.isEmpty()) return Collections.emptyList();
|
||||
try {
|
||||
Map<String,Object> state = FeishuDirectoryLock.acquire(jdbc);
|
||||
FeishuDirectoryPublication publication = FeishuDirectoryPublication.classify(state, time);
|
||||
if (!publication.isAvailable()) throw conflict();
|
||||
String generation = publication.getRevision();
|
||||
String context = publication.getSuccessfulContext();
|
||||
LinkedHashSet<Long> resolved = new LinkedHashSet<>();
|
||||
for (DirectoryIdentityDto identity : identities) {
|
||||
if (identity == null || !generation.equals(identity.getRevision())) throw conflict();
|
||||
resolved.add(resolveOne(identity, generation, context));
|
||||
}
|
||||
if (resolved.size() != identities.size()) throw conflict();
|
||||
return new ArrayList<>(resolved);
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (DataIntegrityViolationException ex) {
|
||||
throw conflict();
|
||||
} catch (RuntimeException ex) {
|
||||
throw conflict();
|
||||
}
|
||||
}
|
||||
|
||||
private Long resolveOne(DirectoryIdentityDto identity, String generation, String context) {
|
||||
List<Map<String,Object>> directoryRows = jdbc.queryForList(
|
||||
"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible "
|
||||
+ "FROM feishu_directory_user WHERE context=? AND snapshot_run_id=? "
|
||||
+ "AND open_id=? FOR UPDATE",
|
||||
context, generation, identity.getOpenId());
|
||||
if (directoryRows.size() != 1) throw conflict();
|
||||
Map<String,Object> directory = directoryRows.get(0);
|
||||
|
||||
List<Map<String,Object>> accountRows = jdbc.queryForList(
|
||||
"SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user "
|
||||
+ "WHERE feishu_open_id=? FOR UPDATE", identity.getOpenId());
|
||||
Map<String,Object> openOwner = null;
|
||||
for (Map<String,Object> row : accountRows) {
|
||||
if (identity.getOpenId().equals(value(row.get("feishu_open_id")))) openOwner = row;
|
||||
}
|
||||
String legacyRequest=identity.getUserId(), legacyRow=value(directory.get("user_id"));
|
||||
if(!blank(legacyRequest)&&!blank(legacyRow)&&!legacyRequest.equals(legacyRow))throw conflict();
|
||||
|
||||
// Lock/check every supplied or published identity, not only the open id.
|
||||
// A legacy id owned by another account is an ownership conflict even when
|
||||
// the compatibility assertion was omitted by the request.
|
||||
LinkedHashSet<String> legacyIds=new LinkedHashSet<>();
|
||||
if(!blank(legacyRow))legacyIds.add(legacyRow);
|
||||
if(!blank(legacyRequest))legacyIds.add(legacyRequest);
|
||||
for(String legacyId:legacyIds){
|
||||
List<Map<String,Object>> owners=jdbc.queryForList(
|
||||
"SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user WHERE feishu_user_id=? FOR UPDATE",
|
||||
legacyId);
|
||||
for(Map<String,Object> owner:owners){
|
||||
if(openOwner==null||!Objects.equals(number(openOwner.get("id")),number(owner.get("id"))))throw conflict();
|
||||
}
|
||||
}
|
||||
|
||||
if (openOwner != null) {
|
||||
String counterpart = value(openOwner.get("feishu_user_id"));
|
||||
if (!blank(counterpart)&&!blank(legacyRow)&&!legacyRow.equals(counterpart)) throw conflict();
|
||||
if (!blank(counterpart)&&!blank(legacyRequest)&&!legacyRequest.equals(counterpart)) throw conflict();
|
||||
if (!"ACTIVE".equalsIgnoreCase(value(openOwner.get("status")))) throw conflict();
|
||||
Long id = number(openOwner.get("id"));
|
||||
if (id == null) throw conflict();
|
||||
return id;
|
||||
}
|
||||
return insertOrdinaryAccount(directory, generation, context);
|
||||
}
|
||||
|
||||
private Long insertOrdinaryAccount(Map<String,Object> row, String generation, String context) {
|
||||
String openId = bounded(value(row.get("open_id")), 100, null);
|
||||
String name = bounded(value(row.get("name")), 100, openId);
|
||||
if (blank(openId) || blank(name)) throw conflict();
|
||||
String rawEmployee = value(row.get("employee_no"));
|
||||
String requestedEmployee = blank(rawEmployee) || rawEmployee.trim().length() > 50
|
||||
? null : rawEmployee.trim();
|
||||
String employee = availableEmployeeNo(requestedEmployee) ? requestedEmployee : generatedEmployeeNo();
|
||||
String directoryStatus = bool(row.get("eligible")) ? "ELIGIBLE" : "INELIGIBLE";
|
||||
Timestamp observed = Timestamp.from(Instant.now());
|
||||
|
||||
for (int attempt = 0; attempt < 5; attempt++) {
|
||||
final String number = employee;
|
||||
KeyHolder key = new GeneratedKeyHolder();
|
||||
PreparedStatementCreator insert = connection -> {
|
||||
PreparedStatement statement = connection.prepareStatement(
|
||||
"INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,avatar_url,email,mobile,position,"
|
||||
+ "user_type,password_hash,status,directory_status,directory_context,directory_verified_at,"
|
||||
+ "directory_last_seen_run_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,'EMPLOYEE',NULL,'ACTIVE',?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
|
||||
Statement.RETURN_GENERATED_KEYS);
|
||||
int index = 1;
|
||||
statement.setString(index++, openId); statement.setString(index++, null);
|
||||
statement.setString(index++, number); statement.setString(index++, name);
|
||||
statement.setString(index++, boundedNullable(value(row.get("avatar_url")), 500));
|
||||
statement.setString(index++, boundedNullable(value(row.get("email")), 200));
|
||||
statement.setString(index++, boundedNullable(value(row.get("mobile")), 20));
|
||||
statement.setString(index++, boundedNullable(value(row.get("job_title")), 200));
|
||||
statement.setString(index++, directoryStatus); statement.setString(index++, context);
|
||||
statement.setTimestamp(index++, observed); statement.setString(index, generation);
|
||||
return statement;
|
||||
};
|
||||
try {
|
||||
jdbc.update(insert, key);
|
||||
if (key.getKey() == null) throw conflict();
|
||||
return key.getKey().longValue();
|
||||
} catch (DataIntegrityViolationException collision) {
|
||||
// A candidate employee number may collide. Retry only when the
|
||||
// immutable identities are still unowned; identity races fail.
|
||||
if (identityExists(openId)) throw conflict();
|
||||
employee = generatedEmployeeNo();
|
||||
}
|
||||
}
|
||||
throw conflict();
|
||||
}
|
||||
|
||||
private boolean identityExists(String openId) {
|
||||
Integer count = jdbc.queryForObject(
|
||||
"SELECT COUNT(*) FROM sys_user WHERE feishu_open_id=?", Integer.class, openId);
|
||||
return count == null || count != 0;
|
||||
}
|
||||
|
||||
private boolean availableEmployeeNo(String number) {
|
||||
if (blank(number)) return false;
|
||||
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE employee_no=?", Integer.class, number);
|
||||
return count != null && count == 0;
|
||||
}
|
||||
|
||||
private String generatedEmployeeNo() {
|
||||
for (int attempt = 0; attempt < 10; attempt++) {
|
||||
String number = "FS-" + UUID.randomUUID();
|
||||
if (availableEmployeeNo(number)) return number;
|
||||
}
|
||||
throw conflict();
|
||||
}
|
||||
|
||||
private static Long number(Object value) { return value instanceof Number ? ((Number)value).longValue() : null; }
|
||||
private static boolean bool(Object value) {
|
||||
return Boolean.TRUE.equals(value) || value instanceof Number && ((Number)value).intValue() != 0
|
||||
|| "true".equalsIgnoreCase(String.valueOf(value));
|
||||
}
|
||||
private static String value(Object value) { return value == null ? null : String.valueOf(value); }
|
||||
private static boolean blank(String value) { return value == null || value.trim().isEmpty(); }
|
||||
private static String boundedNullable(String value, int max) {
|
||||
if (blank(value)) return null;
|
||||
String trimmed = value.trim();
|
||||
return trimmed.length() <= max ? trimmed : trimmed.substring(0, max);
|
||||
}
|
||||
private static String bounded(String value, int max, String fallback) {
|
||||
String result = boundedNullable(value, max);
|
||||
if (result == null) result = boundedNullable(fallback, max);
|
||||
return result;
|
||||
}
|
||||
private static BusinessException conflict() {
|
||||
return new BusinessException("目录身份或成员状态已变更,请刷新后重试", 409);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
@@ -0,0 +1,73 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.finance.system.util.Sha256;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.*;
|
||||
|
||||
/** Differential persistence for the single, transactionally published directory. */
|
||||
@Component
|
||||
public class FeishuDirectoryCurrentStore {
|
||||
static final int MAX_DIRECT_MEMBERSHIPS=500_000, MAX_EXPANDED_MEMBERSHIPS=1_000_000, WRITE_BATCH_SIZE=1_000;
|
||||
private final JdbcTemplate jdbc; private final int maxDirect,maxExpanded,batchSize;
|
||||
@Autowired public FeishuDirectoryCurrentStore(JdbcTemplate jdbc){this(jdbc,MAX_DIRECT_MEMBERSHIPS,MAX_EXPANDED_MEMBERSHIPS,WRITE_BATCH_SIZE);}
|
||||
FeishuDirectoryCurrentStore(JdbcTemplate jdbc,int maxDirect,int maxExpanded,int batchSize){
|
||||
if(maxDirect<1||maxExpanded<1||batchSize<1)throw new IllegalArgumentException("Directory persistence limits must be positive");
|
||||
this.jdbc=jdbc;this.maxDirect=maxDirect;this.maxExpanded=maxExpanded;this.batchSize=Math.min(1000,batchSize);
|
||||
}
|
||||
|
||||
public void publish(String revision,String context,FeishuDirectoryClient.Snapshot snapshot,Timestamp now){
|
||||
Map<String,List<String>> relations=relations(snapshot);Map<String,Integer> counts=memberCounts(snapshot,relations);
|
||||
Map<String,String> oldDepartments=hashes("SELECT open_department_id,content_hash FROM feishu_directory_department");
|
||||
Map<String,String> oldUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_user");
|
||||
Set<String> wantedDepartments=new LinkedHashSet<>(),wantedUsers=new LinkedHashSet<>();
|
||||
List<Object[]> departmentRows=new ArrayList<>(),userRows=new ArrayList<>();
|
||||
List<Object[]> retainedDepartmentRows=new ArrayList<>(),retainedUserRows=new ArrayList<>();
|
||||
for(String id:snapshot.departments){
|
||||
FeishuDirectoryClient.Department d=snapshot.departmentDetails.get(id);if(d==null)d=fallbackDepartment(id);
|
||||
String open=bounded(d.openDepartmentId,64,id),name=bounded(d.name,200,""),parent=bounded(d.parentOpenDepartmentId,64,"0"),status=bounded(d.status,30,"ACTIVE");
|
||||
int count=counts.containsKey(id)?counts.get(id):0;String hash=hash(open,name,parent,String.valueOf(d.order),status,String.valueOf(count),context);wantedDepartments.add(open);
|
||||
if(!hash.equals(oldDepartments.get(open)))departmentRows.add(new Object[]{open,name,parent,d.order,status,count,revision,context,now,hash,now});
|
||||
else retainedDepartmentRows.add(new Object[]{revision,context,now,open});
|
||||
}
|
||||
for(Map.Entry<String,FeishuDirectoryClient.UserSummary> e:snapshot.userSummaries.entrySet()){
|
||||
FeishuDirectoryClient.UserSummary u=e.getValue();String open=bounded(u.openId,100,"");
|
||||
if(!open.equals(e.getKey()))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");
|
||||
String name=bounded(u.name,100,open);String employee=nullableBounded(u.employeeNo,50);
|
||||
String email=bounded(u.email,320,""),mobile=bounded(u.mobile,50,""),job=bounded(u.jobTitle,200,""),avatar=bounded(u.avatarUrl,500,"");boolean eligible=u.eligible;
|
||||
String hash=hash(open,"",name,employee,email,mobile,job,avatar,String.valueOf(eligible),context);wantedUsers.add(open);
|
||||
if(!hash.equals(oldUsers.get(open)))userRows.add(new Object[]{open,null,name,employee,eligible,revision,context,now,email,mobile,job,avatar,hash,now});
|
||||
else retainedUserRows.add(new Object[]{revision,context,now,open});
|
||||
}
|
||||
Set<String> oldMemberships=new LinkedHashSet<>();for(Map<String,Object> row:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department"))oldMemberships.add(key(row.get("open_id"),row.get("open_department_id")));
|
||||
Set<String>wantedMemberships=new LinkedHashSet<>();List<Object[]>membershipRows=new ArrayList<>(),retainedMembershipRows=new ArrayList<>();
|
||||
for(Map.Entry<String,List<String>> e:relations.entrySet()){String open=e.getKey();for(String department:e.getValue()){String key=key(open,department);wantedMemberships.add(key);if(!oldMemberships.contains(key))membershipRows.add(new Object[]{open,department,revision,now});else retainedMembershipRows.add(new Object[]{revision,open,department});}}
|
||||
batchDeleteMemberships(oldMemberships,wantedMemberships);batchDelete("feishu_directory_user","open_id",oldUsers.keySet(),wantedUsers);batchDelete("feishu_directory_department","open_department_id",oldDepartments.keySet(),wantedDepartments);
|
||||
batch("INSERT INTO feishu_directory_department(open_department_id,name,parent_open_department_id,sort_order,status,member_count,snapshot_run_id,context,observed_at,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),parent_open_department_id=VALUES(parent_open_department_id),sort_order=VALUES(sort_order),status=VALUES(status),member_count=VALUES(member_count),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",departmentRows);
|
||||
batch("INSERT INTO feishu_directory_user(open_id,user_id,name,employee_no,eligible,snapshot_run_id,context,observed_at,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),employee_no=VALUES(employee_no),eligible=VALUES(eligible),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",userRows);
|
||||
batch("INSERT INTO feishu_directory_user_department(open_id,open_department_id,revision_run_id,changed_at) VALUES (?,?,?,?)",membershipRows);
|
||||
batch("UPDATE feishu_directory_department SET snapshot_run_id=?,context=?,observed_at=? WHERE open_department_id=?",retainedDepartmentRows);
|
||||
batch("UPDATE feishu_directory_user SET snapshot_run_id=?,context=?,observed_at=? WHERE open_id=?",retainedUserRows);
|
||||
batch("UPDATE feishu_directory_user_department SET revision_run_id=? WHERE open_id=? AND open_department_id=?",retainedMembershipRows);
|
||||
}
|
||||
|
||||
public Map<String,Object> read(){
|
||||
List<Map<String,Object>> departments=new ArrayList<>();for(Map<String,Object>r:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){Map<String,Object>d=new LinkedHashMap<>();d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name")));d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order"))));d.put("memberCount",intValue(r.get("member_count")));departments.add(d);}
|
||||
Map<String,List<String>> memberships=new HashMap<>();for(Map<String,Object>r:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department ORDER BY open_id,open_department_id"))memberships.computeIfAbsent(string(r.get("open_id")),k->new ArrayList<>()).add(string(r.get("open_department_id")));
|
||||
List<Map<String,Object>>users=new ArrayList<>();for(Map<String,Object>r:jdbc.queryForList("SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id")){Map<String,Object>u=new LinkedHashMap<>();String open=string(r.get("open_id"));u.put("openId",open);u.put("userId",r.get("user_id")==null?null:string(r.get("user_id")));u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no"));u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile")));u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url")));u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u);}
|
||||
Map<String,Object>result=new LinkedHashMap<>();result.put("departments",departments);result.put("users",users);return result;
|
||||
}
|
||||
private void batchDeleteMemberships(Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM feishu_directory_user_department WHERE open_id=? AND open_department_id=?",rows);}
|
||||
private void batchDelete(String table,String column,Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value))rows.add(new Object[]{value});batch("DELETE FROM "+table+" WHERE "+column+"=?",rows);}
|
||||
private void batch(String sql,List<Object[]>rows){for(int i=0;i<rows.size();i+=batchSize)jdbc.batchUpdate(sql,rows.subList(i,Math.min(rows.size(),i+batchSize)));}
|
||||
private Map<String,String>hashes(String sql){Map<String,String>r=new LinkedHashMap<>();for(Map<String,Object>row:jdbc.queryForList(sql)){Iterator<Object>i=row.values().iterator();r.put(string(i.next()),string(i.next()));}return r;}
|
||||
private Map<String,List<String>>relations(FeishuDirectoryClient.Snapshot s){Map<String,List<String>>r=new LinkedHashMap<>();int total=0;for(Map.Entry<String,FeishuDirectoryClient.UserSummary>e:s.userSummaries.entrySet()){LinkedHashSet<String>ids=new LinkedHashSet<>();for(String id:e.getValue().departmentIds)if(id!=null&&s.departments.contains(id.trim()))ids.add(id.trim());if(ids.isEmpty()&&s.departments.contains("0"))ids.add("0");if(ids.size()>maxDirect-total)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");total+=ids.size();r.put(e.getKey(),new ArrayList<>(ids));}return r;}
|
||||
private Map<String,Integer>memberCounts(FeishuDirectoryClient.Snapshot s,Map<String,List<String>>relations){Map<String,String>parents=new HashMap<>();for(String id:s.departments){FeishuDirectoryClient.Department d=s.departmentDetails.get(id);parents.put(id,d==null?"0":d.parentOpenDepartmentId);}Map<String,Set<String>>members=new HashMap<>();int expanded=0;for(Map.Entry<String,List<String>>e:relations.entrySet()){String employee=e.getKey();for(String id:e.getValue()){Set<String>visited=new HashSet<>();String current=id;while(current!=null&&parents.containsKey(current)&&visited.add(current)){Set<String>set=members.computeIfAbsent(current,k->new HashSet<>());if(set.add(employee)&&++expanded>maxExpanded)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");String parent=parents.get(current);if(parent==null||parent.equals(current))break;current=parent;}}}Map<String,Integer>r=new HashMap<>();for(Map.Entry<String,Set<String>>e:members.entrySet())r.put(e.getKey(),e.getValue().size());return r;}
|
||||
private static String hash(String...values){StringBuilder b=new StringBuilder();for(String v:values){String x=v==null?"":v;b.append(x.length()).append(':').append(x).append(';');}return Sha256.hex(b.toString());}
|
||||
private static String key(Object a,Object b){return string(a)+'\u0000'+string(b);}
|
||||
private static FeishuDirectoryClient.Department fallbackDepartment(String id){FeishuDirectoryClient.Department d=new FeishuDirectoryClient.Department();d.openDepartmentId=id;d.name="0".equals(id)?"根部门":"";d.parentOpenDepartmentId="0";d.status="ACTIVE";return d;}
|
||||
private static String bounded(String v,int max,String fallback){String r=v==null?fallback:v.trim();return r.length()<=max?r:r.substring(0,max);}private static String nullableBounded(String v,int max){if(v==null||v.trim().isEmpty())return null;return bounded(v,max,null);}private static String string(Object v){return v==null?"":String.valueOf(v);}private static int intValue(Object v){return v instanceof Number?((Number)v).intValue():0;}private static long longValue(Object v){return v instanceof Number?((Number)v).longValue():0;}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The single classifier for the persisted current-directory publication.
|
||||
* Availability is deliberately independent of age and the current Feishu
|
||||
* configuration: a successful atomic publication remains authoritative until
|
||||
* another successful publication replaces it.
|
||||
*/
|
||||
public final class FeishuDirectoryPublication {
|
||||
public enum Availability { AVAILABLE, NEVER_SYNCED, UNAVAILABLE }
|
||||
public enum ContextState { MATCH, CHANGED, UNKNOWN }
|
||||
|
||||
private final Availability availability;
|
||||
private final String revision;
|
||||
private final Instant successfulAt;
|
||||
private final String successfulContext;
|
||||
|
||||
private FeishuDirectoryPublication(Availability availability, String revision,
|
||||
Instant successfulAt, String successfulContext) {
|
||||
this.availability = availability;
|
||||
this.revision = revision;
|
||||
this.successfulAt = successfulAt;
|
||||
this.successfulContext = successfulContext;
|
||||
}
|
||||
|
||||
public static FeishuDirectoryPublication classify(Map<String, Object> state, FeishuDirectoryTime time) {
|
||||
if (state == null) return unavailable();
|
||||
Object runValue = state.get("last_successful_run_id");
|
||||
Object atValue = state.get("last_successful_at");
|
||||
Object contextValue = state.get("successful_context");
|
||||
if (runValue == null && atValue == null && contextValue == null) {
|
||||
return new FeishuDirectoryPublication(Availability.NEVER_SYNCED, null, null, null);
|
||||
}
|
||||
String run = text(runValue);
|
||||
Instant at = time.instant(atValue);
|
||||
String context = text(contextValue);
|
||||
if (run == null || at == null || context == null) return unavailable();
|
||||
return new FeishuDirectoryPublication(Availability.AVAILABLE, run, at, context);
|
||||
}
|
||||
|
||||
public static FeishuDirectoryPublication unavailable() {
|
||||
return new FeishuDirectoryPublication(Availability.UNAVAILABLE, null, null, null);
|
||||
}
|
||||
|
||||
public Availability getAvailability() { return availability; }
|
||||
public String getAvailabilityState() { return availability.name(); }
|
||||
public boolean isAvailable() { return availability == Availability.AVAILABLE; }
|
||||
public boolean isAdditionsAllowed() { return isAvailable(); }
|
||||
public String getSnapshotState() { return isAvailable() ? "FRESH" : availability.name(); }
|
||||
public String getRevision() { return revision; }
|
||||
public Instant getSuccessfulAt() { return successfulAt; }
|
||||
String getSuccessfulContext() { return successfulContext; }
|
||||
|
||||
public ContextState contextState(String currentContext) {
|
||||
if (!isAvailable() || text(currentContext) == null) return ContextState.UNKNOWN;
|
||||
return successfulContext.equals(currentContext.trim()) ? ContextState.MATCH : ContextState.CHANGED;
|
||||
}
|
||||
|
||||
private static String text(Object value) {
|
||||
if (value == null) return null;
|
||||
String result = String.valueOf(value).trim();
|
||||
return result.isEmpty() ? null : result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.PreparedStatementCreator;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
|
||||
/** One READ_COMMITTED transaction: account observations and current-directory diff. */
|
||||
@Component
|
||||
public class FeishuDirectoryPublisher {
|
||||
private static final int LOOKUP_BATCH = 200;
|
||||
static final int ACCOUNT_UPDATE_BATCH = 1_000;
|
||||
private static final String ACCOUNT_UPDATE_SQL="UPDATE sys_user SET feishu_open_id=?,directory_status=?,directory_context=?,directory_verified_at=?,directory_last_seen_run_id=? WHERE id=? AND feishu_open_id=?";
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate publication;
|
||||
private final FeishuDirectoryRunStore runs;
|
||||
private final FeishuDirectoryCurrentStore directory;
|
||||
private final FeishuTenantTokenService tokens;
|
||||
private final ObjectMapper mapper;
|
||||
private final FeishuDirectoryTime time;
|
||||
|
||||
public FeishuDirectoryPublisher(JdbcTemplate jdbc, PlatformTransactionManager manager,
|
||||
FeishuDirectoryRunStore runs, FeishuDirectoryCurrentStore directory,
|
||||
FeishuTenantTokenService tokens, ObjectMapper mapper,
|
||||
FeishuDirectorySettings settings, FeishuDirectoryTime time) {
|
||||
this.jdbc=jdbc; this.runs=runs; this.directory=directory; this.tokens=tokens; this.mapper=mapper; this.time=time;
|
||||
this.publication=new TransactionTemplate(manager);
|
||||
this.publication.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
this.publication.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
|
||||
this.publication.setTimeout((int)Math.max(120L,Math.min(600L,settings.elapsed()+180L)));
|
||||
}
|
||||
|
||||
public FeishuDirectoryService.Run publish(FeishuDirectoryRunStore.Claim claim,
|
||||
FeishuTenantTokenService.Context captured,
|
||||
FeishuDirectoryClient.Snapshot snapshot) {
|
||||
return publication.execute(status -> {
|
||||
runs.requireLease(claim); // singleton is always the first lock
|
||||
if (!tokens.syncEnabled()) throw FeishuTenantTokenService.syncDisabled();
|
||||
if (!captured.fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged();
|
||||
FeishuDirectoryService.Run run=runs.loadPublic(claim.getRunId());
|
||||
FeishuDirectoryService.Counts counts=run.getCounts();
|
||||
Timestamp now=publishData(snapshot,run,captured.fingerprint);
|
||||
if (!captured.fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged();
|
||||
run.setState("SUCCEEDED"); run.setComplete(true); run.setApplied(true); run.setFinishedAt(now.toInstant().toString());
|
||||
int completed=jdbc.update("UPDATE feishu_directory_sync_run SET state='SUCCEEDED',finished_at=?,complete=TRUE,applied=TRUE,"+
|
||||
"departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,context=?,lease_until=NULL,error_code=NULL,error_message=NULL WHERE run_id=? AND execution_token=? AND fence_token=?",
|
||||
now,counts.getDepartments(),counts.getUsersSeen(),counts.getEligible(),counts.getExcluded(),counts.getCreated(),counts.getUpdated(),counts.getIneligible(),counts.getOutOfScope(),captured.fingerprint,claim.getRunId(),claim.getExecutionToken(),claim.getFenceToken());
|
||||
if(completed!=1)throw FeishuTenantTokenService.ownershipLost();
|
||||
String runJson=encode(run);
|
||||
int moved=jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=? WHERE id=1 AND owner=? AND fence_token=?",
|
||||
runJson,claim.getRunId(),now,captured.fingerprint,claim.getRunId(),claim.getFenceToken());
|
||||
if(moved!=1)throw FeishuTenantTokenService.ownershipLost();
|
||||
return run;
|
||||
});
|
||||
}
|
||||
|
||||
/** Publication data unit; caller owns the transaction and fencing boundary. */
|
||||
Timestamp publishData(FeishuDirectoryClient.Snapshot snapshot,FeishuDirectoryService.Run run,String context){
|
||||
applyAccounts(snapshot,run,context);
|
||||
Timestamp now=jdbc.queryForObject("SELECT CURRENT_TIMESTAMP",Timestamp.class);
|
||||
directory.publish(run.getRunId(),context,snapshot,now);
|
||||
return now;
|
||||
}
|
||||
|
||||
void applyAccounts(FeishuDirectoryClient.Snapshot snapshot,FeishuDirectoryService.Run run,String context){
|
||||
FeishuDirectoryService.Counts counts=run.getCounts(); counts.setDepartments(snapshot.departments.size()); counts.setUsersSeen(snapshot.userSummaries.size());
|
||||
Set<String> opens=new LinkedHashSet<>(), employeeNumbers=new LinkedHashSet<>();
|
||||
for(Map.Entry<String,FeishuDirectoryClient.UserSummary> entry:snapshot.userSummaries.entrySet()){
|
||||
FeishuDirectoryClient.UserSummary user=entry.getValue(); String open=requiredOpen(entry);
|
||||
if(!opens.add(open))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");
|
||||
String employee=trim(user.employeeNo);if(!employee.isEmpty()&&employee.length()<=50)employeeNumbers.add(employee);
|
||||
}
|
||||
Map<String,Account> byOpen=new HashMap<>();Set<String> usedEmployees=new HashSet<>();
|
||||
loadAccounts(opens,byOpen,usedEmployees);
|
||||
loadEmployeeNumbers(employeeNumbers,usedEmployees);
|
||||
Instant traversalStarted=Instant.parse(run.getStartedAt());
|
||||
// MySQL stores this column at microsecond precision; use the same
|
||||
// precision so SUCCESS_NO_INFO verification compares the committed
|
||||
// value rather than a sub-microsecond JVM value.
|
||||
Timestamp observedAt=Timestamp.from(Instant.now().truncatedTo(ChronoUnit.MICROS));
|
||||
List<Object[]> updates=new ArrayList<>(ACCOUNT_UPDATE_BATCH);
|
||||
for(Map.Entry<String,FeishuDirectoryClient.UserSummary> entry:snapshot.userSummaries.entrySet()){
|
||||
FeishuDirectoryClient.UserSummary user=entry.getValue(); String open=requiredOpen(entry);
|
||||
Account account=byOpen.get(open); boolean eligible=user.eligible;
|
||||
if(eligible)counts.setEligible(counts.getEligible()+1);else counts.setExcluded(counts.getExcluded()+1);
|
||||
if(account==null&&!eligible)continue;
|
||||
if(account==null){
|
||||
String employee=trim(user.employeeNo);
|
||||
if(employee.isEmpty()||employee.length()>50||usedEmployees.contains(employee)){do{employee="FS-"+UUID.randomUUID();}while(usedEmployees.contains(employee)||employeeExists(employee));}
|
||||
String name=trim(user.name);if(name.isEmpty())name=open;if(name.length()>100)name=name.substring(0,100);
|
||||
long id=insertAccount(open,employee,name);account=new Account(id,open,null,null,null,null);byOpen.put(open,account);usedEmployees.add(employee);counts.setCreated(counts.getCreated()+1);
|
||||
}else{
|
||||
if(account.openId!=null&&!open.equals(account.openId))throw FeishuTenantTokenService.diagnostic("DIRECTORY_ACCOUNT_BINDING_CONFLICT");
|
||||
counts.setUpdated(counts.getUpdated()+1);
|
||||
}
|
||||
boolean newerDenial=context.equals(account.directoryContext)&&"INELIGIBLE".equals(account.directoryStatus)&&account.verifiedAt!=null&&account.verifiedAt.isAfter(traversalStarted);
|
||||
String directoryStatus=eligible&&!newerDenial?"ELIGIBLE":"INELIGIBLE";if(!"ELIGIBLE".equals(directoryStatus))counts.setIneligible(counts.getIneligible()+1);
|
||||
queueAccountUpdate(updates,new Object[]{open,directoryStatus,context,observedAt,run.getRunId(),account.id,open});
|
||||
}
|
||||
flushAccountUpdates(updates);
|
||||
counts.setOutOfScope(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<>?",observedAt,context,run.getRunId()));
|
||||
}
|
||||
|
||||
void queueAccountUpdate(List<Object[]> updates,Object[] update){updates.add(update);if(updates.size()>=ACCOUNT_UPDATE_BATCH)flushAccountUpdates(updates);}
|
||||
void flushAccountUpdates(List<Object[]> updates){
|
||||
if(updates.isEmpty())return;
|
||||
int expected=updates.size();int[] changed=jdbc.batchUpdate(ACCOUNT_UPDATE_SQL,updates);
|
||||
if(changed==null||changed.length!=expected)throw FeishuTenantTokenService.diagnostic("DIRECTORY_ACCOUNT_BINDING_CONFLICT");
|
||||
boolean verificationRequired=false;
|
||||
for(int count:changed){
|
||||
if(count==Statement.SUCCESS_NO_INFO)verificationRequired=true;
|
||||
else if(count!=1)throw FeishuTenantTokenService.diagnostic("DIRECTORY_ACCOUNT_BINDING_CONFLICT");
|
||||
}
|
||||
if(verificationRequired)verifyAccountUpdates(updates);
|
||||
updates.clear();
|
||||
}
|
||||
|
||||
private void verifyAccountUpdates(List<Object[]> updates){
|
||||
Map<Long,Object[]> expectedById=new LinkedHashMap<>();
|
||||
for(Object[] update:updates){
|
||||
if(update==null||update.length!=7||!(update[5] instanceof Number)
|
||||
||!Objects.equals(value(update[0]),value(update[6])))bindingConflict();
|
||||
long id=((Number)update[5]).longValue();
|
||||
if(expectedById.put(id,update)!=null)bindingConflict();
|
||||
}
|
||||
List<Long> ids=new ArrayList<>(expectedById.keySet());
|
||||
Set<Long> verified=new HashSet<>();
|
||||
for(int start=0;start<ids.size();start+=LOOKUP_BATCH){
|
||||
List<Long> batch=ids.subList(start,Math.min(ids.size(),start+LOOKUP_BATCH));
|
||||
String sql="SELECT id,feishu_open_id,directory_status,directory_context,directory_verified_at,directory_last_seen_run_id FROM sys_user WHERE id IN ("+placeholders(batch.size())+")";
|
||||
for(Map<String,Object> row:jdbc.queryForList(sql,batch.toArray())){
|
||||
Object idValue=row.get("id");if(!(idValue instanceof Number))bindingConflict();
|
||||
long id=((Number)idValue).longValue();Object[] expected=expectedById.get(id);
|
||||
if(expected==null||!verified.add(id)
|
||||
||!Objects.equals(value(row.get("feishu_open_id")),value(expected[0]))
|
||||
||!Objects.equals(value(row.get("directory_status")),value(expected[1]))
|
||||
||!Objects.equals(value(row.get("directory_context")),value(expected[2]))
|
||||
||!Objects.equals(time.instant(row.get("directory_verified_at")),time.instant(expected[3]))
|
||||
||!Objects.equals(value(row.get("directory_last_seen_run_id")),value(expected[4])))bindingConflict();
|
||||
}
|
||||
}
|
||||
if(verified.size()!=expectedById.size())bindingConflict();
|
||||
}
|
||||
|
||||
private static void bindingConflict(){throw FeishuTenantTokenService.diagnostic("DIRECTORY_ACCOUNT_BINDING_CONFLICT");}
|
||||
|
||||
private void loadAccounts(Set<String> values,Map<String,Account> byOpen,Set<String> employees){
|
||||
List<String> all=new ArrayList<>(values);for(int start=0;start<all.size();start+=LOOKUP_BATCH){List<String> batch=all.subList(start,Math.min(all.size(),start+LOOKUP_BATCH));String sql="SELECT id,feishu_open_id,feishu_user_id,employee_no,directory_status,directory_context,directory_verified_at FROM sys_user WHERE feishu_open_id IN ("+placeholders(batch.size())+")";for(Map<String,Object> row:jdbc.queryForList(sql,batch.toArray())){Account a=account(row);if(a.openId!=null&&byOpen.put(a.openId,a)!=null)throw FeishuTenantTokenService.diagnostic("DIRECTORY_ACCOUNT_BINDING_CONFLICT");Object employee=row.get("employee_no");if(employee!=null)employees.add(String.valueOf(employee));}}
|
||||
}
|
||||
private void loadEmployeeNumbers(Set<String> values,Set<String> result){List<String>all=new ArrayList<>(values);for(int start=0;start<all.size();start+=LOOKUP_BATCH){List<String>b=all.subList(start,Math.min(all.size(),start+LOOKUP_BATCH));for(Map<String,Object>row:jdbc.queryForList("SELECT employee_no FROM sys_user WHERE employee_no IN ("+placeholders(b.size())+")",b.toArray()))result.add(String.valueOf(row.get("employee_no")));}}
|
||||
private boolean employeeExists(String employee){Integer count=jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE employee_no=?",Integer.class,employee);return count!=null&&count>0;}
|
||||
private long insertAccount(String open,String employee,String name){KeyHolder key=new GeneratedKeyHolder();PreparedStatementCreator creator=connection->{PreparedStatement statement=connection.prepareStatement("INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,status,user_type,directory_status,created_at,updated_at) VALUES (?,NULL,?,?,'ACTIVE','EMPLOYEE','UNKNOWN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",Statement.RETURN_GENERATED_KEYS);statement.setString(1,open);statement.setString(2,employee);statement.setString(3,name);return statement;};jdbc.update(creator,key);if(key.getKey()==null)throw new IllegalStateException("Directory account key unavailable");return key.getKey().longValue();}
|
||||
Account account(Map<String,Object>row){return new Account(((Number)row.get("id")).longValue(),value(row.get("feishu_open_id")),value(row.get("feishu_user_id")),value(row.get("directory_status")),value(row.get("directory_context")),time.instant(row.get("directory_verified_at")));}
|
||||
private static String value(Object value){return value==null?null:String.valueOf(value);} private static String placeholders(int n){StringBuilder b=new StringBuilder();for(int i=0;i<n;i++){if(i>0)b.append(',');b.append('?');}return b.toString();}
|
||||
private static String trim(String value){return value==null?"":value.trim();}
|
||||
private static String requiredOpen(Map.Entry<String,FeishuDirectoryClient.UserSummary> entry){String open=entry.getValue()==null?null:entry.getValue().openId;if(open==null||open.trim().isEmpty()||open.length()>100||!open.equals(entry.getKey()))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");return open;}
|
||||
private String encode(FeishuDirectoryService.Run run){try{return mapper.writeValueAsString(run);}catch(Exception e){throw new IllegalStateException("Cannot encode directory run");}}
|
||||
static final class Account{final long id;final String openId,userId,directoryStatus,directoryContext;final Instant verifiedAt;Account(long id,String openId,String userId,String status,String context,Instant verifiedAt){this.id=id;this.openId=openId;this.userId=userId;this.directoryStatus=status;this.directoryContext=context;this.verifiedAt=verifiedAt;}}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import lombok.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Short-transaction durable queue and lease/fencing boundary. */
|
||||
@Component
|
||||
public class FeishuDirectoryRunStore {
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate requiresNew;
|
||||
private final ObjectMapper mapper;
|
||||
private final long leaseSeconds;
|
||||
|
||||
public FeishuDirectoryRunStore(JdbcTemplate jdbc, PlatformTransactionManager manager,
|
||||
ObjectMapper mapper, FeishuDirectorySettings settings) {
|
||||
this.jdbc = jdbc;
|
||||
this.mapper = mapper;
|
||||
this.leaseSeconds = Math.max(30L, settings.elapsed() + 30L);
|
||||
this.requiresNew = new TransactionTemplate(manager);
|
||||
this.requiresNew.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
this.requiresNew.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
|
||||
this.requiresNew.setTimeout(10);
|
||||
}
|
||||
|
||||
public FeishuDirectoryService.Run enqueue(String trigger) {
|
||||
if (!"MANUAL".equals(trigger) && !"STARTUP".equals(trigger) && !"SCHEDULED".equals(trigger))
|
||||
throw new IllegalArgumentException("Invalid trigger");
|
||||
// Normal duplicate POSTs avoid waiting behind a long publication. The
|
||||
// locked recheck below remains the correctness boundary.
|
||||
Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class);
|
||||
if (observedActive != null && observedActive > 0)
|
||||
throw new BusinessException("Directory sync already running", 409);
|
||||
return requiresNew.execute(status -> {
|
||||
lockState();
|
||||
Integer active = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class);
|
||||
if (active != null && active > 0) throw new BusinessException("Directory sync already running", 409);
|
||||
Timestamp now = databaseNow();
|
||||
FeishuDirectoryService.Run run = new FeishuDirectoryService.Run();
|
||||
run.setRunId(UUID.randomUUID().toString());
|
||||
run.setTrigger(trigger);
|
||||
run.setState("RUNNING"); // Public vocabulary deliberately has no QUEUED state.
|
||||
run.setStartedAt(null); // Execution time begins only when a worker claims this row.
|
||||
jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger_type,state,queued_at,started_at,complete,applied) VALUES (?,?, 'QUEUED',?,NULL,FALSE,FALSE)",
|
||||
run.getRunId(), trigger, now);
|
||||
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1", encode(run));
|
||||
return run;
|
||||
});
|
||||
}
|
||||
|
||||
public Claim claimNext() {
|
||||
return requiresNew.execute(status -> {
|
||||
Map<String,Object> state = lockState();
|
||||
List<Map<String,Object>> rows = jdbc.queryForList(
|
||||
"SELECT run_id,trigger_type,attempt_count FROM feishu_directory_sync_run " +
|
||||
"WHERE (state='QUEUED' OR (state='RUNNING' AND lease_until<CURRENT_TIMESTAMP)) " +
|
||||
"AND attempt_count<? ORDER BY queued_at,run_id LIMIT 1 FOR UPDATE", MAX_ATTEMPTS);
|
||||
if (rows.isEmpty()) {
|
||||
failExhaustedExpiredRuns();
|
||||
return null;
|
||||
}
|
||||
Map<String,Object> row = rows.get(0);
|
||||
String runId = String.valueOf(row.get("run_id"));
|
||||
String trigger = String.valueOf(row.get("trigger_type"));
|
||||
int attempt = ((Number) row.get("attempt_count")).intValue() + 1;
|
||||
long fence = ((Number) state.get("fence_token")).longValue() + 1L;
|
||||
String execution = UUID.randomUUID().toString();
|
||||
Timestamp now = databaseNow();
|
||||
Timestamp lease = Timestamp.from(now.toInstant().plusSeconds(leaseSeconds));
|
||||
jdbc.update("UPDATE feishu_directory_state SET owner=?,lease_until=?,fence_token=?,context=NULL WHERE id=1",
|
||||
runId, lease, fence);
|
||||
jdbc.update("UPDATE feishu_directory_sync_run SET state='RUNNING',started_at=COALESCE(started_at,?),attempt_count=?,execution_token=?,fence_token=?,heartbeat_at=?,lease_until=?,error_code=NULL,error_message=NULL WHERE run_id=?",
|
||||
now,
|
||||
attempt, execution, fence, now, lease, runId);
|
||||
return new Claim(runId, trigger, execution, fence, attempt);
|
||||
});
|
||||
}
|
||||
|
||||
public boolean heartbeat(Claim claim) {
|
||||
Boolean result = requiresNew.execute(status -> {
|
||||
Map<String,Object> state=lockState();
|
||||
if(!claim.runId.equals(state.get("owner"))||((Number)state.get("fence_token")).longValue()!=claim.fenceToken)return false;
|
||||
Timestamp now = databaseNow();
|
||||
Timestamp lease = Timestamp.from(now.toInstant().plusSeconds(leaseSeconds));
|
||||
int changed = jdbc.update("UPDATE feishu_directory_sync_run SET heartbeat_at=?,lease_until=? " +
|
||||
"WHERE run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP",
|
||||
now, lease, claim.runId, claim.executionToken, claim.fenceToken);
|
||||
if (changed == 1) jdbc.update("UPDATE feishu_directory_state SET lease_until=? WHERE id=1 AND owner=? AND fence_token=?",
|
||||
lease, claim.runId, claim.fenceToken);
|
||||
return changed == 1;
|
||||
});
|
||||
return Boolean.TRUE.equals(result);
|
||||
}
|
||||
|
||||
/** Must be called in the publication transaction; takes the singleton lock first. */
|
||||
public Map<String,Object> requireLease(Claim claim) {
|
||||
Map<String,Object> state = lockState();
|
||||
List<Integer> valid = jdbc.query("SELECT 1 FROM feishu_directory_sync_run WHERE run_id=? AND state='RUNNING' " +
|
||||
"AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP",
|
||||
(rs, row) -> rs.getInt(1), claim.runId, claim.executionToken, claim.fenceToken);
|
||||
if (valid.isEmpty() || !claim.runId.equals(state.get("owner"))
|
||||
|| ((Number) state.get("fence_token")).longValue() != claim.fenceToken)
|
||||
throw FeishuTenantTokenService.ownershipLost();
|
||||
return state;
|
||||
}
|
||||
|
||||
public void recordFailure(Claim claim, String code, String message) {
|
||||
requiresNew.execute(status -> {
|
||||
Map<String,Object> state = lockState();
|
||||
List<Map<String,Object>> rows = jdbc.queryForList("SELECT attempt_count FROM feishu_directory_sync_run " +
|
||||
"WHERE run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? FOR UPDATE",
|
||||
claim.runId, claim.executionToken, claim.fenceToken);
|
||||
if (rows.isEmpty()) return null; // A newer owner has fenced this attempt.
|
||||
int attempts = ((Number) rows.get(0).get("attempt_count")).intValue();
|
||||
if (attempts < MAX_ATTEMPTS && retryable(code)) {
|
||||
jdbc.update("UPDATE feishu_directory_sync_run SET state='QUEUED',execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL,error_code=?,error_message=? WHERE run_id=?",
|
||||
code, message, claim.runId);
|
||||
} else {
|
||||
Timestamp now = databaseNow();
|
||||
jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=?,complete=FALSE,applied=FALSE,error_code=?,error_message=?,execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE run_id=?",
|
||||
now, code, message, claim.runId);
|
||||
FeishuDirectoryService.Run run = loadPublic(claim.runId);
|
||||
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1", encode(run));
|
||||
}
|
||||
if (claim.runId.equals(state.get("owner")) && ((Number) state.get("fence_token")).longValue() == claim.fenceToken)
|
||||
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE id=1");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
static boolean retryable(String code){
|
||||
if(code==null)return false;
|
||||
return code.matches("DIRECTORY_(REQUEST_FAILED|RATE_LIMIT_EXHAUSTED|DEADLINE|WORKER_FAILED|WORKER_UNAVAILABLE|PERSISTENCE_CONTENDED|PERSISTENCE_UNAVAILABLE)")
|
||||
||"TOKEN_REQUEST_FAILED".equals(code)||"FEISHU_CODE_99991400".equals(code)
|
||||
||code.matches("HTTP_STATUS_(408|429|5[0-9]{2})");
|
||||
}
|
||||
|
||||
public FeishuDirectoryService.Run loadPublic(String runId) {
|
||||
return jdbc.queryForObject("SELECT * FROM feishu_directory_sync_run WHERE run_id=?", (rs, row) -> {
|
||||
FeishuDirectoryService.Run run = new FeishuDirectoryService.Run();
|
||||
run.setRunId(rs.getString("run_id")); run.setTrigger(rs.getString("trigger_type"));
|
||||
String internal = rs.getString("state");
|
||||
run.setState(("QUEUED".equals(internal) || "RUNNING".equals(internal)) ? "RUNNING" : internal);
|
||||
Timestamp started = rs.getTimestamp("started_at"), finished = rs.getTimestamp("finished_at");
|
||||
run.setStartedAt(started == null ? null : started.toInstant().toString());
|
||||
run.setFinishedAt(finished == null ? null : finished.toInstant().toString());
|
||||
run.setComplete(rs.getBoolean("complete")); run.setApplied(rs.getBoolean("applied"));
|
||||
FeishuDirectoryService.Counts counts = new FeishuDirectoryService.Counts();
|
||||
counts.setDepartments(rs.getInt("departments")); counts.setUsersSeen(rs.getInt("users_seen"));
|
||||
counts.setEligible(rs.getInt("eligible")); counts.setExcluded(rs.getInt("excluded"));
|
||||
counts.setCreated(rs.getInt("created")); counts.setUpdated(rs.getInt("updated"));
|
||||
counts.setIneligible(rs.getInt("ineligible")); counts.setOutOfScope(rs.getInt("out_of_scope"));
|
||||
run.setCounts(counts); run.setErrorCode(rs.getString("error_code")); run.setErrorMessage(rs.getString("error_message"));
|
||||
return run;
|
||||
}, runId);
|
||||
}
|
||||
|
||||
private void failExhaustedExpiredRuns() {
|
||||
List<String> expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE state='RUNNING' " +
|
||||
"AND lease_until<CURRENT_TIMESTAMP AND attempt_count>=? FOR UPDATE",(rs,row)->rs.getString(1),MAX_ATTEMPTS);
|
||||
for(String runId:expired){
|
||||
jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=CURRENT_TIMESTAMP,complete=FALSE,applied=FALSE," +
|
||||
"error_code='DIRECTORY_WORKER_UNAVAILABLE',error_message='Directory sync failed; current directory retained.'," +
|
||||
"execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE run_id=?",runId);
|
||||
FeishuDirectoryService.Run failed=loadPublic(runId);
|
||||
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1",encode(failed));
|
||||
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE id=1 AND owner=?",runId);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String,Object> lockState() {
|
||||
return jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1 FOR UPDATE");
|
||||
}
|
||||
private Timestamp databaseNow() { return jdbc.queryForObject("SELECT CURRENT_TIMESTAMP", Timestamp.class); }
|
||||
private String encode(FeishuDirectoryService.Run run) {
|
||||
try { return mapper.writeValueAsString(run); }
|
||||
catch (Exception e) { throw new IllegalStateException("Cannot encode directory run"); }
|
||||
}
|
||||
|
||||
@Value
|
||||
public static class Claim {
|
||||
String runId;
|
||||
String trigger;
|
||||
String executionToken;
|
||||
long fenceToken;
|
||||
int attempt;
|
||||
}
|
||||
}
|
||||
@@ -1,811 +1,166 @@
|
||||
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.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.finance.system.repository.SysUserRepository;
|
||||
import lombok.Data;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.*;
|
||||
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 java.sql.Timestamp;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/** Public directory facade. POST work ends after the durable enqueue commit. */
|
||||
@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 FeishuDirectoryRunStore runs;
|
||||
private final FeishuDirectoryCurrentStore currentStore;
|
||||
private final FeishuDirectorySyncDispatcher dispatcher;
|
||||
private final TransactionTemplate organizationSnapshot;
|
||||
private final TransactionTemplate observation;
|
||||
private final FeishuDirectoryTime time;
|
||||
private final java.util.concurrent.Semaphore organizationPermits = new java.util.concurrent.Semaphore(4, true);
|
||||
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;
|
||||
private final FeishuDirectoryClient directClient;
|
||||
private final FeishuDirectoryPublisher directPublisher;
|
||||
|
||||
@Autowired
|
||||
public FeishuDirectoryService(JdbcTemplate jdbc, PlatformTransactionManager manager,
|
||||
FeishuTenantTokenService tokens, FeishuDirectorySettings settings,
|
||||
FeishuDirectoryRunStore runs, FeishuDirectoryCurrentStore currentStore,
|
||||
FeishuDirectorySyncDispatcher dispatcher, ObjectMapper mapper,
|
||||
FeishuDirectoryTime time) {
|
||||
this.jdbc=jdbc;this.tokens=tokens;this.settings=settings;this.runs=runs;this.currentStore=currentStore;this.dispatcher=dispatcher;this.mapper=mapper;
|
||||
this.time=time;this.directClient=null;this.directPublisher=null;this.organizationSnapshot=snapshotTx(manager);this.observation=observationTx(manager);
|
||||
}
|
||||
|
||||
/** Focused non-Spring test constructor. It executes the durable row inline. */
|
||||
public FeishuDirectoryService(JdbcTemplate jdbc, PlatformTransactionManager manager, SysUserRepository ignored,
|
||||
FeishuTenantTokenService tokens, FeishuDirectoryClient client,
|
||||
FeishuDirectorySettings settings, ObjectMapper mapper, FeishuDirectoryTime time) {
|
||||
this.jdbc=jdbc;this.tokens=tokens;this.settings=settings;this.mapper=mapper;this.dispatcher=null;this.directClient=client;
|
||||
this.time=time;
|
||||
this.runs=new FeishuDirectoryRunStore(jdbc,manager,mapper,settings);
|
||||
this.currentStore=new FeishuDirectoryCurrentStore(jdbc);
|
||||
this.directPublisher=new FeishuDirectoryPublisher(jdbc,manager,runs,currentStore,tokens,mapper,settings,time);
|
||||
this.organizationSnapshot=snapshotTx(manager);this.observation=observationTx(manager);
|
||||
}
|
||||
|
||||
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;
|
||||
Run accepted=runs.enqueue(trigger);
|
||||
if(dispatcher!=null){dispatcher.wake();return accepted;}
|
||||
// Compatibility for unit tests that instantiate this service directly; production never uses this path.
|
||||
for(int attempt=0;attempt<3;attempt++){
|
||||
FeishuDirectoryRunStore.Claim claim=runs.claimNext();if(claim==null)break;
|
||||
String phase="CONFIGURATION";
|
||||
try{FeishuTenantTokenService.Context context=tokens.capture();if(!tokens.syncEnabled())throw FeishuTenantTokenService.syncDisabled();phase="FETCH";FeishuDirectoryClient.Snapshot snapshot=directClient.fetch(context);phase="PUBLICATION";return directPublisher.publish(claim,context,snapshot);}
|
||||
catch(Throwable failure){String code=safeDiagnostic(failure,phase);runs.recordFailure(claim,code,failureMessage(code));}
|
||||
}
|
||||
return runs.loadPublic(accepted.getRunId());
|
||||
}
|
||||
|
||||
/** Explicit name for callers migrating from the old synchronous API. */
|
||||
public Run enqueue(String trigger){return sync(trigger);}
|
||||
|
||||
@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(DuplicateKeyException ignored){ }
|
||||
}
|
||||
|
||||
public Map<String,Object> status(){
|
||||
Map<String,Object> state=null;try{state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");}catch(RuntimeException ignored){}
|
||||
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
|
||||
String context=currentContext();
|
||||
Instant success=publication.getSuccessfulAt();
|
||||
Integer active=null;try{active=jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')",Integer.class);}catch(RuntimeException ignored){}
|
||||
Map<String,Object> result=new LinkedHashMap<>();result.put("configured",context!=null);result.put("running",active!=null&&active>0);result.put("snapshotState",publication.getSnapshotState());result.put("availabilityState",publication.getAvailabilityState());result.put("additionsAllowed",publication.isAdditionsAllowed());result.put("contextState",publication.contextState(context).name());result.put("storageMode","CURRENT_STATE");result.put("currentRevision",publication.getRevision());result.put("maxStatusAgeSeconds",0);result.put("lastSuccessfulRunId",publication.getRevision());result.put("lastSuccessfulAt",success==null?null:success.toString());result.put("snapshotExpiresAt",null);
|
||||
Run last=null;try{List<String> ids=jdbc.query("SELECT run_id FROM feishu_directory_sync_run ORDER BY queued_at DESC,run_id DESC LIMIT 1",(rs,row)->rs.getString(1));if(!ids.isEmpty())last=runs.loadPublic(ids.get(0));}catch(Exception ignored){last=parse(state==null?null:(String)state.get("last_run"));}
|
||||
result.put("lastRun",last);return result;
|
||||
}
|
||||
|
||||
public Map<String,Object> organization(){
|
||||
Map<String,Object> unavailable=emptyOrganization(FeishuDirectoryPublication.unavailable(),null,"UNKNOWN");
|
||||
if(!organizationPermits.tryAcquire())return unavailable;
|
||||
try{
|
||||
OrganizationSnapshot captured=organizationSnapshot.execute(status->{
|
||||
Map<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
|
||||
Instant success=publication.getSuccessfulAt();
|
||||
Map<String,Object> result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN");
|
||||
if(!publication.isAvailable())return new OrganizationSnapshot(publication,result);
|
||||
Map<String,Object> organization=currentStore.read();
|
||||
if(organization!=null){result.put("departments",organization.get("departments"));result.put("users",organization.get("users"));}
|
||||
return new OrganizationSnapshot(publication,result);
|
||||
});
|
||||
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;
|
||||
if(captured==null||!captured.publication.isAvailable())return captured==null?unavailable:captured.value;
|
||||
if(!revalidate(captured.publication))return unavailable;
|
||||
captured.value.put("contextState",captured.publication.contextState(currentContext()).name());
|
||||
return captured.value;
|
||||
}catch(Exception ignored){log.warn("Feishu organization snapshot could not be read");return unavailable;}
|
||||
finally{organizationPermits.release();}
|
||||
}
|
||||
|
||||
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;
|
||||
/** A separate READ_COMMITTED transaction observes publications committed during materialization. */
|
||||
private boolean revalidate(FeishuDirectoryPublication captured){
|
||||
Boolean stable=observation.execute(status->{
|
||||
Map<String,Object> current=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||
FeishuDirectoryPublication now=FeishuDirectoryPublication.classify(current,time);
|
||||
return now.isAvailable()&&Objects.equals(captured.getRevision(),now.getRevision())
|
||||
&&Objects.equals(captured.getSuccessfulContext(),now.getSuccessfulContext())
|
||||
&&Objects.equals(captured.getSuccessfulAt(),now.getSuccessfulAt());
|
||||
});
|
||||
return Boolean.TRUE.equals(stable);
|
||||
}
|
||||
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 String currentContext(){try{return tokens.capture().fingerprint;}catch(RuntimeException ignored){return null;}}
|
||||
private static Map<String,Object> emptyOrganization(FeishuDirectoryPublication publication,String at,String contextState){Map<String,Object>result=new LinkedHashMap<>();result.put("snapshotState",publication.getSnapshotState());result.put("availabilityState",publication.getAvailabilityState());result.put("additionsAllowed",publication.isAdditionsAllowed());result.put("currentRevision",publication.getRevision());result.put("contextState",contextState);result.put("lastSuccessfulAt",at);result.put("snapshotExpiresAt",null);result.put("maxStatusAgeSeconds",0);result.put("departments",new ArrayList<>());result.put("users",new ArrayList<>());return result;}
|
||||
private Run parse(String json){try{return json==null?null:mapper.readValue(json,Run.class);}catch(Exception ignored){return null;}}
|
||||
private static TransactionTemplate snapshotTx(PlatformTransactionManager manager){TransactionTemplate tx=new TransactionTemplate(manager);tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);tx.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);tx.setReadOnly(true);tx.setTimeout(30);return tx;}
|
||||
private static TransactionTemplate observationTx(PlatformTransactionManager manager){TransactionTemplate tx=new TransactionTemplate(manager);tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);tx.setReadOnly(true);tx.setTimeout(10);return tx;}
|
||||
private static final class OrganizationSnapshot{private final FeishuDirectoryPublication publication;private final Map<String,Object>value;private OrganizationSnapshot(FeishuDirectoryPublication publication,Map<String,Object>value){this.publication=publication;this.value=value;}}
|
||||
|
||||
static String safeDiagnostic(Throwable ex,String phase){
|
||||
String fallback=null;for(Throwable current=ex;current!=null;current=current.getCause()){
|
||||
if(current instanceof FeishuTenantTokenService.DiagnosticFailure){String code=((FeishuTenantTokenService.DiagnosticFailure)current).getDiagnosticCode();if(code!=null&&code.matches("[A-Z][A-Z0-9_]{2,99}"))return code;}
|
||||
if(current instanceof DataIntegrityViolationException)return"DIRECTORY_PERSISTENCE_CONSTRAINT";
|
||||
if(current instanceof InvalidDataAccessResourceUsageException)return"DIRECTORY_PERSISTENCE_SCHEMA";
|
||||
if(current instanceof CannotAcquireLockException)return"DIRECTORY_PERSISTENCE_CONTENDED";
|
||||
if(current instanceof QueryTimeoutException||current instanceof DataAccessResourceFailureException)return"DIRECTORY_PERSISTENCE_UNAVAILABLE";
|
||||
if(current instanceof DataAccessException||current instanceof javax.persistence.PersistenceException||current instanceof org.springframework.transaction.TransactionException)fallback="DIRECTORY_PERSISTENCE_FAILED";
|
||||
if(current instanceof ClassCastException)return"DIRECTORY_PUBLICATION_TYPE_MISMATCH";
|
||||
if(current instanceof IllegalArgumentException||current instanceof IllegalStateException)fallback="DIRECTORY_PUBLICATION_INVALID_STATE";
|
||||
}return fallback==null?"DIRECTORY_"+(phase==null?"WORKER":phase.replaceAll("[^A-Z_]",""))+"_FAILED":fallback;
|
||||
}
|
||||
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);
|
||||
static String safeFailureType(Throwable ex){
|
||||
for(Throwable current=ex;current!=null;current=current.getCause()){
|
||||
if(current instanceof FeishuTenantTokenService.DiagnosticFailure)return"DIAGNOSTIC";
|
||||
if(current instanceof DataIntegrityViolationException)return"DATA_INTEGRITY";
|
||||
if(current instanceof InvalidDataAccessResourceUsageException)return"SQL_SCHEMA";
|
||||
if(current instanceof CannotAcquireLockException)return"LOCK_ACQUISITION";
|
||||
if(current instanceof QueryTimeoutException)return"QUERY_TIMEOUT";
|
||||
if(current instanceof DataAccessResourceFailureException)return"DATA_RESOURCE";
|
||||
if(current instanceof DataAccessException)return"DATA_ACCESS";
|
||||
if(current instanceof org.springframework.transaction.TransactionException)return"TRANSACTION";
|
||||
if(current instanceof ClassCastException)return"TYPE_MISMATCH";
|
||||
if(current instanceof IllegalArgumentException)return"INVALID_ARGUMENT";
|
||||
if(current instanceof IllegalStateException)return"INVALID_STATE";
|
||||
}
|
||||
|
||||
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;
|
||||
return"UNEXPECTED";
|
||||
}
|
||||
static String failureMessage(String diagnostic){return"Directory sync failed; current directory retained. Check Feishu contact permissions, app visibility and configuration. 目录同步失败,已保留当前通讯录;请检查飞书通讯录权限、应用可见范围和配置。 Diagnostic category: "+diagnostic+".";}
|
||||
|
||||
/**
|
||||
* 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; }
|
||||
}
|
||||
@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;@JsonIgnore public int getEligible(){return eligible;}@JsonIgnore public int getIneligible(){return ineligible;}}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ 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;
|
||||
@@ -21,9 +20,8 @@ public class FeishuDirectorySettings {
|
||||
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. */
|
||||
/** Directory-v1 snapshots are fixed to the application 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)); }
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.SmartLifecycle;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/** Single worker lifecycle. Polling, rather than an in-memory queue, is authoritative. */
|
||||
@Component
|
||||
@Slf4j
|
||||
public class FeishuDirectorySyncDispatcher implements SmartLifecycle {
|
||||
private final FeishuDirectorySyncWorker worker;
|
||||
private final ScheduledExecutorService executor;
|
||||
private final AtomicBoolean running=new AtomicBoolean(false);
|
||||
private final boolean testProfile;
|
||||
private ScheduledFuture<?> poller;
|
||||
public FeishuDirectorySyncDispatcher(FeishuDirectorySyncWorker worker,
|
||||
@Qualifier("feishuDirectoryWorkerExecutor") ScheduledExecutorService executor, Environment environment){this.worker=worker;this.executor=executor;this.testProfile=java.util.Arrays.stream(environment.getActiveProfiles()).anyMatch("test"::equalsIgnoreCase);}
|
||||
@Override public void start(){if(running.compareAndSet(false,true)&&!testProfile)poller=executor.scheduleWithFixedDelay(this::drainSafely,0,1, TimeUnit.SECONDS);}
|
||||
public void wake(){if(!running.get()||testProfile)return;try{executor.execute(this::drainSafely);}catch(RejectedExecutionException ignored){/* row remains durable */}}
|
||||
private void drainSafely(){if(!running.get())return;try{while(running.get()&&worker.runOne()){} }catch(Throwable ignored){log.warn("Feishu directory dispatcher iteration failed");}}
|
||||
@Override public void stop(){running.set(false);if(poller!=null)poller.cancel(false);}
|
||||
@Override public void stop(Runnable callback){stop();callback.run();}
|
||||
@Override public boolean isRunning(){return running.get();}
|
||||
@Override public boolean isAutoStartup(){return true;}
|
||||
@Override public int getPhase(){return Integer.MAX_VALUE-100;}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/** Performs one claimed attempt. Feishu HTTP is never inside a DB transaction. */
|
||||
@Component
|
||||
@Slf4j
|
||||
public class FeishuDirectorySyncWorker {
|
||||
private final FeishuDirectoryRunStore runs;
|
||||
private final FeishuTenantTokenService tokens;
|
||||
private final FeishuDirectoryClient client;
|
||||
private final FeishuDirectoryPublisher publisher;
|
||||
@Qualifier("feishuDirectoryHeartbeatExecutor")
|
||||
private final ScheduledExecutorService heartbeatExecutor;
|
||||
|
||||
public FeishuDirectorySyncWorker(FeishuDirectoryRunStore runs, FeishuTenantTokenService tokens,
|
||||
FeishuDirectoryClient client, FeishuDirectoryPublisher publisher,
|
||||
@Qualifier("feishuDirectoryHeartbeatExecutor") ScheduledExecutorService heartbeatExecutor) {
|
||||
this.runs=runs;this.tokens=tokens;this.client=client;this.publisher=publisher;this.heartbeatExecutor=heartbeatExecutor;
|
||||
}
|
||||
|
||||
public boolean runOne() {
|
||||
FeishuDirectoryRunStore.Claim claim=runs.claimNext(); if(claim==null)return false;
|
||||
AtomicBoolean leaseLost=new AtomicBoolean(false);
|
||||
ScheduledFuture<?> heartbeat=heartbeatExecutor.scheduleAtFixedRate(()->{
|
||||
try{if(!runs.heartbeat(claim))leaseLost.set(true);}catch(RuntimeException ex){leaseLost.set(true);}
|
||||
},10,10, TimeUnit.SECONDS);
|
||||
String phase="CONFIGURATION";
|
||||
boolean succeeded=false;
|
||||
try{
|
||||
FeishuTenantTokenService.Context context=tokens.capture();
|
||||
if(!tokens.syncEnabled())throw FeishuTenantTokenService.syncDisabled();
|
||||
phase="FETCH";
|
||||
FeishuDirectoryClient.Snapshot snapshot=client.fetch(context);
|
||||
if(leaseLost.get())throw FeishuTenantTokenService.ownershipLost();
|
||||
phase="PUBLICATION";
|
||||
publisher.publish(claim,context,snapshot);
|
||||
succeeded=true;
|
||||
}catch(Throwable failure){
|
||||
String code=FeishuDirectoryService.safeDiagnostic(failure,phase);
|
||||
log.warn("Feishu directory attempt failed: runId={}, attempt={}, phase={}, errorCode={}, failureType={}",
|
||||
claim.getRunId(),claim.getAttempt(),phase,code,FeishuDirectoryService.safeFailureType(failure));
|
||||
runs.recordFailure(claim,code,FeishuDirectoryService.failureMessage(code));
|
||||
}finally{heartbeat.cancel(false);}
|
||||
return succeeded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Converts JDBC temporal values using the timezone configured for the MySQL connection. */
|
||||
@Component
|
||||
public final class FeishuDirectoryTime {
|
||||
private final ZoneId databaseZone;
|
||||
|
||||
public FeishuDirectoryTime(@Value("${database.time-zone}") String databaseZone) {
|
||||
if (databaseZone == null || databaseZone.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("database.time-zone must be a valid IANA timezone");
|
||||
}
|
||||
try {
|
||||
this.databaseZone = ZoneId.of(databaseZone.trim());
|
||||
} catch (RuntimeException invalid) {
|
||||
throw new IllegalArgumentException("database.time-zone must be a valid IANA timezone: " + databaseZone, invalid);
|
||||
}
|
||||
}
|
||||
|
||||
Instant instant(Object value) {
|
||||
if (value instanceof Instant) return (Instant) value;
|
||||
if (value instanceof OffsetDateTime) return ((OffsetDateTime) value).toInstant();
|
||||
if (value instanceof LocalDateTime) return ((LocalDateTime) value).atZone(databaseZone).toInstant();
|
||||
if (value instanceof Timestamp) return ((Timestamp) value).toInstant();
|
||||
return value instanceof java.util.Date ? ((java.util.Date) value).toInstant() : null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -77,7 +77,7 @@ public class FeishuLoginPersistenceService {
|
||||
public SysUser completeLocal(Long id) {
|
||||
return tx.execute(s -> {
|
||||
FeishuDirectoryLock.acquire(jdbc);
|
||||
SysUser fresh = locked(id); access.requireAllowed(fresh);
|
||||
SysUser fresh = locked(id); access.requireAllowedUnderDirectoryLock(fresh);
|
||||
jdbc.update("UPDATE sys_user SET last_login_at=? WHERE id=?", Timestamp.valueOf(LocalDateTime.now()), id);
|
||||
em.refresh(fresh); return fresh;
|
||||
});
|
||||
|
||||
@@ -12,11 +12,13 @@ import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@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 RATE_LIMIT_CODE = BigInteger.valueOf(99991400L);
|
||||
private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
|
||||
private final IntegrationConfigReader config;
|
||||
private final FeishuDirectorySettings settings;
|
||||
@@ -55,8 +57,11 @@ public class FeishuTenantTokenService {
|
||||
|| !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()));
|
||||
+ "\napi=directory-v1-filter;employee_id_type=open_id;department_id_type=open_department_id"
|
||||
+ ";department_filter=parent_department_id:eq:json-string:bfs-root-0"
|
||||
+ ";employee_transport_partition=work_info.staff_status:eq:1,2,3,4,5:not-projected:not-persisted"
|
||||
+ ";policy=directory-v1-4\n"
|
||||
+ settings.getCredentialRevision()));
|
||||
}
|
||||
|
||||
public boolean syncEnabled() {
|
||||
@@ -70,35 +75,70 @@ public class FeishuTenantTokenService {
|
||||
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 deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(settings.elapsed());
|
||||
int retries=0;
|
||||
while(true){
|
||||
try {
|
||||
ResponseEntity<JsonNode> exchange=http.exchange(API + "/auth/v3/tenant_access_token/internal",
|
||||
HttpMethod.POST,new HttpEntity<>(body),JsonNode.class);
|
||||
JsonNode response=exchange.getBody();
|
||||
BigInteger responseCode = responseCode(response);
|
||||
if (RATE_LIMIT_CODE.equals(responseCode)) {
|
||||
DiagnosticFailure limited=diagnostic("FEISHU_CODE_99991400");
|
||||
if(retries++>=settings.maxRetries())throw limited;
|
||||
awaitRetry(reset(exchange.getHeaders()),retries,deadline,limited);
|
||||
continue;
|
||||
}
|
||||
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);
|
||||
throw code == null ? diagnostic("TOKEN_RESPONSE_INVALID") : diagnostic("FEISHU_CODE_" + code);
|
||||
boolean limited=ex.getStatusCode().value()==429||RATE_LIMIT_CODE.equals(responseCode(response));
|
||||
if(limited){
|
||||
DiagnosticFailure failure=code!=null?diagnostic("FEISHU_CODE_"+code):diagnostic("HTTP_STATUS_429");
|
||||
if(retries++>=settings.maxRetries())throw failure;
|
||||
awaitRetry(reset(ex.getResponseHeaders()),retries,deadline,failure);
|
||||
continue;
|
||||
}
|
||||
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");
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
private static void awaitRetry(Long resetSeconds,int retry,long deadline,DiagnosticFailure exhausted){
|
||||
long delay=resetSeconds==null?Math.min(2000L,100L<<Math.min(4,retry-1)):
|
||||
(resetSeconds>Long.MAX_VALUE/1000L?Long.MAX_VALUE:resetSeconds*1000L);
|
||||
long remaining=TimeUnit.NANOSECONDS.toMillis(deadline-System.nanoTime());
|
||||
if(remaining<=0||delay>=remaining)throw exhausted;
|
||||
try{Thread.sleep(Math.max(1L,delay));}
|
||||
catch(InterruptedException ex){Thread.currentThread().interrupt();throw diagnostic("TOKEN_REQUEST_FAILED");}
|
||||
}
|
||||
|
||||
private static Long reset(HttpHeaders headers){
|
||||
if(headers==null)return null;
|
||||
String value=headers.getFirst("x-ogw-ratelimit-reset");
|
||||
if(value==null||!value.trim().matches("[0-9]{1,10}"))return null;
|
||||
try{return Long.valueOf(value.trim());}catch(NumberFormatException ex){return null;}
|
||||
}
|
||||
|
||||
static DiagnosticFailure diagnostic(String code) {
|
||||
return new DiagnosticFailure(isSafeDiagnostic(code) ? code : "DIRECTORY_UNAVAILABLE");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.finance.system.adapter.feishu;
|
||||
|
||||
import com.finance.system.entity.*;
|
||||
import com.finance.system.util.Sha256;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/** Canonical representation shared by preview validation and Feishu form generation. */
|
||||
public final class ReimbursementCanonicalizer {
|
||||
private ReimbursementCanonicalizer() { }
|
||||
|
||||
public static String fingerprint(ReimApplication app, SysUser applicant, SysDepartment department,
|
||||
SysExpenseType expenseType, SysBankAccount bank,
|
||||
List<ReimExpenseItem> sourceItems) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
field(out, "applicationNo", app.getApplicationNo());
|
||||
field(out, "title", app.getTitle());
|
||||
field(out, "description", app.getDescription());
|
||||
field(out, "sourceDocNo", app.getSourceDocNo());
|
||||
field(out, "applicantId", app.getApplicantId());
|
||||
field(out, "applicantEmployeeNo", applicant == null ? null : applicant.getEmployeeNo());
|
||||
field(out, "applicantName", applicant == null ? null : applicant.getRealName());
|
||||
field(out, "applicantFeishuUserId", applicant == null ? null : applicant.getFeishuUserId());
|
||||
field(out, "applicantFeishuOpenId", applicant == null ? null : applicant.getFeishuOpenId());
|
||||
field(out, "departmentId", app.getDepartmentId());
|
||||
field(out, "departmentName", department == null ? null : department.getDeptName());
|
||||
field(out, "expenseTypeId", app.getExpenseTypeId());
|
||||
field(out, "expenseTypeName", expenseType == null ? null : expenseType.getTypeName());
|
||||
field(out, "category", app.getCategory());
|
||||
field(out, "totalAmount", money(app.getTotalAmount()));
|
||||
field(out, "payeeName", app.getPayeeName());
|
||||
field(out, "payeeBankId", app.getPayeeBankId());
|
||||
field(out, "bankName", bank == null ? null : bank.getBankName());
|
||||
field(out, "branchName", bank == null ? null : bank.getBranchName());
|
||||
field(out, "accountName", bank == null ? null : bank.getAccountName());
|
||||
field(out, "accountNo", bank == null ? null : bank.getAccountNo());
|
||||
field(out, "accountNoMask", bank == null ? null : bank.getAccountNoMask());
|
||||
for (ReimExpenseItem item : orderedItems(sourceItems)) {
|
||||
field(out, "item.seq", item.getSeqNo());
|
||||
field(out, "item.date", item.getExpenseDate());
|
||||
field(out, "item.category", item.getCategory());
|
||||
field(out, "item.description", item.getDescription());
|
||||
field(out, "item.amount", money(item.getAmount()));
|
||||
}
|
||||
return Sha256.hex(out.toString());
|
||||
}
|
||||
|
||||
public static List<ReimExpenseItem> orderedItems(List<ReimExpenseItem> items) {
|
||||
List<ReimExpenseItem> ordered = new ArrayList<>(items == null ? Collections.emptyList() : items);
|
||||
ordered.sort(Comparator.comparing(ReimExpenseItem::getSeqNo, Comparator.nullsLast(Integer::compareTo))
|
||||
.thenComparing(ReimExpenseItem::getId, Comparator.nullsLast(Long::compareTo)));
|
||||
return ordered;
|
||||
}
|
||||
|
||||
public static String money(BigDecimal amount) {
|
||||
return amount == null ? "" : amount.toPlainString();
|
||||
}
|
||||
|
||||
private static void field(StringBuilder out, String name, Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
out.append(name.length()).append(':').append(name).append('=')
|
||||
.append(text.length()).append(':').append(text).append('|');
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -68,18 +70,22 @@ public class KingdeeClient {
|
||||
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");
|
||||
if (body != null && loginSucceeded(body)) {
|
||||
Map<String, Object> context = asMap(body.get("Context"));
|
||||
Map<String, Object> result = asMap(body.get("Result"));
|
||||
String token = text(context.get("SessionId"));
|
||||
if (token == null) token = text(result.get("SessionId"));
|
||||
if (token != null) {
|
||||
this.sessionToken = token;
|
||||
this.sessionExpireTime = System.currentTimeMillis() + 3600000; // 1小时过期
|
||||
this.sessionConfigFingerprint = configFingerprint();
|
||||
return this.sessionToken;
|
||||
}
|
||||
}
|
||||
throw new BusinessException("金蝶登录失败: " + (body != null ? body.get("Message") : "未知错误"));
|
||||
throw new BusinessException("金蝶登录失败");
|
||||
} catch (Exception e) {
|
||||
log.error("金蝶云星空登录失败", e);
|
||||
// Never log the remote exception: it can contain the response body or account data.
|
||||
log.error("金蝶云星空登录失败");
|
||||
throw new BusinessException("金蝶云星空连接失败");
|
||||
}
|
||||
}
|
||||
@@ -122,7 +128,7 @@ public class KingdeeClient {
|
||||
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
|
||||
return response.getBody();
|
||||
} catch (Exception e) {
|
||||
log.error("金蝶查看单据失败: formId={}, billNo={}", formId, billNo, e);
|
||||
log.error("金蝶查看单据失败: formId={}, billNo={}", formId, billNo);
|
||||
throw new BusinessException("金蝶单据查询失败");
|
||||
}
|
||||
}
|
||||
@@ -131,30 +137,42 @@ public class KingdeeClient {
|
||||
* 查询单据列表
|
||||
*/
|
||||
public List<Map<String, Object>> query(String formId, String filterString) {
|
||||
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Query.common.kdsvc";
|
||||
return query(formId, filterString, "*", 0, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries a page of a Kingdee document. The old two argument method is
|
||||
* deliberately kept as a compatibility wrapper because it is used by the
|
||||
* outbound integration code and by older callers.
|
||||
*
|
||||
* @param fieldKeys comma separated Kingdee field keys (or *)
|
||||
* @param startRow zero based offset
|
||||
* @param topRowCount maximum number of rows to return
|
||||
*/
|
||||
public List<Map<String, Object>> query(String formId, String filterString,
|
||||
String fieldKeys, int startRow, int topRowCount) {
|
||||
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc";
|
||||
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("FormId", formId);
|
||||
data.put("FieldKeys", "*");
|
||||
data.put("FieldKeys", fieldKeys == null || fieldKeys.trim().isEmpty() ? "*" : fieldKeys);
|
||||
data.put("FilterString", filterString);
|
||||
data.put("OrderString", "FDate DESC");
|
||||
data.put("TopRowCount", 100);
|
||||
data.put("OrderString", "FBillNo ASC");
|
||||
data.put("StartRow", Math.max(0, startRow));
|
||||
int boundedTop = Math.max(1, Math.min(100, topRowCount));
|
||||
// ExecuteBillQuery uses Limit for page size. TopRowCount must remain
|
||||
// zero or some K3Cloud versions cap the entire result set at page one.
|
||||
data.put("TopRowCount", 0);
|
||||
data.put("Limit", boundedTop);
|
||||
|
||||
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();
|
||||
ResponseEntity<Object> response = restTemplate.postForEntity(url, request, Object.class);
|
||||
return queryRows(response.getBody(), fieldKeys);
|
||||
} catch (Exception e) {
|
||||
log.error("金蝶查询单据失败: formId={}", formId, e);
|
||||
log.error("金蝶查询单据失败: formId={}", formId);
|
||||
throw new BusinessException("金蝶单据查询失败");
|
||||
}
|
||||
}
|
||||
@@ -173,11 +191,11 @@ public class KingdeeClient {
|
||||
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"));
|
||||
throw new BusinessException("金蝶操作失败");
|
||||
}
|
||||
return body;
|
||||
} catch (Exception e) {
|
||||
log.error("金蝶API调用失败: formId={}", formId, e);
|
||||
log.error("金蝶API调用失败: formId={}", formId);
|
||||
throw new BusinessException("金蝶云星空操作失败");
|
||||
}
|
||||
}
|
||||
@@ -185,10 +203,71 @@ public class KingdeeClient {
|
||||
private HttpHeaders buildHeaders() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("SessionId", getValidSession());
|
||||
String session = getValidSession();
|
||||
headers.set("kdservice-sessionid", session);
|
||||
// Keep the legacy header for older K3Cloud gateways during migration.
|
||||
headers.set("SessionId", session);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private boolean loginSucceeded(Map<String, Object> body) {
|
||||
if (Boolean.TRUE.equals(body.get("IsSuccess"))) return true;
|
||||
Object resultType = body.get("LoginResultType");
|
||||
return "1".equals(String.valueOf(resultType));
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> queryRows(Object body, String fieldKeys) {
|
||||
if (body == null) throw new BusinessException("金蝶单据查询失败");
|
||||
Object rowsBody = body;
|
||||
for (int depth = 0; depth < 5 && rowsBody instanceof Map; depth++) {
|
||||
Map<String, Object> map = asMap(rowsBody);
|
||||
// Only documented response envelopes carry operation status.
|
||||
// Do not recursively inspect data rows: a form may legitimately
|
||||
// contain a business field named IsSuccess with value false.
|
||||
if (envelopeFailed(map)) throw new BusinessException("金蝶单据查询失败");
|
||||
if (map.containsKey("Result")) rowsBody = map.get("Result");
|
||||
else if (map.containsKey("Data")) rowsBody = map.get("Data");
|
||||
else throw new BusinessException("金蝶单据查询响应格式错误");
|
||||
}
|
||||
if (!(rowsBody instanceof List)) throw new BusinessException("金蝶单据查询响应格式错误");
|
||||
List<?> rawRows = (List<?>) rowsBody;
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (String key : (fieldKeys == null ? "" : fieldKeys).split(",")) {
|
||||
if (!key.trim().isEmpty()) keys.add(key.trim());
|
||||
}
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (Object rawRow : rawRows) {
|
||||
if (rawRow instanceof Map) rows.add(objectMapper.convertValue(rawRow, new TypeReference<Map<String, Object>>() {}));
|
||||
else if (rawRow instanceof List) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
List<?> values = (List<?>) rawRow;
|
||||
for (int i = 0; i < keys.size() && i < values.size(); i++) row.put(keys.get(i), values.get(i));
|
||||
rows.add(row);
|
||||
} else throw new BusinessException("金蝶单据查询响应格式错误");
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private boolean envelopeFailed(Map<String, Object> envelope) {
|
||||
if (falseValue(envelope.get("IsSuccess"))) return true;
|
||||
Object responseStatus = envelope.get("ResponseStatus");
|
||||
return responseStatus instanceof Map && falseValue(asMap(responseStatus).get("IsSuccess"));
|
||||
}
|
||||
|
||||
private boolean falseValue(Object value) {
|
||||
return Boolean.FALSE.equals(value) || (value != null && "false".equalsIgnoreCase(String.valueOf(value)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> asMap(Object value) {
|
||||
return value instanceof Map ? (Map<String, Object>) value : Collections.emptyMap();
|
||||
}
|
||||
|
||||
private String text(Object value) {
|
||||
String result = value == null ? null : String.valueOf(value).trim();
|
||||
return result == null || result.isEmpty() ? null : result;
|
||||
}
|
||||
|
||||
private String baseUrl() {
|
||||
String raw = configured("baseUrl", kingdeeConfig.getBaseUrl());
|
||||
if (!hasText(raw)) return raw;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.finance.system.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Configuration
|
||||
public class FeishuDirectoryAsyncConfig {
|
||||
@Bean(name="feishuDirectoryWorkerExecutor",destroyMethod="shutdownNow")
|
||||
public ScheduledExecutorService feishuDirectoryWorkerExecutor(){return Executors.newSingleThreadScheduledExecutor(factory("feishu-directory-worker-"));}
|
||||
@Bean(name="feishuDirectoryHeartbeatExecutor",destroyMethod="shutdownNow")
|
||||
public ScheduledExecutorService feishuDirectoryHeartbeatExecutor(){return Executors.newSingleThreadScheduledExecutor(factory("feishu-directory-heartbeat-"));}
|
||||
private static ThreadFactory factory(String prefix){AtomicInteger sequence=new AtomicInteger();return task->{Thread thread=new Thread(task,prefix+sequence.incrementAndGet());thread.setDaemon(true);return thread;};}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.finance.system.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
@Configuration
|
||||
public class KingdeeAsyncSyncConfig {
|
||||
@Bean(name = "kingdeeSyncExecutor")
|
||||
public ThreadPoolTaskExecutor kingdeeSyncExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(2);
|
||||
executor.setMaxPoolSize(4);
|
||||
executor.setQueueCapacity(100);
|
||||
executor.setThreadNamePrefix("kingdee-sync-");
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
|
||||
executor.setWaitForTasksToCompleteOnShutdown(false);
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Bean(name = "kingdeeSyncHeartbeatScheduler")
|
||||
public ThreadPoolTaskScheduler kingdeeSyncHeartbeatScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(8);
|
||||
scheduler.setThreadNamePrefix("kingdee-sync-heartbeat-");
|
||||
scheduler.setWaitForTasksToCompleteOnShutdown(false);
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
@Bean(name = {"kingdeeSyncDeadlineScheduler", "taskScheduler"})
|
||||
public ThreadPoolTaskScheduler kingdeeSyncDeadlineScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(2);
|
||||
scheduler.setThreadNamePrefix("kingdee-sync-deadline-");
|
||||
scheduler.setWaitForTasksToCompleteOnShutdown(false);
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
@@ -4,43 +4,80 @@ 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.SysRole;
|
||||
import com.finance.system.entity.SysUser;
|
||||
import com.finance.system.entity.SysUserGroup;
|
||||
import com.finance.system.entity.SysUserGroupMember;
|
||||
import com.finance.system.entity.SysUserGroupRole;
|
||||
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.SysRoleRepository;
|
||||
import com.finance.system.repository.SysUserRepository;
|
||||
import com.finance.system.repository.SysUserGroupMemberRepository;
|
||||
import com.finance.system.repository.SysUserGroupRepository;
|
||||
import com.finance.system.repository.SysUserGroupRoleRepository;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Safe, deterministic local-only seed data. Production never runs this component. */
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class LocalDataInitializer implements CommandLineRunner {
|
||||
static final String ADMIN_EMPLOYEE_NO = "A9001";
|
||||
static final String DEFAULT_LOCAL_PASSWORD = "local-password";
|
||||
private final SysUserRepository users;
|
||||
private final SysDepartmentRepository departments;
|
||||
private final SysExpenseTypeRepository expenseTypes;
|
||||
private final SysBankAccountRepository bankAccounts;
|
||||
private final SysApprovalNodeRepository nodes;
|
||||
private final SysRoleRepository roles;
|
||||
private final SysUserGroupRepository groups;
|
||||
private final SysUserGroupMemberRepository members;
|
||||
private final SysUserGroupRoleRepository groupRoles;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final boolean superAdminBootstrapEnabled;
|
||||
private final String superAdminBootstrapPassword;
|
||||
|
||||
public LocalDataInitializer(SysUserRepository users, SysDepartmentRepository departments,
|
||||
SysExpenseTypeRepository expenseTypes, SysBankAccountRepository bankAccounts,
|
||||
SysApprovalNodeRepository nodes,
|
||||
PasswordEncoder passwordEncoder) {
|
||||
SysExpenseTypeRepository expenseTypes, SysBankAccountRepository bankAccounts,
|
||||
SysApprovalNodeRepository nodes, SysRoleRepository roles,
|
||||
SysUserGroupRepository groups, SysUserGroupMemberRepository members,
|
||||
SysUserGroupRoleRepository groupRoles,
|
||||
PasswordEncoder passwordEncoder,
|
||||
@Value("${finance.local-bootstrap.super-admin.enabled:false}") boolean superAdminBootstrapEnabled,
|
||||
@Value("${finance.local-bootstrap.super-admin.password:}") String superAdminBootstrapPassword) {
|
||||
this.users = users;
|
||||
this.departments = departments;
|
||||
this.expenseTypes = expenseTypes;
|
||||
this.bankAccounts = bankAccounts;
|
||||
this.nodes = nodes;
|
||||
this.roles = roles;
|
||||
this.groups = groups;
|
||||
this.members = members;
|
||||
this.groupRoles = groupRoles;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.superAdminBootstrapEnabled = superAdminBootstrapEnabled;
|
||||
this.superAdminBootstrapPassword = superAdminBootstrapPassword;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) {
|
||||
if (users.findByEmployeeNo("E1001") != null) return;
|
||||
if (superAdminBootstrapEnabled) validateBootstrapPassword(superAdminBootstrapPassword);
|
||||
|
||||
if (users.findByEmployeeNo("E1001") != null) {
|
||||
if (superAdminBootstrapEnabled) bootstrapSuperAdmin();
|
||||
return;
|
||||
}
|
||||
|
||||
SysDepartment department = new SysDepartment();
|
||||
department.setDeptCode("FIN");
|
||||
@@ -49,12 +86,13 @@ public class LocalDataInitializer implements CommandLineRunner {
|
||||
department.setStatus("ACTIVE");
|
||||
department = departments.save(department);
|
||||
|
||||
SysUser employee = user("E1001", "本地员工", "EMPLOYEE", "员工", department.getId());
|
||||
SysUser employee = user("E1001", "本地员工", "EMPLOYEE", "员工", department.getId(), DEFAULT_LOCAL_PASSWORD);
|
||||
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()));
|
||||
assignBootstrapRole(employee, "EMPLOYEE");
|
||||
assignBootstrapRole(users.save(user("E1002", "本地员工二", "EMPLOYEE", "员工", department.getId(), DEFAULT_LOCAL_PASSWORD)), "EMPLOYEE");
|
||||
assignBootstrapRole(users.save(user("F2001", "应付会计", "FINANCE", "应付会计", department.getId(), DEFAULT_LOCAL_PASSWORD)), "FINANCE");
|
||||
assignBootstrapRole(users.save(user("M3001", "财务经理", "FINANCE", "财务经理", department.getId(), DEFAULT_LOCAL_PASSWORD)), "FINANCE");
|
||||
if (superAdminBootstrapEnabled) bootstrapSuperAdmin(department.getId());
|
||||
|
||||
SysExpenseType type = new SysExpenseType();
|
||||
type.setTypeCode("TRAVEL");
|
||||
@@ -79,14 +117,129 @@ public class LocalDataInitializer implements CommandLineRunner {
|
||||
nodes.save(node("NODE_MANAGER", "财务经理审批", "FINANCE_MANAGER", 2));
|
||||
}
|
||||
|
||||
private SysUser user(String number, String name, String type, String position, Long departmentId) {
|
||||
private void bootstrapSuperAdmin() {
|
||||
SysDepartment department = departments.findByDeptCode("FIN");
|
||||
if (department == null || department.getId() == null) {
|
||||
throw new IllegalStateException("启用本地超级管理员引导时必须存在 FIN 部门");
|
||||
}
|
||||
bootstrapSuperAdmin(department.getId());
|
||||
}
|
||||
|
||||
private void bootstrapSuperAdmin(Long departmentId) {
|
||||
requiredActiveRole("SUPER_ADMIN");
|
||||
SysUser existing = users.findByEmployeeNo(ADMIN_EMPLOYEE_NO);
|
||||
if (existing != null) {
|
||||
assertExistingAdminIsBootstrapOwned(existing);
|
||||
return;
|
||||
}
|
||||
SysUser admin = users.save(user(ADMIN_EMPLOYEE_NO, "系统管理员", "EMPLOYEE", "管理员",
|
||||
departmentId, superAdminBootstrapPassword));
|
||||
assignBootstrapRole(admin, "SUPER_ADMIN");
|
||||
}
|
||||
|
||||
private void assertExistingAdminIsBootstrapOwned(SysUser user) {
|
||||
if (user.getId() == null || !"ACTIVE".equalsIgnoreCase(user.getStatus())
|
||||
|| !"EMPLOYEE".equalsIgnoreCase(user.getUserType())) {
|
||||
throw new IllegalStateException("A9001 已存在但不是有效的本地引导账号;拒绝提升或修改");
|
||||
}
|
||||
if (user.getPasswordHash() == null
|
||||
|| !passwordEncoder.matches(superAdminBootstrapPassword, user.getPasswordHash())
|
||||
|| passwordEncoder.matches(DEFAULT_LOCAL_PASSWORD, user.getPasswordHash())) {
|
||||
throw new IllegalStateException("A9001 已存在但密码不匹配本次安全引导配置;拒绝修改");
|
||||
}
|
||||
SysRole role = requiredActiveRole("SUPER_ADMIN");
|
||||
String groupCode = groupCode(user);
|
||||
SysUserGroup group = groups.findByGroupCode(groupCode).orElse(null);
|
||||
if (group == null || !bootstrapMarker(user).equals(group.getDescription())
|
||||
|| !Boolean.TRUE.equals(group.getBuiltIn()) || !"ACTIVE".equalsIgnoreCase(group.getStatus())) {
|
||||
throw new IllegalStateException("A9001 已存在且无法证明由本地引导创建;拒绝提升");
|
||||
}
|
||||
List<SysUserGroupMember> groupMembers = members.findByIdGroupId(group.getId());
|
||||
List<SysUserGroupMember> userMemberships = members.findByIdUserId(user.getId());
|
||||
List<SysUserGroupRole> assignedRoles = groupRoles.findByIdGroupId(group.getId());
|
||||
if (groupMembers.size() != 1 || !user.getId().equals(groupMembers.get(0).getId().getUserId())
|
||||
|| userMemberships.size() != 1 || !group.getId().equals(userMemberships.get(0).getId().getGroupId())
|
||||
|| assignedRoles.size() != 1 || !role.getId().equals(assignedRoles.get(0).getId().getRoleId())) {
|
||||
throw new IllegalStateException("A9001 本地引导所有权记录冲突;拒绝修改");
|
||||
}
|
||||
}
|
||||
|
||||
private void assignBootstrapRole(SysUser user, String roleCode) {
|
||||
if (user == null || user.getId() == null) throw new IllegalStateException("本地引导用户保存失败");
|
||||
SysRole expected = roles.findByRoleCode(roleCode).orElse(null);
|
||||
if (expected == null || expected.getId() == null || !"ACTIVE".equalsIgnoreCase(expected.getStatus())) {
|
||||
if ("SUPER_ADMIN".equals(roleCode)) requiredActiveRole(roleCode);
|
||||
return;
|
||||
}
|
||||
String groupCode = groupCode(user);
|
||||
String marker = bootstrapMarker(user);
|
||||
SysUserGroup group = groups.findByGroupCode(groupCode).orElse(null);
|
||||
if (group == null) {
|
||||
group = SysUserGroup.builder().groupCode(groupCode).groupName(user.getRealName() + "(本地)")
|
||||
.description(marker).status("ACTIVE").builtIn(true).build();
|
||||
group = groups.save(group);
|
||||
} else if (!marker.equals(group.getDescription()) || !Boolean.TRUE.equals(group.getBuiltIn())
|
||||
|| !"ACTIVE".equalsIgnoreCase(group.getStatus())) {
|
||||
throw new IllegalStateException("本地初始化用户组编码已被占用: " + groupCode);
|
||||
}
|
||||
|
||||
List<SysUserGroupMember> groupMembers = members.findByIdGroupId(group.getId());
|
||||
for (SysUserGroupMember membership : groupMembers) {
|
||||
if (!user.getId().equals(membership.getId().getUserId())) {
|
||||
throw new IllegalStateException("本地初始化专属用户组包含其他用户: " + groupCode);
|
||||
}
|
||||
}
|
||||
List<SysUserGroupMember> userMemberships = members.findByIdUserId(user.getId());
|
||||
for (SysUserGroupMember membership : userMemberships) {
|
||||
if (!group.getId().equals(membership.getId().getGroupId())) {
|
||||
throw new IllegalStateException("本地初始化用户已属于其他用户组: " + user.getEmployeeNo());
|
||||
}
|
||||
}
|
||||
List<SysUserGroupRole> assignedRoles = groupRoles.findByIdGroupId(group.getId());
|
||||
for (SysUserGroupRole assigned : assignedRoles) {
|
||||
if (!expected.getId().equals(assigned.getId().getRoleId())) {
|
||||
throw new IllegalStateException("本地初始化用户组包含其他角色: " + groupCode);
|
||||
}
|
||||
}
|
||||
if (assignedRoles.isEmpty()) groupRoles.save(new SysUserGroupRole(group.getId(), expected.getId()));
|
||||
if (userMemberships.isEmpty()) members.save(new SysUserGroupMember(group.getId(), user.getId()));
|
||||
}
|
||||
|
||||
private SysRole requiredActiveRole(String roleCode) {
|
||||
SysRole expected = roles.findByRoleCode(roleCode).orElse(null);
|
||||
if (expected == null || expected.getId() == null || !"ACTIVE".equalsIgnoreCase(expected.getStatus())) {
|
||||
throw new IllegalStateException("本地初始化所需角色不存在或未启用: " + roleCode);
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
|
||||
private String groupCode(SysUser user) {
|
||||
return "LOCAL_USER_" + user.getEmployeeNo().replaceAll("[^A-Za-z0-9_-]", "_").toUpperCase();
|
||||
}
|
||||
|
||||
private String bootstrapMarker(SysUser user) {
|
||||
return "Local bootstrap group for " + user.getEmployeeNo();
|
||||
}
|
||||
|
||||
private void validateBootstrapPassword(String password) {
|
||||
boolean strong = password != null && password.length() >= 16
|
||||
&& password.matches(".*[A-Z].*") && password.matches(".*[a-z].*")
|
||||
&& password.matches(".*[0-9].*") && password.matches(".*[^A-Za-z0-9\\s].*")
|
||||
&& !password.toLowerCase(Locale.ROOT).contains("local-password")
|
||||
&& !password.toUpperCase(Locale.ROOT).contains(ADMIN_EMPLOYEE_NO);
|
||||
if (!strong) {
|
||||
throw new IllegalStateException("finance.local-bootstrap.super-admin.password 必须至少 16 位并包含大小写字母、数字和特殊字符");
|
||||
}
|
||||
}
|
||||
|
||||
private SysUser user(String number, String name, String type, String position, Long departmentId, String password) {
|
||||
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.setPasswordHash(passwordEncoder.encode(password));
|
||||
user.setStatus("ACTIVE");
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ public class SecurityConfig {
|
||||
.cors(cors -> {})
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> {
|
||||
if (isLocalProfile()) {
|
||||
if (isDevelopmentProfile()) {
|
||||
auth.antMatchers("/api/auth/login").permitAll();
|
||||
}
|
||||
auth
|
||||
@@ -41,7 +41,6 @@ public class SecurityConfig {
|
||||
.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();
|
||||
})
|
||||
@@ -60,9 +59,9 @@ public class SecurityConfig {
|
||||
return http.build();
|
||||
}
|
||||
|
||||
private boolean isLocalProfile() {
|
||||
private boolean isDevelopmentProfile() {
|
||||
for (String profile : environment.getActiveProfiles()) {
|
||||
if ("local".equalsIgnoreCase(profile)) {
|
||||
if ("local".equalsIgnoreCase(profile) || "test".equalsIgnoreCase(profile)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,13 +17,13 @@ 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")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<PageResponse<ReimApplicationSummary>>> getTasks(
|
||||
@RequestParam(defaultValue = "PENDING") String status,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@@ -35,12 +35,14 @@ public class AccountsPayableController {
|
||||
}
|
||||
|
||||
@GetMapping("/tasks/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> getTaskDetail(@PathVariable Long id) {
|
||||
ReimApplicationDetail detail = reimApplicationService.getApplicationDetail(id, AuditUtil.getCurrentUserId());
|
||||
return ResponseEntity.ok(ApiResponse.success(detail));
|
||||
}
|
||||
|
||||
@PostMapping("/approve")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.approval.decide')")
|
||||
public ResponseEntity<ApiResponse<Void>> approve(@RequestBody ApprovalActionRequest request) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
reimApprovalService.approve(request.getApplicationId(), userId, request.getComment());
|
||||
@@ -48,6 +50,7 @@ public class AccountsPayableController {
|
||||
}
|
||||
|
||||
@PostMapping("/reject")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.approval.decide')")
|
||||
public ResponseEntity<ApiResponse<Void>> reject(@RequestBody ApprovalActionRequest request) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
reimApprovalService.reject(request.getApplicationId(), userId,
|
||||
@@ -56,6 +59,7 @@ public class AccountsPayableController {
|
||||
}
|
||||
|
||||
@GetMapping("/history")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<List<ApprovalRecordDto>>> getHistory() {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
List<ApprovalRecordDto> history = reimApprovalService.getApprovalHistoryByUser(userId);
|
||||
|
||||
@@ -150,7 +150,7 @@ public class ApplicationController {
|
||||
* 获取付款申请列表(应付会计B视图,过滤 expenseType=员工报销类)
|
||||
*/
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listApplications(
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) String expenseType) {
|
||||
@@ -180,7 +180,7 @@ public class ApplicationController {
|
||||
* 获取付款申请详情
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> getApplicationDetail(@PathVariable Long id) {
|
||||
try {
|
||||
Map<String, Object> application = MOCK_APPLICATIONS.stream()
|
||||
|
||||
@@ -7,7 +7,6 @@ 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;
|
||||
@@ -23,7 +22,6 @@ 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;
|
||||
@@ -39,17 +37,12 @@ public class AuthController {
|
||||
private final FeishuAuthService feishuAuthService;
|
||||
private final Environment environment;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private RoleService roleService;
|
||||
private final 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()) {
|
||||
@@ -193,7 +186,7 @@ public class AuthController {
|
||||
* 获取所有用户列表
|
||||
*/
|
||||
@GetMapping("/users")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.users')")
|
||||
public ResponseEntity<ApiResponse<List<UserProfile>>> listUsers() {
|
||||
List<SysUser> users = sysUserRepository.findAll();
|
||||
List<UserProfile> profiles = users.stream()
|
||||
@@ -206,55 +199,19 @@ public class AuthController {
|
||||
* 更新用户角色
|
||||
*/
|
||||
@PutMapping("/users/{id}/role")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.user.legacy-role.change')")
|
||||
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)));
|
||||
return ResponseEntity.status(410)
|
||||
.body(ApiResponse.error(410, "用户角色只能通过用户组管理"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换用户状态
|
||||
*/
|
||||
@PutMapping("/users/{id}/status")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.user.status.change')")
|
||||
public ResponseEntity<ApiResponse<UserProfile>> toggleUserStatus(
|
||||
@PathVariable Long id,
|
||||
@RequestBody Map<String, String> request) {
|
||||
@@ -280,24 +237,18 @@ public class AuthController {
|
||||
.body(ApiResponse.error(404, "用户不存在"));
|
||||
}
|
||||
|
||||
user.setStatus(normalizedStatus);
|
||||
sysUserRepository.save(user);
|
||||
user = roleService.changeUserStatus(id, normalizedStatus, AuditUtil.getCurrentUserId());
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user)));
|
||||
}
|
||||
|
||||
/** Replaces direct role assignments; groups are intentionally managed by the group API. */
|
||||
/** Retired: roles are assigned only through the user-group API. */
|
||||
@PutMapping("/users/{id}/roles")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.user.role.assign')")
|
||||
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)));
|
||||
return ResponseEntity.status(410)
|
||||
.body(ApiResponse.error(410, "用户角色只能通过用户组管理"));
|
||||
}
|
||||
|
||||
private UserProfile buildUserProfile(SysUser user) {
|
||||
@@ -321,8 +272,9 @@ public class AuthController {
|
||||
.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()))
|
||||
.roleCodes(roleService.userRoleCodes(user.getId()))
|
||||
.groupNames(roleService.userGroupNames(user.getId()))
|
||||
.isSuperAdmin(roleService.isSuperAdmin(user.getId()))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.finance.system.controller;
|
||||
|
||||
import com.finance.system.dto.*;
|
||||
import com.finance.system.exception.BadRequestException;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import com.finance.system.service.ReimPaymentService;
|
||||
import com.finance.system.util.AuditUtil;
|
||||
@@ -20,12 +21,12 @@ 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")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.payments')")
|
||||
public ResponseEntity<ApiResponse<PageResponse<PaymentTaskDto>>> getTasks(
|
||||
@RequestParam(defaultValue = "UNPAID") String status,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@@ -38,12 +39,14 @@ public class CashierController {
|
||||
}
|
||||
|
||||
@GetMapping("/tasks/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.payments')")
|
||||
public ResponseEntity<ApiResponse<PaymentDetailDto>> getTaskDetail(@PathVariable Long id) {
|
||||
PaymentDetailDto detail = reimPaymentService.getPaymentDetail(id, AuditUtil.getCurrentUserId());
|
||||
return ResponseEntity.ok(ApiResponse.success(detail));
|
||||
}
|
||||
|
||||
@PostMapping("/pay")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.register')")
|
||||
public ResponseEntity<ApiResponse<PaymentResultDto>> executePayment(
|
||||
@RequestBody CreatePaymentRequest request,
|
||||
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) {
|
||||
@@ -56,6 +59,7 @@ public class CashierController {
|
||||
}
|
||||
|
||||
@PostMapping("/partial-pay")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.register')")
|
||||
public ResponseEntity<ApiResponse<PaymentResultDto>> processPartialPayment(
|
||||
@RequestBody CreatePaymentRequest request,
|
||||
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) {
|
||||
@@ -69,6 +73,7 @@ public class CashierController {
|
||||
}
|
||||
|
||||
@GetMapping("/history")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.payments')")
|
||||
public ResponseEntity<ApiResponse<List<PaymentRecordDto>>> getPaymentHistory() {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
List<PaymentRecordDto> history = reimPaymentService.getPaymentHistoryByOperator(userId);
|
||||
@@ -76,18 +81,26 @@ public class CashierController {
|
||||
}
|
||||
|
||||
@GetMapping("/payments/{paymentNo}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.payments')")
|
||||
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())) {
|
||||
String header = normalizeIdempotencyKey(headerValue);
|
||||
String body = normalizeIdempotencyKey(bodyValue);
|
||||
if (header != null && body != null && !header.equals(body)) {
|
||||
throw new BusinessException("Header 与 body 的幂等键不一致", 409);
|
||||
}
|
||||
if (hasHeader) return headerValue.trim();
|
||||
return hasBody ? bodyValue.trim() : null;
|
||||
return header != null ? header : body;
|
||||
}
|
||||
|
||||
private String normalizeIdempotencyKey(String value) {
|
||||
if (value == null) return null;
|
||||
String normalized = value.trim();
|
||||
if (!StringUtils.hasText(normalized)) return null;
|
||||
if (normalized.length() > 100) throw new BadRequestException("幂等键长度不能超过100个字符");
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public class DashboardController {
|
||||
private final DashboardService dashboardService;
|
||||
|
||||
@GetMapping("/stats")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'dashboard')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')")
|
||||
public ResponseEntity<ApiResponse<DashboardStats>> getStats() {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
DashboardStats stats = dashboardService.getDashboardStats(userId);
|
||||
@@ -28,7 +28,7 @@ public class DashboardController {
|
||||
}
|
||||
|
||||
@GetMapping("/recent")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'dashboard')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')")
|
||||
public ResponseEntity<ApiResponse<List<ReimApplicationSummary>>> getRecent(
|
||||
@RequestParam(defaultValue = "5") int limit) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.finance.system.controller;
|
||||
|
||||
import com.finance.system.adapter.feishu.FeishuDefinitionSyncService;
|
||||
import com.finance.system.dto.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/feishu/approval/definition")
|
||||
@RequiredArgsConstructor
|
||||
public class FeishuApprovalDefinitionController {
|
||||
private final FeishuDefinitionSyncService syncService;
|
||||
|
||||
@PostMapping("/sync")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.feishu.approval.sync')")
|
||||
public ResponseEntity<ApiResponse<FeishuDefinitionSyncResult>> sync() {
|
||||
return ResponseEntity.ok(ApiResponse.success(syncService.sync()));
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,14 @@ 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.entity.IntFeishuApproval;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import com.finance.system.exception.ResourceNotFoundException;
|
||||
import com.finance.system.repository.IntFeishuApprovalRepository;
|
||||
import com.finance.system.repository.SysWebhookEventRepository;
|
||||
import com.finance.system.service.FeishuWebhookInboxService;
|
||||
import com.finance.system.service.ReimApplicationService;
|
||||
import com.finance.system.util.AuditUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -15,6 +21,7 @@ import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -37,6 +44,14 @@ public class FeishuAuthController {
|
||||
private final FeishuApprovalService feishuApprovalService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SysWebhookEventRepository webhookEventRepository;
|
||||
private final IntFeishuApprovalRepository feishuApprovalRepository;
|
||||
private final ReimApplicationService reimApplicationService;
|
||||
private FeishuWebhookInboxService webhookInboxService;
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setWebhookInboxService(FeishuWebhookInboxService webhookInboxService) {
|
||||
this.webhookInboxService = webhookInboxService;
|
||||
}
|
||||
|
||||
@Value("${app.frontend-url:http://localhost:5173}")
|
||||
private String frontendUrl;
|
||||
@@ -63,7 +78,7 @@ public class FeishuAuthController {
|
||||
public ResponseEntity<Void> callback(
|
||||
@RequestParam("code") String code,
|
||||
@RequestParam(value = "state", required = false) String state) {
|
||||
log.info("收到飞书OAuth回调");
|
||||
log.info("Feishu OAuth callback received");
|
||||
|
||||
try {
|
||||
feishuAuthService.validateCallbackState(state);
|
||||
@@ -74,14 +89,14 @@ public class FeishuAuthController {
|
||||
return new ResponseEntity<>(headers, HttpStatus.FOUND);
|
||||
|
||||
} catch (BusinessException e) {
|
||||
log.warn("飞书登录失败: {}", e.getMessage());
|
||||
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败: " + e.getMessage());
|
||||
log.warn("Feishu OAuth callback rejected; category=business status={}", e.getStatusCode());
|
||||
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请重新发起授权");
|
||||
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());
|
||||
log.error("Feishu OAuth callback failed; category=internal");
|
||||
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请稍后重试");
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setLocation(URI.create(errorUrl));
|
||||
return new ResponseEntity<>(headers, HttpStatus.FOUND);
|
||||
@@ -92,7 +107,7 @@ public class FeishuAuthController {
|
||||
try {
|
||||
return URLEncoder.encode(value, "UTF-8");
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +116,6 @@ public class FeishuAuthController {
|
||||
* 处理审批实例状态变更、审批任务变更等事件
|
||||
*/
|
||||
@PostMapping("/webhook")
|
||||
@Transactional
|
||||
public ResponseEntity<Map<String, Object>> handleWebhook(
|
||||
@RequestBody String rawBody,
|
||||
@RequestHeader(value = "X-Lark-Signature", required = false) String signature,
|
||||
@@ -114,7 +128,7 @@ public class FeishuAuthController {
|
||||
return ResponseEntity.badRequest().body(responseMap(1, "invalid webhook body"));
|
||||
}
|
||||
|
||||
log.info("收到飞书Webhook请求: eventType={}", body.get("event_type"));
|
||||
log.info("Feishu webhook request received");
|
||||
|
||||
if (!feishuAuthService.isWebhookAuthorized(body, signature, timestamp, nonce, rawBody)) {
|
||||
return ResponseEntity.status(401).body(responseMap(1, "invalid webhook signature"));
|
||||
@@ -122,8 +136,11 @@ public class FeishuAuthController {
|
||||
|
||||
// 处理URL验证(飞书首次配置事件订阅时会发送验证请求)
|
||||
if (body.containsKey("challenge")) {
|
||||
String challenge = (String) body.get("challenge");
|
||||
log.info("飞书Webhook URL验证: challenge={}", challenge);
|
||||
Object challengeValue=body.get("challenge");
|
||||
if(!(challengeValue instanceof String)||((String)challengeValue).isEmpty()||((String)challengeValue).length()>512)
|
||||
return ResponseEntity.badRequest().body(responseMap(1,"invalid webhook challenge"));
|
||||
String challenge = (String) challengeValue;
|
||||
log.info("Feishu webhook verification request accepted");
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("challenge", challenge);
|
||||
return ResponseEntity.ok(result);
|
||||
@@ -194,11 +211,40 @@ public class FeishuAuthController {
|
||||
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();
|
||||
if(value==null)return null;String result=String.valueOf(value).trim();
|
||||
return result.isEmpty()||result.length()>200?null:result;
|
||||
}
|
||||
|
||||
private ResponseEntity<Map<String, Object>> processWebhookEvent(
|
||||
String eventId, Map<String, Object> body) {
|
||||
if (webhookInboxService != null) {
|
||||
FeishuWebhookInboxService.ClaimOutcome claim;
|
||||
try {
|
||||
claim = webhookInboxService.begin(eventId);
|
||||
} catch (Exception e) {
|
||||
log.error("Feishu webhook inbox unavailable; category=storage");
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(responseMap(1, "webhook inbox unavailable"));
|
||||
}
|
||||
if (claim == FeishuWebhookInboxService.ClaimOutcome.ALREADY_PROCESSED)
|
||||
return ResponseEntity.ok(responseMap(0, "success"));
|
||||
if (claim == FeishuWebhookInboxService.ClaimOutcome.BUSY) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set(HttpHeaders.RETRY_AFTER, "5");
|
||||
return new ResponseEntity<>(responseMap(1, "webhook processing busy"), headers,
|
||||
HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
try {
|
||||
feishuApprovalService.handleApprovalEvent(body);
|
||||
webhookInboxService.processed(eventId);
|
||||
return ResponseEntity.ok(responseMap(0, "success"));
|
||||
} catch (Exception e) {
|
||||
try { webhookInboxService.failed(eventId); } catch (Exception ignored) { }
|
||||
log.error("Feishu webhook processing failed; category=handler");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(responseMap(1, "webhook processing failed"));
|
||||
}
|
||||
}
|
||||
SysWebhookEvent event = null;
|
||||
try {
|
||||
webhookEventRepository.insertIfAbsent(eventId);
|
||||
@@ -216,12 +262,14 @@ public class FeishuAuthController {
|
||||
event.setStatus(SysWebhookEvent.PROCESSING);
|
||||
feishuApprovalService.handleApprovalEvent(body);
|
||||
event.setStatus(SysWebhookEvent.PROCESSED);
|
||||
webhookEventRepository.save(event);
|
||||
return ResponseEntity.ok(responseMap(0, "success"));
|
||||
} catch (Exception e) {
|
||||
if (event != null) {
|
||||
event.setStatus(SysWebhookEvent.FAILED);
|
||||
webhookEventRepository.save(event);
|
||||
}
|
||||
log.error("处理飞书Webhook失败: eventId={}", eventId, e);
|
||||
log.error("Feishu webhook processing failed; category=handler");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(responseMap(1, "webhook processing failed"));
|
||||
}
|
||||
@@ -238,14 +286,14 @@ public class FeishuAuthController {
|
||||
* 获取审批定义(审批节点信息)
|
||||
*/
|
||||
@GetMapping("/approval/definition")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')")
|
||||
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()));
|
||||
log.error("Feishu approval definition request failed; category=internal");
|
||||
return ResponseEntity.ok(ApiResponse.error(500, "获取审批定义失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,14 +301,14 @@ public class FeishuAuthController {
|
||||
* 获取审批节点列表
|
||||
*/
|
||||
@GetMapping("/approval/nodes")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')")
|
||||
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()));
|
||||
log.error("Feishu approval node request failed; category=internal");
|
||||
return ResponseEntity.ok(ApiResponse.error(500, "获取审批节点失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,15 +316,18 @@ public class FeishuAuthController {
|
||||
* 获取审批实例进度
|
||||
*/
|
||||
@GetMapping("/approval/instance/{instanceCode}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications') || @permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<Object>> getApprovalInstanceDetail(
|
||||
@PathVariable String instanceCode) {
|
||||
IntFeishuApproval mapping = feishuApprovalRepository.findByFeishuInstanceCode(instanceCode)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("本地审批实例映射不存在"));
|
||||
reimApplicationService.getApplicationDetail(mapping.getApplicationId(), AuditUtil.getCurrentUserId());
|
||||
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()));
|
||||
log.error("Feishu approval instance request failed; category=internal");
|
||||
return ResponseEntity.ok(ApiResponse.error(500, "获取审批实例详情失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,15 +335,16 @@ public class FeishuAuthController {
|
||||
* 根据报销单ID获取审批进度
|
||||
*/
|
||||
@GetMapping("/approval/application/{applicationId}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications') || @permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<Object>> getApprovalTimelineByApplication(
|
||||
@PathVariable Long applicationId) {
|
||||
reimApplicationService.getApplicationDetail(applicationId, AuditUtil.getCurrentUserId());
|
||||
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()));
|
||||
log.error("Feishu approval timeline request failed; category=internal");
|
||||
return ResponseEntity.ok(ApiResponse.error(500, "获取审批进度失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ public class FeishuCallbackController {
|
||||
private final JwtConfig jwtConfig;
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final SysDepartmentRepository sysDepartmentRepository;
|
||||
private final RoleService roleService;
|
||||
|
||||
/**
|
||||
* 飞书登录接口 - 返回JSON而非重定向
|
||||
@@ -51,15 +52,15 @@ public class FeishuCallbackController {
|
||||
// 1. 交换access_token
|
||||
FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code);
|
||||
String accessToken = tokenResponse.getData().getAccessToken();
|
||||
log.info("飞书access_token获取成功");
|
||||
log.info("Feishu OAuth token exchange succeeded");
|
||||
|
||||
// 2. 获取用户信息
|
||||
FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken);
|
||||
log.info("飞书用户信息获取成功: name={}, openId={}", feishuUserInfo.getName(), feishuUserInfo.getOpenId());
|
||||
log.info("Feishu OAuth user-info request succeeded");
|
||||
|
||||
// 3. 查找已绑定的本地用户
|
||||
SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo);
|
||||
log.info("用户绑定成功: userId={}, realName={}", user.getId(), user.getRealName());
|
||||
log.info("Feishu OAuth local account finalization succeeded");
|
||||
if (!isActive(user)) {
|
||||
return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用"));
|
||||
}
|
||||
@@ -86,11 +87,11 @@ public class FeishuCallbackController {
|
||||
return ResponseEntity.ok(ApiResponse.success(loginResponse));
|
||||
|
||||
} catch (BusinessException e) {
|
||||
log.warn("飞书登录失败: {}", e.getMessage());
|
||||
log.warn("Feishu OAuth login rejected; category=business status={}", e.getStatusCode());
|
||||
return ResponseEntity.status(e.getStatusCode())
|
||||
.body(ApiResponse.error(e.getStatusCode(), e.getMessage()));
|
||||
} catch (Exception e) {
|
||||
log.error("飞书登录失败", e);
|
||||
log.error("Feishu OAuth login failed; category=internal");
|
||||
return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
@@ -136,11 +137,11 @@ public class FeishuCallbackController {
|
||||
return ResponseEntity.ok(ApiResponse.success(loginResponse));
|
||||
|
||||
} catch (BusinessException e) {
|
||||
log.warn("飞书登录失败: {}", e.getMessage());
|
||||
log.warn("Feishu OAuth login rejected; category=business status={}", e.getStatusCode());
|
||||
return ResponseEntity.status(e.getStatusCode())
|
||||
.body(ApiResponse.error(e.getStatusCode(), e.getMessage()));
|
||||
} catch (Exception e) {
|
||||
log.error("飞书登录失败", e);
|
||||
log.error("Feishu OAuth login failed; category=internal");
|
||||
return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
@@ -166,6 +167,9 @@ public class FeishuCallbackController {
|
||||
.status(user.getStatus())
|
||||
.feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定")
|
||||
.lastLoginAt(user.getLastLoginAt() != null ? user.getLastLoginAt().toString().replace("T", " ") : null)
|
||||
.roleCodes(roleService.userRoleCodes(user.getId()))
|
||||
.groupNames(roleService.userGroupNames(user.getId()))
|
||||
.isSuperAdmin(roleService.isSuperAdmin(user.getId()))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,18 +14,17 @@ import java.util.Map;
|
||||
public class FeishuDirectoryController {
|
||||
private final FeishuDirectoryService directory;
|
||||
@PostMapping("/sync")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.feishu.directory.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));
|
||||
FeishuDirectoryService.Run run = directory.enqueue("MANUAL");
|
||||
return ResponseEntity.accepted().body(ApiResponse.success(run));
|
||||
}
|
||||
@GetMapping("/status")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync') or @permissionChecker.has(authentication, 'system:feishu:bind')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory')")
|
||||
public ApiResponse<Map<String,Object>> organization() {
|
||||
return ApiResponse.success(directory.organization());
|
||||
}
|
||||
|
||||
@@ -16,15 +16,15 @@ public class IntegrationConfigController {
|
||||
private final IntegrationConfigService service;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:integration:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> get() { return ResponseEntity.ok(ApiResponse.success(service.view())); }
|
||||
|
||||
@PutMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:integration:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.config.update')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.config.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,80 @@
|
||||
package com.finance.system.controller;
|
||||
|
||||
import com.finance.system.dto.ApiResponse;
|
||||
import com.finance.system.service.KingdeeSyncConfigService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/integrations/kingdee/sync-configs")
|
||||
@RequiredArgsConstructor
|
||||
public class KingdeeSyncConfigController {
|
||||
private final KingdeeSyncConfigService service;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list() {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.list()));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.create')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> create(@RequestBody KingdeeSyncConfigService.ConfigRequest request) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.create(request)));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> get(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.get(id)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.update')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> update(@PathVariable Long id,
|
||||
@RequestBody KingdeeSyncConfigService.ConfigRequest request) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.update(id, request)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.delete')")
|
||||
public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) {
|
||||
service.delete(id); return ResponseEntity.ok(ApiResponse.success());
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/preview")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.data.preview')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> preview(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.preview(id)));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/prepare-table")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.table.prepare')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> prepareTable(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.prepareTable(id)));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/sync")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.sync.execute')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> sync(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.sync(id)));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/runs")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> runs(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(service.runs(id)));
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public class LogController {
|
||||
* 获取操作日志列表
|
||||
*/
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.operation-log')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listLogs(
|
||||
@RequestParam(required = false) String category,
|
||||
@RequestParam(required = false) String operator,
|
||||
|
||||
@@ -109,6 +109,7 @@ public class MetadataController {
|
||||
* 获取费用类型列表
|
||||
*/
|
||||
@GetMapping("/expense-types")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.expense-types') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExpenseTypes() {
|
||||
try {
|
||||
return ResponseEntity.ok(ApiResponse.success(EXPENSE_TYPES));
|
||||
@@ -122,7 +123,7 @@ public class MetadataController {
|
||||
* 获取收款人列表
|
||||
*/
|
||||
@GetMapping("/payees")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.payees') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getPayees(
|
||||
@RequestParam(required = false) String keyword) {
|
||||
try {
|
||||
|
||||
@@ -114,7 +114,7 @@ public class PaymentController {
|
||||
* 获取付款列表(资金出纳B视图,过滤 expenseType=员工报销类)
|
||||
*/
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'payment:register')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.payments')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> listPayments(
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) String expenseType) {
|
||||
@@ -149,7 +149,7 @@ public class PaymentController {
|
||||
* 登记付款
|
||||
*/
|
||||
@PostMapping("/register")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'payment:register')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.register')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> registerPayment(@RequestBody Map<String, Object> request) {
|
||||
try {
|
||||
UserPrincipal principal = AuditUtil.getCurrentUser();
|
||||
|
||||
@@ -21,7 +21,12 @@ public class ReimApplicationController {
|
||||
private final ReimApplicationService reimApplicationService;
|
||||
|
||||
@GetMapping("/workbench")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')"
|
||||
+ " || @permissionChecker.has(authentication, 'page.applications')"
|
||||
+ " || @permissionChecker.has(authentication, 'page.application-create')"
|
||||
+ " || @permissionChecker.has(authentication, 'page.application-edit')"
|
||||
+ " || @permissionChecker.has(authentication, 'page.finance-receipt')"
|
||||
+ " || @permissionChecker.has(authentication, 'page.payments')")
|
||||
public ResponseEntity<ApiResponse<WorkbenchDto>> getWorkbench() {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
WorkbenchDto workbench = reimApplicationService.getWorkbench(userId);
|
||||
@@ -29,7 +34,7 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@GetMapping("/my")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications')")
|
||||
public ResponseEntity<ApiResponse<PageResponse<ReimApplicationSummary>>> getMyApplications(
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@@ -42,7 +47,7 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own') || @permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications') || @permissionChecker.has(authentication, 'page.application-edit') || @permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> getDetail(@PathVariable Long id) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
ReimApplicationDetail detail = reimApplicationService.getApplicationDetail(id, userId);
|
||||
@@ -50,7 +55,7 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@GetMapping("/no/{applicationNo}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own') || @permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications') || @permissionChecker.has(authentication, 'page.application-edit') || @permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> getByApplicationNo(
|
||||
@PathVariable String applicationNo) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
@@ -59,7 +64,7 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.create')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> create(
|
||||
@Valid @RequestBody CreateApplicationRequest request) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
@@ -68,7 +73,7 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.edit')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> update(
|
||||
@PathVariable Long id,
|
||||
@RequestBody CreateApplicationRequest request) {
|
||||
@@ -78,15 +83,30 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/submit")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> submit(@PathVariable Long id) {
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.submit')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> submit(
|
||||
@PathVariable Long id, @Valid @RequestBody SubmitApplicationRequest request) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
ReimApplicationDetail detail = reimApplicationService.submitApplication(id, userId);
|
||||
ReimApplicationDetail detail = reimApplicationService.submitApplication(id, userId, request.getPreviewToken());
|
||||
return ResponseEntity.ok(ApiResponse.success(detail));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/route-preview")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||
public ResponseEntity<ApiResponse<RoutePreviewDto>> previewRoute(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(
|
||||
reimApplicationService.previewRoute(id, AuditUtil.getCurrentUserId())));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/route-timeline")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications') || @permissionChecker.has(authentication, 'page.application-edit') || @permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<java.util.List<RouteTimelineNodeDto>>> routeTimeline(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(ApiResponse.success(
|
||||
reimApplicationService.getRouteTimeline(id, AuditUtil.getCurrentUserId())));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/receive")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'receipt:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.receipt.confirm')")
|
||||
public ResponseEntity<ApiResponse<ReimApplicationDetail>> receive(@PathVariable Long id) {
|
||||
Long operatorId = AuditUtil.getCurrentUserId();
|
||||
ReimApplicationDetail detail = reimApplicationService.receiveApplication(id, operatorId);
|
||||
@@ -94,7 +114,7 @@ public class ReimApplicationController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.edit')")
|
||||
public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) {
|
||||
reimApplicationService.deleteApplication(id, AuditUtil.getCurrentUserId());
|
||||
return ResponseEntity.ok(ApiResponse.success());
|
||||
|
||||
@@ -7,7 +7,6 @@ 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.*;
|
||||
@@ -18,11 +17,12 @@ import java.util.*;
|
||||
@RequestMapping("/api/roles")
|
||||
public class RoleController {
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private RoleService roleService;
|
||||
private final RoleService roleService;
|
||||
|
||||
public RoleController(SysUserRepository sysUserRepository) { this.sysUserRepository = sysUserRepository; }
|
||||
@Autowired(required = false)
|
||||
public void setRoleService(RoleService roleService) { this.roleService = roleService; }
|
||||
public RoleController(SysUserRepository sysUserRepository, RoleService roleService) {
|
||||
this.sysUserRepository = sysUserRepository;
|
||||
this.roleService = roleService;
|
||||
}
|
||||
|
||||
private static final List<Map<String, Object>> ROLE_PROFILES = new ArrayList<>();
|
||||
static {
|
||||
@@ -52,42 +52,44 @@ public class RoleController {
|
||||
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"));
|
||||
Map<String, Object> resolved = roleService.currentPermissionsMap(user.getId());
|
||||
result.put("permissions", resolved.get("permissionCodes"));
|
||||
result.put("permissionCodes", resolved.get("permissionCodes"));
|
||||
result.put("fieldPermissions", resolved.get("fieldPermissions"));
|
||||
result.put("permissionAccess", resolved.get("permissionAccess"));
|
||||
return ResponseEntity.ok(ApiResponse.success(result));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.roles') || @permissionChecker.has(authentication, 'page.groups') || @permissionChecker.hasEdit(authentication, 'system.group.role.bind')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listRoles())); }
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.create')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.edit')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.delete')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.roles')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.roles')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.permission.configure')")
|
||||
public ResponseEntity<ApiResponse<Void>> setPermissions(@PathVariable Long id, @RequestBody Map<String, Object> body) {
|
||||
roleService.replaceRolePermissions(id, body, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success());
|
||||
}
|
||||
@@ -98,7 +100,6 @@ public class RoleController {
|
||||
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,59 @@
|
||||
package com.finance.system.controller;
|
||||
|
||||
import com.finance.system.dto.ApiResponse;
|
||||
import com.finance.system.dto.ScheduledTaskRunDto;
|
||||
import com.finance.system.service.ScheduledTaskService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/scheduled-tasks")
|
||||
public class ScheduledTaskController {
|
||||
private final ScheduledTaskService service;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')")
|
||||
public ApiResponse<List<Map<String, Object>>> list() {
|
||||
return ApiResponse.success(service.list());
|
||||
}
|
||||
|
||||
@GetMapping("/{code}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')")
|
||||
public ApiResponse<Map<String, Object>> detail(@PathVariable String code) {
|
||||
return ApiResponse.success(service.detail(code));
|
||||
}
|
||||
|
||||
@PutMapping("/{code}/schedule")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.scheduled-task.config.update')")
|
||||
public ApiResponse<Map<String, Object>> update(@PathVariable String code,
|
||||
@RequestBody ScheduledTaskService.ScheduleRequest request) {
|
||||
return ApiResponse.success(service.update(code, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{code}/execute")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.scheduled-task.execute')")
|
||||
public ResponseEntity<ApiResponse<ScheduledTaskRunDto>> execute(@PathVariable String code) {
|
||||
return ResponseEntity.accepted().body(ApiResponse.success(service.execute(code)));
|
||||
}
|
||||
|
||||
@GetMapping("/{code}/runs")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')")
|
||||
public ApiResponse<Map<String, Object>> runs(@PathVariable String code,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.success(service.runs(code, page, size));
|
||||
}
|
||||
}
|
||||
@@ -129,7 +129,7 @@ public class SourceDocumentController {
|
||||
* 获取业务单据列表
|
||||
*/
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.source-documents')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listSources(
|
||||
@RequestParam(required = false) String sourceSystem,
|
||||
@RequestParam(required = false) String sourceStatus) {
|
||||
@@ -156,7 +156,7 @@ public class SourceDocumentController {
|
||||
* 获取业务单据详情
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.source-documents')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> getSourceDetail(@PathVariable Long id) {
|
||||
try {
|
||||
Map<String, Object> source = MOCK_SOURCES.stream()
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.finance.system.controller;
|
||||
|
||||
import com.finance.system.dto.ApiResponse;
|
||||
import com.finance.system.dto.MemberCandidatesResponse;
|
||||
import com.finance.system.dto.DirectoryIdentityDto;
|
||||
import com.finance.system.entity.SysUserGroup;
|
||||
import com.finance.system.service.RoleService;
|
||||
import com.finance.system.util.AuditUtil;
|
||||
@@ -15,55 +17,89 @@ import java.util.*;
|
||||
@RequestMapping("/api/user-groups")
|
||||
@RequiredArgsConstructor
|
||||
public class UserGroupController {
|
||||
private static final int MAX_DIRECTORY_IDENTITIES = 200;
|
||||
private static final int MAX_MEMBER_IDS = 5_000;
|
||||
private final RoleService roleService;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.groups')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listGroups())); }
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.create')")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> create(@RequestBody Map<String, Object> body) {
|
||||
return ResponseEntity.status(201).body(ApiResponse.success(groupMap(roleService.saveGroup(null, body))));
|
||||
SysUserGroup saved = roleService.saveGroup(null, body);
|
||||
return ResponseEntity.status(201).body(ApiResponse.success(roleService.groupDetails(saved.getId())));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.edit')")
|
||||
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))));
|
||||
roleService.saveGroup(id, body);
|
||||
return ResponseEntity.ok(ApiResponse.success(roleService.groupDetails(id)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.delete')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.groups')")
|
||||
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')")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.role.bind')")
|
||||
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());
|
||||
roleService.replaceGroupRoles(id, requiredList(body, "roleIds"),
|
||||
requiredList(body, "expectedRoleIds"), AuditUtil.getCurrentUserId());
|
||||
return ResponseEntity.ok(ApiResponse.success());
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/members")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.groups')")
|
||||
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));
|
||||
return ResponseEntity.ok(ApiResponse.success(roleService.groupMembers(id)));
|
||||
}
|
||||
|
||||
@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());
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind')")
|
||||
public ResponseEntity<ApiResponse<Map<String,Object>>> setMembers(@PathVariable Long id,
|
||||
@RequestBody Map<String, Object> body) {
|
||||
List<Long> userIds = requiredLongList(body, "userIds");
|
||||
List<Long> expectedUserIds = requiredLongList(body, "expectedUserIds");
|
||||
List<DirectoryIdentityDto> identities = requiredDirectoryIdentities(body, "directoryIdentities");
|
||||
if (userIds.size() + identities.size() > MAX_MEMBER_IDS)
|
||||
throw new com.finance.system.exception.BadRequestException("提交的最终成员数量不能超过5000");
|
||||
List<Long> committed = roleService.replaceGroupMembers(id, userIds, identities,
|
||||
expectedUserIds, AuditUtil.getCurrentUserId());
|
||||
Map<String,Object> result = new LinkedHashMap<>();
|
||||
result.put("userIds", committed);
|
||||
return ResponseEntity.ok(ApiResponse.success(result));
|
||||
}
|
||||
|
||||
@GetMapping("/candidates")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> candidates() { return ResponseEntity.ok(ApiResponse.success(roleService.candidates())); }
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind') || @permissionChecker.has(authentication, 'page.groups') || (#groupId == null && @permissionChecker.has(authentication, 'page.users'))")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> candidates(
|
||||
@RequestParam(value = "groupId", required = false) Long groupId,
|
||||
@RequestParam(value = "q", required = false) String q,
|
||||
@RequestParam(value = "keyword", required = false) String keyword) {
|
||||
String query = q != null ? q : keyword;
|
||||
return ResponseEntity.ok(ApiResponse.success(roleService.candidates(groupId, query)));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/member-candidates")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind') || @permissionChecker.has(authentication, 'page.groups')")
|
||||
public ResponseEntity<ApiResponse<MemberCandidatesResponse>> memberCandidates(
|
||||
@PathVariable Long id, @RequestParam(value = "q", required = false) String query) {
|
||||
return ResponseEntity.ok(ApiResponse.success(roleService.memberCandidates(id, query)));
|
||||
}
|
||||
|
||||
/** Java-call compatibility for focused controller tests and internal callers. */
|
||||
ResponseEntity<ApiResponse<List<Map<String, Object>>>> candidates(Long groupId) {
|
||||
return ResponseEntity.ok(ApiResponse.success(roleService.candidates(groupId)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<?> requiredList(Map<String, Object> body, String key) {
|
||||
@@ -72,8 +108,64 @@ public class UserGroupController {
|
||||
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;
|
||||
private List<Long> requiredLongList(Map<String,Object> body, String key) {
|
||||
List<?> values = requiredList(body, key);
|
||||
if (values.size() > MAX_MEMBER_IDS)
|
||||
throw new com.finance.system.exception.BadRequestException(key + " 数量不能超过5000");
|
||||
List<Long> result = new ArrayList<>();
|
||||
Set<Long> unique = new HashSet<>();
|
||||
for (Object value : values) {
|
||||
if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long))
|
||||
throw new com.finance.system.exception.BadRequestException(key + " 必须仅包含正整数");
|
||||
long parsed = ((Number)value).longValue();
|
||||
if (parsed <= 0 || !unique.add(parsed))
|
||||
throw new com.finance.system.exception.BadRequestException(key + " 包含无效或重复成员");
|
||||
result.add(parsed);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<DirectoryIdentityDto> requiredDirectoryIdentities(Map<String,Object> body, String key) {
|
||||
List<?> values = requiredList(body, key);
|
||||
if (values.size() > MAX_DIRECTORY_IDENTITIES)
|
||||
throw new com.finance.system.exception.BadRequestException(key + " 数量不能超过200");
|
||||
List<DirectoryIdentityDto> result = new ArrayList<>();
|
||||
Set<DirectoryIdentityDto> unique = new HashSet<>();
|
||||
for (Object value : values) {
|
||||
if (!(value instanceof Map))
|
||||
throw new com.finance.system.exception.BadRequestException(key + " 必须仅包含目录身份对象");
|
||||
Map<?,?> identity = (Map<?,?>) value;
|
||||
boolean revisionKey=identity.containsKey("revision");
|
||||
boolean legacyRevisionKey=identity.containsKey("generationId");
|
||||
if (revisionKey==legacyRevisionKey || !identity.containsKey("openId")
|
||||
|| identity.size() != (identity.containsKey("userId") ? 3 : 2))
|
||||
throw new com.finance.system.exception.BadRequestException("目录身份格式不正确");
|
||||
String generationId = identityText(identity.get(revisionKey?"revision":"generationId"), 36);
|
||||
String openId = identityText(identity.get("openId"), 100);
|
||||
String userId = identity.containsKey("userId") ? optionalIdentityText(identity.get("userId"),100) : null;
|
||||
DirectoryIdentityDto parsed = new DirectoryIdentityDto(generationId, openId, userId);
|
||||
if (!unique.add(parsed))
|
||||
throw new com.finance.system.exception.BadRequestException("目录身份不能重复");
|
||||
result.add(parsed);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String identityText(Object value, int maxLength) {
|
||||
if (!(value instanceof String))
|
||||
throw new com.finance.system.exception.BadRequestException("目录身份字段类型不正确");
|
||||
String text = ((String)value).trim();
|
||||
if (text.isEmpty() || text.length() > maxLength)
|
||||
throw new com.finance.system.exception.BadRequestException("目录身份字段长度不正确");
|
||||
return text;
|
||||
}
|
||||
private String optionalIdentityText(Object value,int maxLength){
|
||||
if(value==null)return null;
|
||||
if(!(value instanceof String))throw new com.finance.system.exception.BadRequestException("目录身份字段类型不正确");
|
||||
String text=((String)value).trim();
|
||||
if(text.isEmpty())return null;
|
||||
if(text.length()>maxLength)throw new com.finance.system.exception.BadRequestException("目录身份字段长度不正确");
|
||||
return text;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/** Immutable handle for one row in a published Feishu directory generation. */
|
||||
public final class DirectoryIdentityDto {
|
||||
private final String revision;
|
||||
private final String openId;
|
||||
private final String userId;
|
||||
|
||||
public DirectoryIdentityDto(String revision, String openId, String userId) {
|
||||
this.revision = revision;
|
||||
this.openId = openId;
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getRevision() { return revision; }
|
||||
/** Rolling compatibility for older service callers. */
|
||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
||||
public String getGenerationId() { return revision; }
|
||||
public String getOpenId() { return openId; }
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)
|
||||
public String getUserId() { return userId; }
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof DirectoryIdentityDto)) return false;
|
||||
DirectoryIdentityDto that = (DirectoryIdentityDto) other;
|
||||
return Objects.equals(revision, that.revision) && Objects.equals(openId, that.openId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() { return Objects.hash(revision, openId); }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import lombok.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
public class FeishuDefinitionSyncResult {
|
||||
private String fingerprint;
|
||||
private LocalDateTime fetchedAt;
|
||||
private int nodeCount;
|
||||
private boolean changed;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** Candidate shape. The directory identity is populated only for bind editors. */
|
||||
public final class MemberCandidateDto {
|
||||
private final Long id;
|
||||
private final String realName;
|
||||
private final String employeeNo;
|
||||
private final List<String> departmentNames;
|
||||
private final Long assignedGroupId;
|
||||
private final String assignedGroupName;
|
||||
private final boolean eligible;
|
||||
private final boolean selectable;
|
||||
private final DirectoryIdentityDto directoryIdentity;
|
||||
|
||||
public MemberCandidateDto(Long id, String realName, String employeeNo, List<String> departmentNames,
|
||||
Long assignedGroupId, String assignedGroupName,
|
||||
boolean eligible, boolean selectable) {
|
||||
this(id, realName, employeeNo, departmentNames, assignedGroupId, assignedGroupName,
|
||||
eligible, selectable, null);
|
||||
}
|
||||
|
||||
public MemberCandidateDto(Long id, String realName, String employeeNo, List<String> departmentNames,
|
||||
Long assignedGroupId, String assignedGroupName,
|
||||
boolean eligible, boolean selectable, DirectoryIdentityDto directoryIdentity) {
|
||||
this.id = id;
|
||||
this.realName = realName;
|
||||
this.employeeNo = employeeNo;
|
||||
this.departmentNames = Collections.unmodifiableList(new ArrayList<>(
|
||||
departmentNames == null ? Collections.<String>emptyList() : departmentNames));
|
||||
this.assignedGroupId = assignedGroupId;
|
||||
this.assignedGroupName = assignedGroupName;
|
||||
this.eligible = eligible;
|
||||
this.selectable = selectable;
|
||||
this.directoryIdentity = directoryIdentity;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public String getRealName() { return realName; }
|
||||
public String getEmployeeNo() { return employeeNo; }
|
||||
public List<String> getDepartmentNames() { return departmentNames; }
|
||||
public Long getAssignedGroupId() { return assignedGroupId; }
|
||||
public String getAssignedGroupName() { return assignedGroupName; }
|
||||
public boolean isEligible() { return eligible; }
|
||||
public boolean isSelectable() { return selectable; }
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)
|
||||
public DirectoryIdentityDto getDirectoryIdentity() { return directoryIdentity; }
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public final class MemberCandidatesResponse {
|
||||
private final String snapshotState;
|
||||
private final String availabilityState;
|
||||
private final boolean additionsAllowed;
|
||||
private final String currentRevision;
|
||||
private final String contextState;
|
||||
private final List<MemberCandidateDto> currentMembers;
|
||||
private final List<MemberCandidateDto> matches;
|
||||
private final int limit;
|
||||
private final boolean truncated;
|
||||
private final boolean blockedMatchesPresent;
|
||||
|
||||
public MemberCandidatesResponse(String snapshotState, List<MemberCandidateDto> currentMembers,
|
||||
List<MemberCandidateDto> matches, int limit, boolean truncated,
|
||||
boolean blockedMatchesPresent) {
|
||||
this(snapshotState, "FRESH".equals(snapshotState) ? "AVAILABLE"
|
||||
: "NEVER_SYNCED".equals(snapshotState) ? "NEVER_SYNCED" : "UNAVAILABLE",
|
||||
"FRESH".equals(snapshotState), null, "UNKNOWN", currentMembers, matches,
|
||||
limit, truncated, blockedMatchesPresent);
|
||||
}
|
||||
|
||||
public MemberCandidatesResponse(String snapshotState, String availabilityState,
|
||||
boolean additionsAllowed, String currentRevision, String contextState,
|
||||
List<MemberCandidateDto> currentMembers, List<MemberCandidateDto> matches,
|
||||
int limit, boolean truncated, boolean blockedMatchesPresent) {
|
||||
this.snapshotState = snapshotState;
|
||||
this.availabilityState = availabilityState;
|
||||
this.additionsAllowed = additionsAllowed;
|
||||
this.currentRevision = currentRevision;
|
||||
this.contextState = contextState;
|
||||
this.currentMembers = immutable(currentMembers);
|
||||
this.matches = immutable(matches);
|
||||
this.limit = limit;
|
||||
this.truncated = truncated;
|
||||
// Compatibility field retained for older clients. Explicit bindings are
|
||||
// not eligibility-filtered, so there are no policy-blocked matches.
|
||||
this.blockedMatchesPresent = false;
|
||||
}
|
||||
|
||||
private static List<MemberCandidateDto> immutable(List<MemberCandidateDto> value) {
|
||||
return Collections.unmodifiableList(new ArrayList<>(value == null
|
||||
? Collections.<MemberCandidateDto>emptyList() : value));
|
||||
}
|
||||
|
||||
public String getSnapshotState() { return snapshotState; }
|
||||
public String getAvailabilityState() { return availabilityState; }
|
||||
public boolean isAdditionsAllowed() { return additionsAllowed; }
|
||||
public String getCurrentRevision() { return currentRevision; }
|
||||
public String getContextState() { return contextState; }
|
||||
public List<MemberCandidateDto> getCurrentMembers() { return currentMembers; }
|
||||
public List<MemberCandidateDto> getMatches() { return matches; }
|
||||
public int getLimit() { return limit; }
|
||||
public boolean isTruncated() { return truncated; }
|
||||
public boolean isBlockedMatchesPresent() { return blockedMatchesPresent; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import lombok.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
public class RoutePreviewDto {
|
||||
private Long applicationId;
|
||||
private String source;
|
||||
private List<RouteNodeDto> nodes;
|
||||
private String routeFingerprint;
|
||||
private String snapshotFingerprint;
|
||||
private String previewToken;
|
||||
private LocalDateTime expiresAt;
|
||||
private LocalDateTime snapshotFetchedAt;
|
||||
private boolean staleSnapshot;
|
||||
private boolean exact;
|
||||
private String warning;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
public static class RouteNodeDto {
|
||||
private Integer order;
|
||||
private String nodeKey;
|
||||
private String nodeName;
|
||||
private String nodeType;
|
||||
private String approvalMode;
|
||||
private List<String> approverLabels;
|
||||
private boolean dynamic;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import lombok.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
public class RouteTimelineNodeDto {
|
||||
private Integer order;
|
||||
private String nodeName;
|
||||
private String nodeType;
|
||||
private String approvalMode;
|
||||
private boolean planned;
|
||||
private String status;
|
||||
private String approverLabel;
|
||||
private String comment;
|
||||
private LocalDateTime actionTime;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** Public scheduled-task run representation shared by execute and history APIs. */
|
||||
@Data
|
||||
public class ScheduledTaskRunDto {
|
||||
private String runId;
|
||||
private String trigger;
|
||||
private String state;
|
||||
private String queuedAt;
|
||||
private String startedAt;
|
||||
private String finishedAt;
|
||||
private int attempts;
|
||||
private boolean complete;
|
||||
private boolean applied;
|
||||
private Counts counts;
|
||||
private String errorCode;
|
||||
private String errorMessage;
|
||||
|
||||
@Data
|
||||
public static class Counts {
|
||||
private int departments;
|
||||
private int usersSeen;
|
||||
private int eligible;
|
||||
private int excluded;
|
||||
private int created;
|
||||
private int updated;
|
||||
private int ineligible;
|
||||
private int outOfScope;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
@Data
|
||||
public class SubmitApplicationRequest {
|
||||
@NotBlank(message = "previewToken不能为空")
|
||||
private String previewToken;
|
||||
}
|
||||
@@ -25,4 +25,6 @@ public class UserProfile {
|
||||
private String lastLoginAt;
|
||||
private List<String> roleCodes;
|
||||
private List<String> groupNames;
|
||||
/** True only for a currently active recovery or group-authorized super administrator. */
|
||||
private Boolean isSuperAdmin;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "feishu_approval_definition_approver")
|
||||
public class FeishuApprovalDefinitionApprover {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
|
||||
@Column(name = "node_id", nullable = false) private Long nodeId;
|
||||
@Column(name = "approver_order", nullable = false) private Integer approverOrder;
|
||||
@Column(name = "approver_type", length = 80) private String approverType;
|
||||
@Column(name = "approver_ref", length = 300) private String approverRef;
|
||||
@Column(name = "approver_label", nullable = false, length = 300) private String approverLabel;
|
||||
@Column(nullable = false) private Boolean dynamic;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "feishu_approval_definition_node")
|
||||
public class FeishuApprovalDefinitionNode {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
|
||||
@Column(name = "snapshot_id", nullable = false) private Long snapshotId;
|
||||
@Column(name = "node_order", nullable = false) private Integer nodeOrder;
|
||||
@Column(name = "node_key", nullable = false, length = 300) private String nodeKey;
|
||||
@Column(name = "node_name", nullable = false, length = 300) private String nodeName;
|
||||
@Column(name = "node_type", length = 80) private String nodeType;
|
||||
@Column(name = "approval_mode", length = 80) private String approvalMode;
|
||||
@Column(nullable = false) private Boolean dynamic;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "feishu_approval_definition_snapshot")
|
||||
public class FeishuApprovalDefinitionSnapshot {
|
||||
public static final long CURRENT_ID = 1L;
|
||||
@Id private Long id;
|
||||
@Column(name = "approval_code", nullable = false, length = 200) private String approvalCode;
|
||||
@Column(name = "approval_name", length = 300) private String approvalName;
|
||||
@Column(nullable = false, length = 64) private String fingerprint;
|
||||
@Column(name = "fetched_at", nullable = false) private LocalDateTime fetchedAt;
|
||||
@Column(name = "created_at", nullable = false) private LocalDateTime createdAt;
|
||||
@Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "feishu_definition_sync_fence")
|
||||
public class FeishuDefinitionSyncFence {
|
||||
public static final long SINGLETON_ID = 1L;
|
||||
@Id private Long id;
|
||||
@Column(nullable = false) private Long generation;
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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,27 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "int_feishu_instance_timeline_node")
|
||||
public class FeishuInstanceTimelineNode {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
|
||||
@Column(name = "feishu_approval_id", nullable = false) private Long feishuApprovalId;
|
||||
@Column(name = "instance_code", nullable = false, length = 200) private String instanceCode;
|
||||
@Column(name = "timeline_key", nullable = false, length = 400) private String timelineKey;
|
||||
@Column(name = "node_order") private Integer nodeOrder;
|
||||
@Column(name = "node_key", length = 300) private String nodeKey;
|
||||
@Column(name = "node_name", length = 300) private String nodeName;
|
||||
@Column(name = "node_type", length = 80) private String nodeType;
|
||||
@Column(name = "approval_mode", length = 80) private String approvalMode;
|
||||
@Column(nullable = false) private Boolean planned;
|
||||
@Column(name = "task_id", length = 300) private String taskId;
|
||||
@Column(length = 50) private String status;
|
||||
@Column(name = "approver_label", length = 300) private String approverLabel;
|
||||
@Column(length = 2000) private String comment;
|
||||
@Column(name = "action_time") private LocalDateTime actionTime;
|
||||
@Column(name = "created_at", nullable = false) private LocalDateTime createdAt;
|
||||
@Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -18,6 +18,20 @@ import java.time.LocalDateTime;
|
||||
@Table(name = "int_feishu_approval")
|
||||
public class IntFeishuApproval {
|
||||
|
||||
/** Compatibility constructor retained for existing service callers. */
|
||||
public IntFeishuApproval(Long id, Long applicationId, String feishuInstanceCode,
|
||||
String feishuApprovalCode, String status, String callbackData,
|
||||
LocalDateTime syncedAt, LocalDateTime createdAt) {
|
||||
this.id = id;
|
||||
this.applicationId = applicationId;
|
||||
this.feishuInstanceCode = feishuInstanceCode;
|
||||
this.feishuApprovalCode = feishuApprovalCode;
|
||||
this.status = status;
|
||||
this.callbackData = callbackData;
|
||||
this.syncedAt = syncedAt;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@@ -46,6 +60,48 @@ public class IntFeishuApproval {
|
||||
@Column(name = "synced_at")
|
||||
private LocalDateTime syncedAt;
|
||||
|
||||
@Column(name = "application_fingerprint", length = 64)
|
||||
private String applicationFingerprint;
|
||||
|
||||
@Column(name = "route_fingerprint", length = 64)
|
||||
private String routeFingerprint;
|
||||
|
||||
@Column(name = "snapshot_fingerprint", length = 64)
|
||||
private String snapshotFingerprint;
|
||||
|
||||
@Column(name = "request_uuid", length = 64)
|
||||
private String requestUuid;
|
||||
|
||||
@Column(name = "preview_token_hash", length = 64)
|
||||
private String previewTokenHash;
|
||||
|
||||
@Column(name = "create_started_at")
|
||||
private LocalDateTime createStartedAt;
|
||||
|
||||
@Column(name = "event_updated_at")
|
||||
private LocalDateTime eventUpdatedAt;
|
||||
|
||||
@Column(name = "deferred_status", length = 30)
|
||||
private String deferredStatus;
|
||||
|
||||
@Column(name = "deferred_event_at")
|
||||
private LocalDateTime deferredEventAt;
|
||||
|
||||
@Column(name = "create_payload", columnDefinition = "TEXT")
|
||||
private String createPayload;
|
||||
|
||||
@Column(name = "create_payload_hash", length = 64)
|
||||
private String createPayloadHash;
|
||||
|
||||
@Column(name = "submission_content_hash", length = 64)
|
||||
private String submissionContentHash;
|
||||
|
||||
@Column(name = "route_source", length = 20)
|
||||
private String routeSource;
|
||||
|
||||
@Column(name = "route_plan", columnDefinition = "TEXT")
|
||||
private String routePlan;
|
||||
|
||||
/** 创建时间 */
|
||||
@Column(name = "created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "int_feishu_approval_attempt")
|
||||
public class IntFeishuApprovalAttempt {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
|
||||
@Column(name = "feishu_approval_id", nullable = false) private Long feishuApprovalId;
|
||||
@Column(name = "application_id", nullable = false) private Long applicationId;
|
||||
@Column(name = "instance_code", nullable = false, unique = true, length = 200) private String instanceCode;
|
||||
@Column(name = "request_uuid", length = 64) private String requestUuid;
|
||||
@Column(length = 30) private String status;
|
||||
@Column(name = "event_updated_at") private LocalDateTime eventUpdatedAt;
|
||||
@Column(name = "created_at", nullable = false) private LocalDateTime createdAt;
|
||||
@Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.*;
|
||||
import javax.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "reim_route_preview_token")
|
||||
public class ReimRoutePreviewToken {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
|
||||
@Column(name = "token_hash", nullable = false, unique = true, length = 64) private String tokenHash;
|
||||
@Column(name = "application_id", nullable = false) private Long applicationId;
|
||||
@Column(name = "user_id", nullable = false) private Long userId;
|
||||
@Column(name = "route_source", nullable = false, length = 20) private String routeSource;
|
||||
@Column(name = "approval_code", length = 200) private String approvalCode;
|
||||
@Column(name = "application_fingerprint", nullable = false, length = 64) private String applicationFingerprint;
|
||||
@Column(name = "route_fingerprint", nullable = false, length = 64) private String routeFingerprint;
|
||||
@Column(name = "snapshot_fingerprint", length = 64) private String snapshotFingerprint;
|
||||
@Column(name = "route_plan", nullable = false, columnDefinition = "TEXT") private String routePlan;
|
||||
@Column(name = "first_approver_id") private Long firstApproverId;
|
||||
@Column(name = "first_node_id") private Long firstNodeId;
|
||||
@Column(name = "first_approver_role", length = 50) private String firstApproverRole;
|
||||
@Column(name = "first_node_name", length = 300) private String firstNodeName;
|
||||
@Column(name = "created_at", nullable = false) private LocalDateTime createdAt;
|
||||
@Column(name = "expires_at", nullable = false) private LocalDateTime expiresAt;
|
||||
@Column(name = "consumed_at") private LocalDateTime consumedAt;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.PrePersist;
|
||||
import javax.persistence.PreUpdate;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "sys_kingdee_sync_config")
|
||||
public class SysKingdeeSyncConfig {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "config_name", nullable = false, length = 200)
|
||||
private String configName;
|
||||
@Column(name = "form_id", nullable = false, length = 120)
|
||||
private String formId;
|
||||
@Column(name = "target_table_name", nullable = false, unique = true, length = 63)
|
||||
private String targetTableName;
|
||||
@Column(name = "target_table_comment", length = 500)
|
||||
private String targetTableComment;
|
||||
@Column(nullable = false)
|
||||
private Boolean enabled;
|
||||
@Column(name = "max_rows_per_run", nullable = false)
|
||||
private Integer maxRowsPerRun;
|
||||
@Column(name = "created_at")
|
||||
private LocalDateTime createdAt;
|
||||
@Column(name = "updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (enabled == null) enabled = Boolean.TRUE;
|
||||
if (maxRowsPerRun == null) maxRowsPerRun = 10000;
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = createdAt;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() { updatedAt = LocalDateTime.now(); }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.PrePersist;
|
||||
import javax.persistence.PreUpdate;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "sys_kingdee_sync_field")
|
||||
public class SysKingdeeSyncField {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(name = "config_id", nullable = false) private Long configId;
|
||||
@Column(name = "source_field_key", nullable = false, length = 200) private String sourceFieldKey;
|
||||
@Column(name = "target_column_name", nullable = false, length = 63) private String targetColumnName;
|
||||
@Column(name = "field_comment", length = 500) private String fieldComment;
|
||||
@Column(name = "data_type", nullable = false, length = 20) private String dataType;
|
||||
@Column(name = "field_length") private Integer fieldLength;
|
||||
@Column(name = "sort_order", nullable = false) private Integer sortOrder;
|
||||
@Column(name = "created_at") private LocalDateTime createdAt;
|
||||
@Column(name = "updated_at") private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = createdAt; }
|
||||
@PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.PrePersist;
|
||||
import javax.persistence.PreUpdate;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "sys_kingdee_sync_filter")
|
||||
public class SysKingdeeSyncFilter {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(name = "config_id", nullable = false) private Long configId;
|
||||
@Column(name = "source_field_key", nullable = false, length = 200) private String sourceFieldKey;
|
||||
@Column(nullable = false, length = 20) private String operator;
|
||||
@Column(name = "filter_value", length = 1000) private String filterValue;
|
||||
@Column(name = "sort_order", nullable = false) private Integer sortOrder;
|
||||
@Column(name = "created_at") private LocalDateTime createdAt;
|
||||
@Column(name = "updated_at") private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = createdAt; }
|
||||
@PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.PrePersist;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "sys_kingdee_sync_run")
|
||||
public class SysKingdeeSyncRun {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(name = "config_id", nullable = false) private Long configId;
|
||||
@Column(nullable = false, length = 20) private String status;
|
||||
@Column(name = "filter_string", length = 4000) private String filterString;
|
||||
@Column(name = "fetched_count", nullable = false) private Integer fetchedCount;
|
||||
@Column(name = "inserted_count", nullable = false) private Integer insertedCount;
|
||||
@Column(name = "updated_count", nullable = false) private Integer updatedCount;
|
||||
@Column(name = "failed_count", nullable = false) private Integer failedCount;
|
||||
@Column(name = "error_message", length = 2000) private String errorMessage;
|
||||
@Column(name = "started_at") private LocalDateTime startedAt;
|
||||
@Column(name = "finished_at") private LocalDateTime finishedAt;
|
||||
@JsonIgnore
|
||||
@Column(name = "execution_token", length = 64) private String executionToken;
|
||||
@Column(name = "heartbeat_at") private LocalDateTime heartbeatAt;
|
||||
@Column(name = "lease_until") private LocalDateTime leaseUntil;
|
||||
|
||||
@PrePersist protected void onCreate() {
|
||||
if (fetchedCount == null) fetchedCount = 0;
|
||||
if (insertedCount == null) insertedCount = 0;
|
||||
if (updatedCount == null) updatedCount = 0;
|
||||
if (failedCount == null) failedCount = 0;
|
||||
if (startedAt == null) startedAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,15 @@ public class SysUserGroup {
|
||||
private String groupName;
|
||||
@Column(length = 500) private String description;
|
||||
@Column(length = 20) private String status;
|
||||
@Builder.Default
|
||||
@org.hibernate.annotations.ColumnDefault("false")
|
||||
@Column(name = "built_in", nullable = false)
|
||||
private Boolean builtIn = 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(); }
|
||||
@PrePersist protected void onCreate() {
|
||||
if (builtIn == null) builtIn = false;
|
||||
createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now();
|
||||
}
|
||||
@PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); }
|
||||
}
|
||||
@@ -10,7 +10,9 @@ import javax.persistence.*;
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "sys_user_group_member", uniqueConstraints = @UniqueConstraint(columnNames = {"group_id", "user_id"}))
|
||||
@Table(name = "sys_user_group_member", uniqueConstraints = {
|
||||
@UniqueConstraint(name = "ux_user_group_member_user", columnNames = {"user_id"})
|
||||
})
|
||||
public class SysUserGroupMember {
|
||||
@EmbeddedId private SysUserGroupMemberId id;
|
||||
public SysUserGroupMember(Long groupId, Long userId) { this.id = new SysUserGroupMemberId(groupId, userId); }
|
||||
|
||||
@@ -18,6 +18,9 @@ import java.time.LocalDateTime;
|
||||
@AllArgsConstructor
|
||||
@Table(name = "sys_webhook_event")
|
||||
public class SysWebhookEvent {
|
||||
public SysWebhookEvent(String eventId, String status, LocalDateTime createdAt) {
|
||||
this.eventId = eventId; this.status = status; this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public static final String PROCESSING = "PROCESSING";
|
||||
public static final String PROCESSED = "PROCESSED";
|
||||
@@ -33,6 +36,9 @@ public class SysWebhookEvent {
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "processing_started_at")
|
||||
private LocalDateTime processingStartedAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.finance.system.exception;
|
||||
|
||||
/** The create request may have reached Feishu; retry only with the same UUID and exact payload. */
|
||||
public class FeishuCreateOutcomeUnknownException extends BusinessException {
|
||||
public FeishuCreateOutcomeUnknownException(String message, Throwable cause) {
|
||||
super(message, 503);
|
||||
initCause(cause);
|
||||
}
|
||||
public FeishuCreateOutcomeUnknownException(String message) { super(message, 503); }
|
||||
}
|
||||
@@ -9,6 +9,8 @@ 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 org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -66,6 +68,19 @@ public class GlobalExceptionHandler {
|
||||
.body(ApiResponse.error(400, "参数校验失败", errors));
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleUnreadableBody(HttpMessageNotReadableException e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error(400, "请求体不能为空或格式不正确"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleDataIntegrityViolation(DataIntegrityViolationException e) {
|
||||
log.warn("Database constraint conflict");
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(ApiResponse.error(409, "数据冲突,请刷新后重试"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleGeneral(Exception e) {
|
||||
log.error("Unexpected error", e);
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.FeishuApprovalDefinitionApprover;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface FeishuApprovalDefinitionApproverRepository extends JpaRepository<FeishuApprovalDefinitionApprover, Long> {
|
||||
List<FeishuApprovalDefinitionApprover> findByNodeIdOrderByApproverOrderAsc(Long nodeId);
|
||||
void deleteByNodeIdIn(List<Long> nodeIds);
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.FeishuApprovalDefinitionNode;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface FeishuApprovalDefinitionNodeRepository extends JpaRepository<FeishuApprovalDefinitionNode, Long> {
|
||||
List<FeishuApprovalDefinitionNode> findBySnapshotIdOrderByNodeOrderAsc(Long snapshotId);
|
||||
void deleteBySnapshotId(Long snapshotId);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.FeishuApprovalDefinitionSnapshot;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import javax.persistence.LockModeType;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface FeishuApprovalDefinitionSnapshotRepository extends JpaRepository<FeishuApprovalDefinitionSnapshot, Long> {
|
||||
@Lock(LockModeType.PESSIMISTIC_READ)
|
||||
@Query("select s from FeishuApprovalDefinitionSnapshot s where s.id = :id")
|
||||
Optional<FeishuApprovalDefinitionSnapshot> findByIdForRouteValidation(@Param("id") Long id);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.FeishuDefinitionSyncFence;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import javax.persistence.LockModeType;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface FeishuDefinitionSyncFenceRepository extends JpaRepository<FeishuDefinitionSyncFence, Long> {
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select f from FeishuDefinitionSyncFence f where f.id=:id")
|
||||
Optional<FeishuDefinitionSyncFence> findByIdForUpdate(@Param("id") Long id);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.FeishuInstanceTimelineNode;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.*;
|
||||
|
||||
public interface FeishuInstanceTimelineNodeRepository extends JpaRepository<FeishuInstanceTimelineNode, Long> {
|
||||
Optional<FeishuInstanceTimelineNode> findByFeishuApprovalIdAndInstanceCodeAndTimelineKey(Long approvalId, String instanceCode, String timelineKey);
|
||||
Optional<FeishuInstanceTimelineNode> findFirstByFeishuApprovalIdAndInstanceCodeAndNodeKeyOrderByIdAsc(Long approvalId, String instanceCode, String nodeKey);
|
||||
Optional<FeishuInstanceTimelineNode> findByFeishuApprovalIdAndInstanceCodeAndTaskId(Long approvalId, String instanceCode, String taskId);
|
||||
List<FeishuInstanceTimelineNode> findByFeishuApprovalIdAndInstanceCodeOrderByNodeOrderAscIdAsc(Long approvalId, String instanceCode);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.IntFeishuApprovalAttempt;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import javax.persistence.LockModeType;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface IntFeishuApprovalAttemptRepository extends JpaRepository<IntFeishuApprovalAttempt, Long> {
|
||||
Optional<IntFeishuApprovalAttempt> findByInstanceCode(String instanceCode);
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select a from IntFeishuApprovalAttempt a where a.instanceCode=:instanceCode")
|
||||
Optional<IntFeishuApprovalAttempt> findByInstanceCodeForUpdate(@Param("instanceCode") String instanceCode);
|
||||
}
|
||||
@@ -19,4 +19,8 @@ public interface IntFeishuApprovalRepository extends JpaRepository<IntFeishuAppr
|
||||
Optional<IntFeishuApproval> findByFeishuInstanceCodeForUpdate(@Param("instanceCode") String instanceCode);
|
||||
|
||||
Optional<IntFeishuApproval> findByApplicationId(Long applicationId);
|
||||
|
||||
@Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select a from IntFeishuApproval a where a.applicationId = :applicationId")
|
||||
Optional<IntFeishuApproval> findByApplicationIdForUpdate(@Param("applicationId") Long applicationId);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.ReimRoutePreviewToken;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import javax.persistence.LockModeType;
|
||||
import java.util.Optional;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
public interface ReimRoutePreviewTokenRepository extends JpaRepository<ReimRoutePreviewToken, Long> {
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select t from ReimRoutePreviewToken t where t.tokenHash = :hash")
|
||||
Optional<ReimRoutePreviewToken> findByTokenHashForUpdate(@Param("hash") String hash);
|
||||
|
||||
@Modifying(flushAutomatically = true, clearAutomatically = true)
|
||||
@Query("delete from ReimRoutePreviewToken t where t.applicationId=:applicationId and t.userId=:userId")
|
||||
void deleteByApplicationIdAndUserId(@Param("applicationId") Long applicationId, @Param("userId") Long userId);
|
||||
@Modifying(flushAutomatically = true, clearAutomatically = true)
|
||||
@Query("delete from ReimRoutePreviewToken t where t.applicationId=:applicationId")
|
||||
void deleteByApplicationId(@Param("applicationId") Long applicationId);
|
||||
@Modifying(flushAutomatically = true, clearAutomatically = true)
|
||||
@Query("delete from ReimRoutePreviewToken t where t.expiresAt<:now or t.consumedAt is not null")
|
||||
int deleteByExpiresAtBeforeOrConsumedAtIsNotNull(@Param("now") LocalDateTime now);
|
||||
@Query("select t.id from ReimRoutePreviewToken t where t.expiresAt<:now or t.consumedAt is not null order by t.id")
|
||||
List<Long> findCleanupIds(@Param("now") LocalDateTime now, Pageable pageable);
|
||||
@Modifying
|
||||
@Query("delete from ReimRoutePreviewToken t where t.id in :ids")
|
||||
int deleteCleanupIds(@Param("ids") List<Long> ids);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.SysKingdeeSyncConfig;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import javax.persistence.LockModeType;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface SysKingdeeSyncConfigRepository extends JpaRepository<SysKingdeeSyncConfig, Long> {
|
||||
boolean existsByTargetTableName(String targetTableName);
|
||||
boolean existsByTargetTableNameAndIdNot(String targetTableName, Long id);
|
||||
Optional<SysKingdeeSyncConfig> findByTargetTableName(String targetTableName);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select c from SysKingdeeSyncConfig c where c.id = :id")
|
||||
Optional<SysKingdeeSyncConfig> findByIdForUpdate(@Param("id") Long id);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.SysKingdeeSyncField;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface SysKingdeeSyncFieldRepository extends JpaRepository<SysKingdeeSyncField, Long> {
|
||||
List<SysKingdeeSyncField> findByConfigIdOrderBySortOrderAscIdAsc(Long configId);
|
||||
void deleteByConfigId(Long configId);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.SysKingdeeSyncFilter;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface SysKingdeeSyncFilterRepository extends JpaRepository<SysKingdeeSyncFilter, Long> {
|
||||
List<SysKingdeeSyncFilter> findByConfigIdOrderBySortOrderAscIdAsc(Long configId);
|
||||
void deleteByConfigId(Long configId);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.SysKingdeeSyncRun;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import javax.persistence.LockModeType;
|
||||
|
||||
@Repository
|
||||
public interface SysKingdeeSyncRunRepository extends JpaRepository<SysKingdeeSyncRun, Long> {
|
||||
List<SysKingdeeSyncRun> findTop100ByConfigIdOrderByStartedAtDescIdDesc(Long configId);
|
||||
Optional<SysKingdeeSyncRun> findFirstByConfigIdAndStatusOrderByStartedAtDesc(Long configId, String status);
|
||||
void deleteByConfigId(Long configId);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select r from SysKingdeeSyncRun r where r.id = :id")
|
||||
Optional<SysKingdeeSyncRun> findByIdForUpdate(@Param("id") Long id);
|
||||
|
||||
@Query(value = "SELECT CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
LocalDateTime currentDatabaseTime();
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET status = :status, error_message = :error, "
|
||||
+ "finished_at = CURRENT_TIMESTAMP(6) WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND execution_token = :token AND lease_until > CURRENT_TIMESTAMP(6) "
|
||||
+ "AND started_at + INTERVAL 30 MINUTE > CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
int finishSuccessIfValid(@Param("id") Long id, @Param("status") String status,
|
||||
@Param("token") String token, @Param("error") String error);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET status = 'FAILED', error_message = :error, "
|
||||
+ "finished_at = CURRENT_TIMESTAMP(6) WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND execution_token = :token", nativeQuery = true)
|
||||
int failIfRunning(@Param("id") Long id, @Param("token") String token, @Param("error") String error);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET heartbeat_at = CURRENT_TIMESTAMP(6), "
|
||||
+ "lease_until = LEAST(CURRENT_TIMESTAMP(6) + INTERVAL 90 SECOND, "
|
||||
+ "started_at + INTERVAL 30 MINUTE) WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND execution_token = :token AND lease_until > CURRENT_TIMESTAMP(6) "
|
||||
+ "AND started_at + INTERVAL 30 MINUTE > CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
int renewLease(@Param("id") Long id, @Param("token") String token);
|
||||
|
||||
@Query(value = "SELECT COUNT(*) FROM sys_kingdee_sync_run WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND execution_token = :token AND lease_until > CURRENT_TIMESTAMP(6) "
|
||||
+ "AND started_at + INTERVAL 30 MINUTE > CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
int countValidFence(@Param("id") Long id, @Param("token") String token);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET fetched_count = fetched_count + 1, "
|
||||
+ "inserted_count = inserted_count + :inserted, updated_count = updated_count + :updated "
|
||||
+ "WHERE id = :id AND status = 'RUNNING' AND execution_token = :token "
|
||||
+ "AND lease_until > CURRENT_TIMESTAMP(6) "
|
||||
+ "AND started_at + INTERVAL 30 MINUTE > CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
int incrementSuccessIfValid(@Param("id") Long id, @Param("token") String token,
|
||||
@Param("inserted") int inserted, @Param("updated") int updated);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET fetched_count = fetched_count + 1, "
|
||||
+ "failed_count = failed_count + 1 WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND execution_token = :token AND lease_until > CURRENT_TIMESTAMP(6) "
|
||||
+ "AND started_at + INTERVAL 30 MINUTE > CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
int incrementFailureIfValid(@Param("id") Long id, @Param("token") String token);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET status = 'FAILED', error_message = :error, "
|
||||
+ "finished_at = CURRENT_TIMESTAMP(6) WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND (lease_until IS NULL OR lease_until <= CURRENT_TIMESTAMP(6) "
|
||||
+ "OR started_at + INTERVAL 30 MINUTE <= CURRENT_TIMESTAMP(6))", nativeQuery = true)
|
||||
int failExpiredRun(@Param("id") Long id, @Param("error") String error);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET status = 'FAILED', error_message = :error, "
|
||||
+ "finished_at = CURRENT_TIMESTAMP(6) WHERE status = 'RUNNING' AND "
|
||||
+ "(lease_until IS NULL OR lease_until <= CURRENT_TIMESTAMP(6) "
|
||||
+ "OR started_at + INTERVAL 30 MINUTE <= CURRENT_TIMESTAMP(6))", nativeQuery = true)
|
||||
int failExpiredLeases(@Param("error") String error);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "UPDATE sys_kingdee_sync_run SET status = 'FAILED', error_message = :error, "
|
||||
+ "finished_at = CURRENT_TIMESTAMP(6) WHERE id = :id AND status = 'RUNNING' "
|
||||
+ "AND execution_token = :token "
|
||||
+ "AND started_at + INTERVAL 30 MINUTE <= CURRENT_TIMESTAMP(6)", nativeQuery = true)
|
||||
int timeoutIfHardDeadlineExpired(@Param("id") Long id, @Param("token") String token,
|
||||
@Param("error") String error);
|
||||
}
|
||||
@@ -2,6 +2,9 @@ package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.SysRole;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
@@ -9,5 +12,8 @@ import java.util.Optional;
|
||||
@Repository
|
||||
public interface SysRoleRepository extends JpaRepository<SysRole, Long> {
|
||||
Optional<SysRole> findByRoleCode(String roleCode);
|
||||
@Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select r from SysRole r where r.roleCode = :roleCode")
|
||||
Optional<SysRole> findByRoleCodeForUpdate(@Param("roleCode") String roleCode);
|
||||
boolean existsByRoleCode(String roleCode);
|
||||
}
|
||||
@@ -5,11 +5,14 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Collection;
|
||||
|
||||
@Repository
|
||||
public interface SysUserGroupMemberRepository extends JpaRepository<SysUserGroupMember, SysUserGroupMember.SysUserGroupMemberId> {
|
||||
List<SysUserGroupMember> findByIdGroupId(Long groupId);
|
||||
List<SysUserGroupMember> findByIdUserId(Long userId);
|
||||
List<SysUserGroupMember> findByIdUserIdIn(Collection<Long> userIds);
|
||||
boolean existsByIdUserId(Long userId);
|
||||
void deleteByIdGroupId(Long groupId);
|
||||
void deleteByIdUserId(Long userId);
|
||||
}
|
||||
@@ -2,6 +2,9 @@ package com.finance.system.repository;
|
||||
|
||||
import com.finance.system.entity.SysUserGroup;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
@@ -9,5 +12,8 @@ import java.util.Optional;
|
||||
@Repository
|
||||
public interface SysUserGroupRepository extends JpaRepository<SysUserGroup, Long> {
|
||||
Optional<SysUserGroup> findByGroupCode(String groupCode);
|
||||
@Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select g from SysUserGroup g where g.id = :id")
|
||||
Optional<SysUserGroup> findByIdForUpdate(@Param("id") Long id);
|
||||
boolean existsByGroupCode(String groupCode);
|
||||
}
|
||||
@@ -3,8 +3,12 @@ package com.finance.system.repository;
|
||||
import com.finance.system.entity.SysUser;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface SysUserRepository extends JpaRepository<SysUser, Long> {
|
||||
@@ -16,4 +20,8 @@ public interface SysUserRepository extends JpaRepository<SysUser, Long> {
|
||||
SysUser findByEmployeeNo(String employeeNo);
|
||||
|
||||
List<SysUser> findByUserType(String userType);
|
||||
}
|
||||
|
||||
@Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select u from SysUser u where u.id = :id")
|
||||
Optional<SysUser> findByIdForUpdate(@Param("id") Long id);
|
||||
}
|
||||
@@ -22,14 +22,18 @@ public class SysWebhookEventRepositoryImpl implements SysWebhookEventRepositoryC
|
||||
}
|
||||
|
||||
private int executeInsertIfAbsent(Connection connection, String eventId) {
|
||||
boolean h2 = isH2(connection);
|
||||
String product = databaseProduct(connection);
|
||||
boolean h2 = "H2".equalsIgnoreCase(product);
|
||||
boolean mysql = "MySQL".equalsIgnoreCase(product);
|
||||
if (!h2 && !mysql) {
|
||||
throw new PersistenceException("Unsupported database for webhook inbox: " + product);
|
||||
}
|
||||
String sql = h2
|
||||
? "INSERT INTO sys_webhook_event (event_id, status, created_at) "
|
||||
+ "SELECT ?, 'PROCESSING', CURRENT_TIMESTAMP "
|
||||
+ "WHERE NOT EXISTS (SELECT 1 FROM sys_webhook_event WHERE event_id = ?)"
|
||||
: "INSERT INTO sys_webhook_event (event_id, status, created_at) "
|
||||
+ "VALUES (?, 'PROCESSING', CURRENT_TIMESTAMP) "
|
||||
+ "ON CONFLICT (event_id) DO NOTHING";
|
||||
+ "VALUES (?, 'PROCESSING', CURRENT_TIMESTAMP(6))";
|
||||
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, eventId);
|
||||
@@ -38,19 +42,19 @@ public class SysWebhookEventRepositoryImpl implements SysWebhookEventRepositoryC
|
||||
}
|
||||
return statement.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
// The H2 fallback has the same unique-key race window as any
|
||||
// INSERT ... WHERE NOT EXISTS. A concurrent loser is a duplicate,
|
||||
// which has the same insert-if-absent result as ON CONFLICT DO NOTHING.
|
||||
if (h2 && "23505".equals(e.getSQLState())) {
|
||||
// Both the MySQL insert and the H2 test fallback resolve a
|
||||
// concurrent loser as the insert-if-absent result zero.
|
||||
if ((mysql && e.getErrorCode() == 1062)
|
||||
|| (h2 && "23505".equals(e.getSQLState()))) {
|
||||
return 0;
|
||||
}
|
||||
throw new PersistenceException("Unable to insert webhook inbox event", e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isH2(Connection connection) {
|
||||
private String databaseProduct(Connection connection) {
|
||||
try {
|
||||
return "H2".equalsIgnoreCase(connection.getMetaData().getDatabaseProductName());
|
||||
return connection.getMetaData().getDatabaseProductName();
|
||||
} catch (SQLException e) {
|
||||
throw new PersistenceException("Unable to determine database product", e);
|
||||
}
|
||||
|
||||
@@ -11,15 +11,13 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Collections;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -89,20 +87,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
.feishuOpenId(user.getFeishuOpenId())
|
||||
.build();
|
||||
|
||||
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
|
||||
if (StringUtils.hasText(userType)) {
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_" + userType));
|
||||
// Preserve the existing SUPER_ADMIN permission expansion, but use
|
||||
// the role read from the database on every request.
|
||||
if ("SUPER_ADMIN".equals(userType)) {
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_FINANCE"));
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_CASHIER"));
|
||||
}
|
||||
}
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
|
||||
new UsernamePasswordAuthenticationToken(userPrincipal, null, Collections.emptyList());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,23 @@ public class PermissionChecker {
|
||||
if (authentication == null || !authentication.isAuthenticated()
|
||||
|| !(authentication.getPrincipal() instanceof UserPrincipal)) return false;
|
||||
UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
|
||||
return principal.getId() != null && roleService.hasPermission(principal.getId(), permissionCode);
|
||||
if (principal.getId() == null) return false;
|
||||
try {
|
||||
return roleService.hasPermission(principal.getId(), permissionCode);
|
||||
} catch (RuntimeException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasEdit(Authentication authentication, String permissionCode) {
|
||||
if (authentication == null || !authentication.isAuthenticated()
|
||||
|| !(authentication.getPrincipal() instanceof UserPrincipal)) return false;
|
||||
UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
|
||||
if (principal.getId() == null) return false;
|
||||
try {
|
||||
return roleService.hasEditPermission(principal.getId(), permissionCode);
|
||||
} catch (RuntimeException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,10 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import com.finance.system.service.RoleService;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@@ -26,7 +24,7 @@ public class UserPrincipal implements UserDetails {
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return Collections.<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_" + RoleService.normalize(userType)));
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.finance.system.service;
|
||||
|
||||
import com.finance.system.entity.SysWebhookEvent;
|
||||
import com.finance.system.repository.SysWebhookEventRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FeishuWebhookInboxService {
|
||||
public enum ClaimOutcome { ACQUIRED, ALREADY_PROCESSED, BUSY }
|
||||
private final SysWebhookEventRepository events;
|
||||
@Value("${feishu.webhook.processing-lease-seconds:120}")
|
||||
private long processingLeaseSeconds;
|
||||
@Transactional
|
||||
public ClaimOutcome begin(String id) {
|
||||
events.insertIfAbsent(id);
|
||||
SysWebhookEvent event = events.findById(id).orElseThrow(() -> new IllegalStateException("webhook inbox unavailable"));
|
||||
if (SysWebhookEvent.PROCESSED.equals(event.getStatus())) return ClaimOutcome.ALREADY_PROCESSED;
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
if (SysWebhookEvent.PROCESSING.equals(event.getStatus()) && event.getProcessingStartedAt() != null
|
||||
&& event.getProcessingStartedAt().isAfter(now.minusSeconds(Math.max(1, processingLeaseSeconds))))
|
||||
return ClaimOutcome.BUSY;
|
||||
event.setStatus(SysWebhookEvent.PROCESSING); event.setProcessingStartedAt(now); events.save(event);
|
||||
return ClaimOutcome.ACQUIRED;
|
||||
}
|
||||
@Transactional public void processed(String id){events.findById(id).ifPresent(e->{e.setStatus(SysWebhookEvent.PROCESSED);e.setProcessingStartedAt(null);events.save(e);});}
|
||||
@Transactional public void failed(String id){events.findById(id).ifPresent(e->{e.setStatus(SysWebhookEvent.FAILED);e.setProcessingStartedAt(null);events.save(e);});}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.finance.system.service;
|
||||
|
||||
import com.finance.system.entity.SysKingdeeSyncConfig;
|
||||
import com.finance.system.entity.SysKingdeeSyncField;
|
||||
import com.finance.system.entity.SysKingdeeSyncFilter;
|
||||
import com.finance.system.entity.SysKingdeeSyncRun;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import com.finance.system.exception.ResourceNotFoundException;
|
||||
import com.finance.system.repository.SysKingdeeSyncConfigRepository;
|
||||
import com.finance.system.repository.SysKingdeeSyncFieldRepository;
|
||||
import com.finance.system.repository.SysKingdeeSyncFilterRepository;
|
||||
import com.finance.system.repository.SysKingdeeSyncRunRepository;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class KingdeeAsyncSyncService {
|
||||
static final Duration MAX_RUNTIME = Duration.ofMinutes(30);
|
||||
|
||||
private final SysKingdeeSyncConfigRepository configRepository;
|
||||
private final SysKingdeeSyncFieldRepository fieldRepository;
|
||||
private final SysKingdeeSyncFilterRepository filterRepository;
|
||||
private final SysKingdeeSyncRunRepository runRepository;
|
||||
private final KingdeeDocumentSyncService documentSyncService;
|
||||
private final KingdeeSyncRunStateService stateService;
|
||||
private final KingdeeFencedRowWriteService fencedRowWriteService;
|
||||
private final ThreadPoolTaskExecutor executor;
|
||||
private final ThreadPoolTaskScheduler heartbeatScheduler;
|
||||
private final ThreadPoolTaskScheduler deadlineScheduler;
|
||||
private final TransactionTemplate transaction;
|
||||
|
||||
public KingdeeAsyncSyncService(SysKingdeeSyncConfigRepository configRepository,
|
||||
SysKingdeeSyncFieldRepository fieldRepository,
|
||||
SysKingdeeSyncFilterRepository filterRepository,
|
||||
SysKingdeeSyncRunRepository runRepository,
|
||||
KingdeeDocumentSyncService documentSyncService,
|
||||
KingdeeSyncRunStateService stateService,
|
||||
KingdeeFencedRowWriteService fencedRowWriteService,
|
||||
@Qualifier("kingdeeSyncExecutor") ThreadPoolTaskExecutor executor,
|
||||
@Qualifier("kingdeeSyncHeartbeatScheduler") ThreadPoolTaskScheduler heartbeatScheduler,
|
||||
@Qualifier("kingdeeSyncDeadlineScheduler") ThreadPoolTaskScheduler deadlineScheduler,
|
||||
PlatformTransactionManager transactionManager) {
|
||||
this.configRepository = configRepository;
|
||||
this.fieldRepository = fieldRepository;
|
||||
this.filterRepository = filterRepository;
|
||||
this.runRepository = runRepository;
|
||||
this.documentSyncService = documentSyncService;
|
||||
this.stateService = stateService;
|
||||
this.fencedRowWriteService = fencedRowWriteService;
|
||||
this.executor = executor;
|
||||
this.heartbeatScheduler = heartbeatScheduler;
|
||||
this.deadlineScheduler = deadlineScheduler;
|
||||
this.transaction = new TransactionTemplate(transactionManager);
|
||||
this.transaction.setTimeout(30);
|
||||
}
|
||||
|
||||
public Map<String, Object> start(Long configId) {
|
||||
final ReservedWork work;
|
||||
try {
|
||||
work = transaction.execute(status -> reserve(configId));
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new BusinessException("该同步规则已有任务正在运行", 409);
|
||||
}
|
||||
if (work == null) throw new BusinessException("同步任务创建失败", 500);
|
||||
|
||||
Future<?> submitted = null;
|
||||
ScheduledFuture<?> heartbeat = null;
|
||||
ScheduledFuture<?> deadlineTask = null;
|
||||
try {
|
||||
heartbeat = heartbeatScheduler.scheduleAtFixedRate(() ->
|
||||
fencedRowWriteService.renewLease(work.run.getId(), work.run.getExecutionToken()),
|
||||
new Date(), 30000L);
|
||||
work.heartbeat = heartbeat;
|
||||
AtomicReference<Future<?>> worker = new AtomicReference<>();
|
||||
final ScheduledFuture<?> retainedHeartbeat = heartbeat;
|
||||
deadlineTask = deadlineScheduler.schedule(() -> {
|
||||
retainedHeartbeat.cancel(false);
|
||||
if (stateService.timeoutIfHardDeadlineExpired(work.run.getId(), work.run.getExecutionToken())) {
|
||||
Future<?> running = worker.get();
|
||||
if (running != null) running.cancel(true);
|
||||
}
|
||||
}, Instant.now().plus(MAX_RUNTIME));
|
||||
work.deadlineTask = deadlineTask;
|
||||
submitted = executor.submit(() -> execute(work));
|
||||
worker.set(submitted);
|
||||
} catch (RejectedExecutionException e) {
|
||||
if (submitted != null) submitted.cancel(true);
|
||||
if (heartbeat != null) heartbeat.cancel(false);
|
||||
if (deadlineTask != null) deadlineTask.cancel(false);
|
||||
try {
|
||||
stateService.fail(work.run.getId(), work.run.getExecutionToken(), "同步执行资源不可用");
|
||||
} catch (RuntimeException ignored) {
|
||||
// The reservation is still fenced by its short lease and the
|
||||
// periodic reaper. The API contract must remain a 503.
|
||||
}
|
||||
throw new BusinessException("同步执行资源不可用,请稍后重试", 503);
|
||||
}
|
||||
return runMap(work.run);
|
||||
}
|
||||
|
||||
private ReservedWork reserve(Long configId) {
|
||||
if (configId == null) throw new ResourceNotFoundException("金蝶同步配置不存在");
|
||||
SysKingdeeSyncConfig config = configRepository.findByIdForUpdate(configId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + configId));
|
||||
SysKingdeeSyncRun active = runRepository
|
||||
.findFirstByConfigIdAndStatusOrderByStartedAtDesc(configId, "RUNNING").orElse(null);
|
||||
if (active != null && runRepository.failExpiredRun(active.getId(),
|
||||
KingdeeSyncRunStateService.TIMEOUT_MESSAGE) == 1) active = null;
|
||||
if (active != null) throw new BusinessException("该同步规则已有任务正在运行", 409);
|
||||
if (!Boolean.TRUE.equals(config.getEnabled())) throw new BusinessException("同步配置未启用", 409);
|
||||
|
||||
List<SysKingdeeSyncField> fields = fieldRepository.findByConfigIdOrderBySortOrderAscIdAsc(configId);
|
||||
List<SysKingdeeSyncFilter> filters = filterRepository.findByConfigIdOrderBySortOrderAscIdAsc(configId);
|
||||
String filterString = documentSyncService.compileFilter(filters);
|
||||
LocalDateTime now = runRepository.currentDatabaseTime();
|
||||
String token = UUID.randomUUID().toString();
|
||||
SysKingdeeSyncRun run = SysKingdeeSyncRun.builder().configId(configId).status("RUNNING")
|
||||
.filterString(filterString).fetchedCount(0).insertedCount(0).updatedCount(0).failedCount(0)
|
||||
.startedAt(now).executionToken(token).heartbeatAt(now)
|
||||
.leaseUntil(now.plus(KingdeeFencedRowWriteService.LEASE_DURATION)).build();
|
||||
run = runRepository.saveAndFlush(run);
|
||||
return new ReservedWork(run, new KingdeeSyncConfigService.Aggregate(config, fields, filters));
|
||||
}
|
||||
|
||||
private void execute(ReservedWork work) {
|
||||
try {
|
||||
KingdeeDocumentSyncService.ExecutionResult result = documentSyncService.execute(
|
||||
work.aggregate, work.run.getId(), work.run.getExecutionToken());
|
||||
stateService.finish(work.run.getId(), work.run.getExecutionToken(), result);
|
||||
} catch (RuntimeException e) {
|
||||
stateService.fail(work.run.getId(), work.run.getExecutionToken(), "同步处理失败");
|
||||
} finally {
|
||||
if (work.heartbeat != null) work.heartbeat.cancel(false);
|
||||
if (work.deadlineTask != null) work.deadlineTask.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> runMap(SysKingdeeSyncRun run) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("id", run.getId()); result.put("configId", run.getConfigId()); result.put("status", run.getStatus());
|
||||
result.put("filterString", run.getFilterString()); result.put("fetchedCount", run.getFetchedCount());
|
||||
result.put("insertedCount", run.getInsertedCount()); result.put("updatedCount", run.getUpdatedCount());
|
||||
result.put("failedCount", run.getFailedCount()); result.put("errorMessage", run.getErrorMessage());
|
||||
result.put("startedAt", run.getStartedAt()); result.put("finishedAt", run.getFinishedAt());
|
||||
result.put("heartbeatAt", run.getHeartbeatAt()); result.put("leaseUntil", run.getLeaseUntil());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class ReservedWork {
|
||||
private final SysKingdeeSyncRun run;
|
||||
private final KingdeeSyncConfigService.Aggregate aggregate;
|
||||
private volatile ScheduledFuture<?> heartbeat;
|
||||
private volatile ScheduledFuture<?> deadlineTask;
|
||||
private ReservedWork(SysKingdeeSyncRun run, KingdeeSyncConfigService.Aggregate aggregate) {
|
||||
this.run = run;
|
||||
this.aggregate = aggregate;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
package com.finance.system.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.finance.system.adapter.kingdee.KingdeeClient;
|
||||
import com.finance.system.entity.SysKingdeeSyncConfig;
|
||||
import com.finance.system.entity.SysKingdeeSyncField;
|
||||
import com.finance.system.entity.SysKingdeeSyncFilter;
|
||||
import com.finance.system.entity.SysKingdeeSyncRun;
|
||||
import com.finance.system.exception.BadRequestException;
|
||||
import com.finance.system.exception.BusinessException;
|
||||
import com.finance.system.repository.SysKingdeeSyncRunRepository;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.ConnectionCallback;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.sql.Types;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Performs inbound document reads and writes only; it does not alter the existing outbound save service. */
|
||||
@Slf4j
|
||||
@Service
|
||||
public class KingdeeDocumentSyncService {
|
||||
private static final Pattern IDENTIFIER = Pattern.compile("[a-z][a-z0-9_]{0,62}");
|
||||
private static final Set<String> TYPES = new HashSet<>(Arrays.asList(
|
||||
"STRING", "INTEGER", "BIGINT", "DECIMAL", "DATE", "DATETIME", "BOOLEAN", "JSON"));
|
||||
private final KingdeeClient kingdeeClient;
|
||||
private final KingdeeFilterCompiler filterCompiler;
|
||||
private final JdbcTemplate jdbc;
|
||||
private final SysKingdeeSyncRunRepository runRepository;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private KingdeeFencedRowWriteService fencedRowWriteService;
|
||||
|
||||
public KingdeeDocumentSyncService(KingdeeClient kingdeeClient, KingdeeFilterCompiler filterCompiler,
|
||||
JdbcTemplate jdbc, SysKingdeeSyncRunRepository runRepository) {
|
||||
this.kingdeeClient = kingdeeClient;
|
||||
this.filterCompiler = filterCompiler;
|
||||
this.jdbc = jdbc;
|
||||
this.runRepository = runRepository;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setFencedRowWriteService(KingdeeFencedRowWriteService fencedRowWriteService) {
|
||||
this.fencedRowWriteService = fencedRowWriteService;
|
||||
}
|
||||
|
||||
public Map<String, Object> preview(KingdeeSyncConfigService.Aggregate aggregate) {
|
||||
// Preview and sync must use the same bounded filter compilation path.
|
||||
String filterString = compileFilter(aggregate.getFilters());
|
||||
String fieldKeys = fieldKeys(aggregate.getFields());
|
||||
List<Map<String, Object>> rows;
|
||||
try {
|
||||
rows = kingdeeClient.query(aggregate.getConfig().getFormId(), filterString, fieldKeys, 0, 20);
|
||||
} catch (Exception e) {
|
||||
log.warn("金蝶同步预览失败: configId={}", aggregate.getConfig().getId());
|
||||
throw new BusinessException("金蝶预览请求失败", 502);
|
||||
}
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("filterString", filterString);
|
||||
result.put("rows", rows == null ? Collections.emptyList() : rows.subList(0, Math.min(20, rows.size())));
|
||||
result.put("truncated", rows != null && rows.size() >= 20);
|
||||
return result;
|
||||
}
|
||||
|
||||
public Map<String, Object> prepareTable(KingdeeSyncConfigService.Aggregate aggregate) {
|
||||
return prepareTable(aggregate, null);
|
||||
}
|
||||
|
||||
private Map<String, Object> prepareTable(KingdeeSyncConfigService.Aggregate aggregate, Runnable leaseCheck) {
|
||||
SysKingdeeSyncConfig config = aggregate.getConfig();
|
||||
String table = identifier(config.getTargetTableName());
|
||||
if (aggregate.getFields() == null || aggregate.getFields().isEmpty())
|
||||
throw new BadRequestException("至少配置一个同步字段");
|
||||
for (SysKingdeeSyncField field : aggregate.getFields()) {
|
||||
if (!KingdeeFilterCompiler.isSafeSourceField(field.getSourceFieldKey()))
|
||||
throw new BadRequestException("动态字段标识不安全");
|
||||
identifier(field.getTargetColumnName());
|
||||
if (!TYPES.contains(field.getDataType())) throw new BadRequestException("不支持的数据类型");
|
||||
}
|
||||
try {
|
||||
return withDdlLock(table, leaseCheck, () -> prepareTableLocked(table, config, aggregate.getFields()));
|
||||
} catch (DataAccessException e) {
|
||||
log.error("金蝶同步表准备失败: configId={}", config.getId());
|
||||
throw new BusinessException("目标表准备失败", 409);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> prepareTableLocked(String table, SysKingdeeSyncConfig config,
|
||||
List<SysKingdeeSyncField> fields) throws SQLException {
|
||||
Map<String, ColumnInfo> columns = tableColumns(table);
|
||||
boolean created = columns.isEmpty() && !tableExists(table);
|
||||
if (created) {
|
||||
jdbc.execute(createTableSql(table, config, fields));
|
||||
// MySQL DDL is implicitly committed, so the advisory lock remains
|
||||
// held while the declared shape is validated and comments are added.
|
||||
columns = declaredColumns(fields);
|
||||
}
|
||||
ensureColumn(columns, "_kd_id", "BIGINT");
|
||||
if (!created) ensureSourceKey(columns, table);
|
||||
ensureColumn(columns, "_kd_synced_at", "DATETIME");
|
||||
for (SysKingdeeSyncField field : fields) ensureColumn(columns, field.getTargetColumnName(), field.getDataType());
|
||||
addComments(config, fields);
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("tableName", table); result.put("created", created); result.put("columnCount", columns.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
<T> T withDdlLock(String table, Runnable leaseCheck, DdlOperation<T> operation) {
|
||||
String lockName = "finance:kingdee-ddl:" + shortHash(table);
|
||||
return jdbc.execute((ConnectionCallback<T>) connection -> {
|
||||
boolean acquired = false;
|
||||
try (PreparedStatement statement = connection.prepareStatement("SELECT GET_LOCK(?, ?)")) {
|
||||
statement.setString(1, lockName);
|
||||
statement.setInt(2, 10);
|
||||
try (ResultSet result = statement.executeQuery()) {
|
||||
acquired = result.next() && result.getInt(1) == 1;
|
||||
}
|
||||
}
|
||||
if (!acquired) throw new BusinessException("目标表结构正在被其他任务修改", 409);
|
||||
try {
|
||||
if (leaseCheck != null) leaseCheck.run();
|
||||
T result = operation.execute();
|
||||
if (leaseCheck != null) leaseCheck.run();
|
||||
return result;
|
||||
} finally {
|
||||
try (PreparedStatement statement = connection.prepareStatement("SELECT RELEASE_LOCK(?)")) {
|
||||
statement.setString(1, lockName);
|
||||
try (ResultSet ignored = statement.executeQuery()) {
|
||||
if (ignored.next() && ignored.getInt(1) != 1)
|
||||
log.warn("金蝶同步DDL锁释放状态异常: table={}", table);
|
||||
}
|
||||
} catch (SQLException releaseFailure) {
|
||||
log.warn("金蝶同步DDL锁释放失败: table={}", table);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, ColumnInfo> declaredColumns(List<SysKingdeeSyncField> fields) {
|
||||
Map<String, ColumnInfo> columns = new HashMap<>();
|
||||
columns.put("_kd_id", new ColumnInfo(Types.BIGINT, "BIGINT", DatabaseMetaData.columnNoNulls));
|
||||
columns.put("_kd_source_key", new ColumnInfo(Types.VARCHAR, "VARCHAR", DatabaseMetaData.columnNoNulls));
|
||||
columns.put("_kd_synced_at", new ColumnInfo(Types.TIMESTAMP, "TIMESTAMP", DatabaseMetaData.columnNoNulls));
|
||||
for (SysKingdeeSyncField field : fields) {
|
||||
int jdbcType = "INTEGER".equals(field.getDataType()) ? Types.INTEGER
|
||||
: "BIGINT".equals(field.getDataType()) ? Types.BIGINT
|
||||
: "DECIMAL".equals(field.getDataType()) ? Types.DECIMAL
|
||||
: "DATE".equals(field.getDataType()) ? Types.DATE
|
||||
: "DATETIME".equals(field.getDataType()) ? Types.TIMESTAMP
|
||||
: "BOOLEAN".equals(field.getDataType()) ? Types.BOOLEAN : Types.VARCHAR;
|
||||
columns.put(field.getTargetColumnName().toLowerCase(Locale.ROOT),
|
||||
new ColumnInfo(jdbcType, field.getDataType(), DatabaseMetaData.columnNullable));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
public ExecutionResult execute(KingdeeSyncConfigService.Aggregate aggregate, Long runId,
|
||||
String executionToken) {
|
||||
SysKingdeeSyncConfig config = aggregate.getConfig();
|
||||
ExecutionResult result = new ExecutionResult();
|
||||
int start = 0;
|
||||
try {
|
||||
if (fencedRowWriteService == null) throw new IllegalStateException("金蝶同步写入围栏未初始化");
|
||||
requireLease(runId, executionToken);
|
||||
fencedRowWriteService.executeFenced(runId, executionToken,
|
||||
() -> prepareTable(aggregate, () -> requireLease(runId, executionToken)));
|
||||
requireLease(runId, executionToken);
|
||||
int max = config.getMaxRowsPerRun() == null ? 10000 : config.getMaxRowsPerRun();
|
||||
int pageSize;
|
||||
String filterString = compileFilter(aggregate.getFilters());
|
||||
while (start < max) {
|
||||
checkInterrupted();
|
||||
requireLease(runId, executionToken);
|
||||
pageSize = Math.min(100, max - start);
|
||||
List<Map<String, Object>> rows;
|
||||
try {
|
||||
rows = kingdeeClient.query(config.getFormId(), filterString, fieldKeys(aggregate.getFields()), start, pageSize);
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("金蝶同步请求失败", 502);
|
||||
}
|
||||
requireLease(runId, executionToken);
|
||||
if (rows == null || rows.isEmpty()) break;
|
||||
for (int i = 0; i < rows.size() && start + i < max; i++) {
|
||||
checkInterrupted();
|
||||
final Map<String, Object> row = rows.get(i);
|
||||
KingdeeFencedRowWriteService.WriteResult writeResult = fencedRowWriteService.write(
|
||||
runId, executionToken,
|
||||
() -> upsert(config.getFormId(), config.getTargetTableName(), aggregate.getFields(), row));
|
||||
result.fetchedCount++;
|
||||
if (writeResult == KingdeeFencedRowWriteService.WriteResult.INSERTED) result.insertedCount++;
|
||||
else if (writeResult == KingdeeFencedRowWriteService.WriteResult.UPDATED) result.updatedCount++;
|
||||
else {
|
||||
result.failedCount++;
|
||||
log.warn("金蝶同步行处理失败: configId={}, row={}", config.getId(), start + i + 1);
|
||||
}
|
||||
}
|
||||
if (rows.size() < pageSize) break;
|
||||
start += rows.size();
|
||||
}
|
||||
result.status = result.failedCount > 0 ? "PARTIAL" : "SUCCEEDED";
|
||||
} catch (Exception e) {
|
||||
result.status = "FAILED";
|
||||
result.errorMessage = e instanceof BusinessException && ((BusinessException) e).getStatusCode() == 502
|
||||
? "金蝶接口调用失败" : e instanceof InterruptedException || Thread.currentThread().isInterrupted()
|
||||
? "同步任务超过30分钟,已停止处理" : "同步处理失败";
|
||||
if (e instanceof InterruptedException) Thread.currentThread().interrupt();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void requireLease(Long runId, String token) {
|
||||
if (!fencedRowWriteService.renewLease(runId, token))
|
||||
throw new KingdeeFencedRowWriteService.KingdeeSyncFenceException();
|
||||
}
|
||||
|
||||
private void checkInterrupted() throws InterruptedException {
|
||||
if (Thread.currentThread().isInterrupted())
|
||||
throw new InterruptedException("Kingdee sync deadline exceeded");
|
||||
}
|
||||
|
||||
String compileFilter(List<SysKingdeeSyncFilter> filters) {
|
||||
String filterString = filterCompiler.compile(filters);
|
||||
if (filterString != null && filterString.length() > KingdeeFilterCompiler.MAX_FILTER_STRING_LENGTH)
|
||||
throw new BadRequestException("过滤条件生成结果过长,不能超过" + KingdeeFilterCompiler.MAX_FILTER_STRING_LENGTH + "个字符");
|
||||
return filterString == null ? "" : filterString;
|
||||
}
|
||||
|
||||
public static class ExecutionResult {
|
||||
private String status = "FAILED";
|
||||
private int fetchedCount;
|
||||
private int insertedCount;
|
||||
private int updatedCount;
|
||||
private int failedCount;
|
||||
private String errorMessage;
|
||||
public String getStatus() { return status; }
|
||||
public int getFetchedCount() { return fetchedCount; }
|
||||
public int getInsertedCount() { return insertedCount; }
|
||||
public int getUpdatedCount() { return updatedCount; }
|
||||
public int getFailedCount() { return failedCount; }
|
||||
public String getErrorMessage() { return errorMessage; }
|
||||
}
|
||||
|
||||
private int upsert(String formId, String rawTable, List<SysKingdeeSyncField> fields, Map<String, Object> row) {
|
||||
String table = identifier(rawTable);
|
||||
String sourceKey = buildDeterministicSourceKey(formId, fields, row);
|
||||
if (sourceKey.length() > 255) throw new IllegalArgumentException("来源主键长度超过255");
|
||||
List<Object> values = new ArrayList<>();
|
||||
for (SysKingdeeSyncField field : fields) values.add(convert(value(row, field.getSourceFieldKey()), field));
|
||||
StringBuilder update = new StringBuilder("UPDATE ").append(quote(table)).append(" SET ");
|
||||
for (int i = 0; i < fields.size(); i++) {
|
||||
if (i > 0) update.append(", ");
|
||||
update.append(quote(identifier(fields.get(i).getTargetColumnName()))).append("=?");
|
||||
}
|
||||
update.append(", ").append(quote("_kd_synced_at")).append("=CURRENT_TIMESTAMP(6) WHERE ")
|
||||
.append(quote("_kd_source_key")).append("=?");
|
||||
List<Object> updateArgs = new ArrayList<>(values); updateArgs.add(sourceKey);
|
||||
if (jdbc.update(update.toString(), updateArgs.toArray()) > 0) return 0;
|
||||
StringBuilder insert = new StringBuilder("INSERT INTO ").append(quote(table))
|
||||
.append(" (").append(quote("_kd_source_key")).append(", ").append(quote("_kd_synced_at"));
|
||||
for (SysKingdeeSyncField field : fields) insert.append(", ").append(quote(identifier(field.getTargetColumnName())));
|
||||
insert.append(") VALUES (?, CURRENT_TIMESTAMP(6)");
|
||||
for (int i = 0; i < fields.size(); i++) insert.append(", ?");
|
||||
insert.append(")");
|
||||
List<Object> insertArgs = new ArrayList<>(); insertArgs.add(sourceKey); insertArgs.addAll(values);
|
||||
try {
|
||||
jdbc.update(insert.toString(), insertArgs.toArray());
|
||||
return 1;
|
||||
} catch (DataAccessException duplicateOrRace) {
|
||||
// A second application instance may win between UPDATE and INSERT.
|
||||
if (jdbc.update(update.toString(), updateArgs.toArray()) > 0) return 0;
|
||||
throw duplicateOrRace;
|
||||
}
|
||||
}
|
||||
|
||||
private Object value(Map<String, Object> row, String key) {
|
||||
if (row == null) return null;
|
||||
if (row.containsKey(key)) return row.get(key);
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) if (key.equalsIgnoreCase(entry.getKey())) return entry.getValue();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the immutable Kingdee bill number. A mutable field-value digest
|
||||
* is not a safe identity: changing a document would otherwise insert a
|
||||
* second row instead of updating the existing one.
|
||||
*/
|
||||
public static String buildDeterministicSourceKey(String formId, List<SysKingdeeSyncField> fields,
|
||||
Map<String, Object> row) {
|
||||
if (fields == null || fields.isEmpty()) throw new IllegalArgumentException("同步字段不能为空");
|
||||
Object billNo = sourceValue(row, "FBillNo");
|
||||
if (billNo == null || String.valueOf(billNo).trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("金蝶返回数据缺少 FBillNo,拒绝生成不稳定来源主键");
|
||||
}
|
||||
String normalizedFormId = formId == null ? "" : formId.trim();
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
digest.update((normalizedFormId + "\u0000" + String.valueOf(billNo).trim())
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
return hex(digest.digest());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("来源键生成失败");
|
||||
}
|
||||
}
|
||||
|
||||
private static Object sourceValue(Map<String, Object> row, String key) {
|
||||
if (row == null) return null;
|
||||
if (row.containsKey(key)) return row.get(key);
|
||||
for (Map.Entry<String, Object> entry : row.entrySet())
|
||||
if (key != null && key.equalsIgnoreCase(entry.getKey())) return entry.getValue();
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
char[] digits = "0123456789abcdef".toCharArray();
|
||||
char[] result = new char[bytes.length * 2];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
int value = bytes[i] & 0xff;
|
||||
result[i * 2] = digits[value >>> 4]; result[i * 2 + 1] = digits[value & 0x0f];
|
||||
}
|
||||
return new String(result);
|
||||
}
|
||||
|
||||
private Object convert(Object value, SysKingdeeSyncField field) {
|
||||
if (value == null) return null;
|
||||
String type = field.getDataType();
|
||||
if ("STRING".equals(type)) return String.valueOf(value);
|
||||
if ("JSON".equals(type)) {
|
||||
if (value instanceof String) return value;
|
||||
try { return objectMapper.writeValueAsString(value); } catch (Exception e) { throw new IllegalArgumentException("JSON转换失败"); }
|
||||
}
|
||||
String text = String.valueOf(value).trim();
|
||||
if ("INTEGER".equals(type)) return value instanceof Number ? ((Number) value).intValue() : Integer.valueOf(text);
|
||||
if ("BIGINT".equals(type)) return value instanceof Number ? ((Number) value).longValue() : Long.valueOf(text);
|
||||
if ("DECIMAL".equals(type)) return value instanceof BigDecimal ? value : new BigDecimal(text);
|
||||
if ("DATE".equals(type)) return value instanceof java.sql.Date ? value : java.sql.Date.valueOf(LocalDate.parse(text.substring(0, 10)));
|
||||
if ("DATETIME".equals(type)) return value instanceof Timestamp ? value : Timestamp.valueOf(normalizeDateTime(text));
|
||||
if ("BOOLEAN".equals(type)) {
|
||||
if (value instanceof Boolean) return value;
|
||||
if ("true".equalsIgnoreCase(text) || "1".equals(text)) return Boolean.TRUE;
|
||||
if ("false".equalsIgnoreCase(text) || "0".equals(text)) return Boolean.FALSE;
|
||||
throw new IllegalArgumentException("BOOLEAN转换失败");
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的数据类型");
|
||||
}
|
||||
|
||||
private String normalizeDateTime(String value) {
|
||||
String text = value.replace('T', ' ');
|
||||
if (text.length() == 10) return text + " 00:00:00";
|
||||
if (text.length() == 16) return text + ":00";
|
||||
return text;
|
||||
}
|
||||
|
||||
private String fieldKeys(List<SysKingdeeSyncField> fields) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
boolean hasBillNo = false;
|
||||
for (SysKingdeeSyncField field : fields) {
|
||||
if (result.length() > 0) result.append(",");
|
||||
result.append(field.getSourceFieldKey());
|
||||
if ("FBillNo".equalsIgnoreCase(field.getSourceFieldKey())) hasBillNo = true;
|
||||
}
|
||||
if (!hasBillNo) result.append(result.length() > 0 ? ",FBillNo" : "FBillNo");
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String createTableSql(String table, SysKingdeeSyncConfig config, List<SysKingdeeSyncField> fields) {
|
||||
StringBuilder sql = new StringBuilder("CREATE TABLE ").append(quote(table)).append(" (")
|
||||
.append(quote("_kd_id")).append(" BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, ")
|
||||
.append(quote("_kd_source_key")).append(" VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL UNIQUE, ")
|
||||
.append(quote("_kd_synced_at")).append(" DATETIME(6) NOT NULL");
|
||||
for (SysKingdeeSyncField field : fields) sql.append(", ").append(quote(identifier(field.getTargetColumnName())))
|
||||
.append(" ").append(sqlType(field))
|
||||
.append(field.getFieldComment() == null ? "" : " COMMENT '" + sqlLiteral(field.getFieldComment()) + "'");
|
||||
sql.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
|
||||
if (config.getTargetTableComment() != null)
|
||||
sql.append(" COMMENT='").append(sqlLiteral(config.getTargetTableComment())).append("'");
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
private String sqlType(SysKingdeeSyncField field) {
|
||||
String type = field.getDataType();
|
||||
if ("STRING".equals(type)) return "VARCHAR(" + (field.getFieldLength() == null ? 200 : field.getFieldLength()) + ")";
|
||||
if ("INTEGER".equals(type)) return "INTEGER";
|
||||
if ("BIGINT".equals(type)) return "BIGINT";
|
||||
if ("DECIMAL".equals(type)) return "DECIMAL(19,6)";
|
||||
if ("DATE".equals(type)) return "DATE";
|
||||
if ("DATETIME".equals(type)) return "DATETIME(6)";
|
||||
if ("BOOLEAN".equals(type)) return "TINYINT(1)";
|
||||
return "LONGTEXT";
|
||||
}
|
||||
|
||||
private Map<String, ColumnInfo> tableColumns(String table) throws SQLException {
|
||||
DataSource dataSource = jdbc.getDataSource();
|
||||
if (dataSource == null) throw new SQLException("数据库连接不可用");
|
||||
try (Connection connection = dataSource.getConnection()) {
|
||||
DatabaseMetaData metadata = connection.getMetaData();
|
||||
String actual = findTable(connection, table);
|
||||
if (actual == null) return new HashMap<>();
|
||||
Map<String, ColumnInfo> columns = new HashMap<>();
|
||||
try (ResultSet rs = metadata.getColumns(connection.getCatalog(), null, actual, "%")) {
|
||||
while (rs.next()) columns.put(rs.getString("COLUMN_NAME").toLowerCase(Locale.ROOT),
|
||||
new ColumnInfo(rs.getInt("DATA_TYPE"), rs.getString("TYPE_NAME"), rs.getInt("NULLABLE")));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tableExists(String table) throws SQLException {
|
||||
DataSource dataSource = jdbc.getDataSource();
|
||||
if (dataSource == null) throw new SQLException("数据库连接不可用");
|
||||
try (Connection connection = dataSource.getConnection()) { return findTable(connection, table) != null; }
|
||||
}
|
||||
|
||||
private String findTable(Connection connection, String table) throws SQLException {
|
||||
DatabaseMetaData metadata = connection.getMetaData();
|
||||
for (String candidate : new String[]{table, table.toUpperCase(Locale.ROOT), table.toLowerCase(Locale.ROOT)}) {
|
||||
try (ResultSet rs = metadata.getTables(connection.getCatalog(), null, candidate, new String[]{"TABLE"})) {
|
||||
if (rs.next()) return rs.getString("TABLE_NAME");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void ensureColumn(Map<String, ColumnInfo> columns, String name, String type) {
|
||||
ColumnInfo info = columns.get(name.toLowerCase(Locale.ROOT));
|
||||
if (info == null) throw new BusinessException("目标表缺少列: " + name, 409);
|
||||
if (!compatible(info, type)) throw new BusinessException("目标表列类型不兼容: " + name, 409);
|
||||
}
|
||||
|
||||
private void ensureSourceKey(Map<String, ColumnInfo> columns, String table) throws SQLException {
|
||||
ColumnInfo info = columns.get("_kd_source_key");
|
||||
if (info == null) throw new BusinessException("目标表缺少列: _kd_source_key", 409);
|
||||
if (info.nullability != DatabaseMetaData.columnNoNulls)
|
||||
throw new BusinessException("目标表 _kd_source_key 必须为非空列,无法安全建立唯一约束", 409);
|
||||
if (!compatible(info, "STRING")) throw new BusinessException("目标表列类型不兼容: _kd_source_key", 409);
|
||||
if (hasUniqueSourceKey(table)) return;
|
||||
String indexName = "uk_kd_src_" + shortHash(table);
|
||||
try {
|
||||
jdbc.execute("CREATE UNIQUE INDEX " + quote(indexName) + " ON " + quote(identifier(table))
|
||||
+ " (" + quote("_kd_source_key") + ")");
|
||||
} catch (DataAccessException e) {
|
||||
// Usually indicates duplicate existing keys. Do not modify or delete
|
||||
// data; report a deterministic configuration error instead.
|
||||
throw new BusinessException("无法为目标表建立 _kd_source_key 唯一约束,可能存在重复数据", 409);
|
||||
}
|
||||
// The index was created on the transaction-bound connection. A second
|
||||
// metadata connection may not see it until commit, so do not perform
|
||||
// a false-negative cross-connection recheck here.
|
||||
}
|
||||
|
||||
private boolean hasUniqueSourceKey(String table) throws SQLException {
|
||||
DataSource dataSource = jdbc.getDataSource();
|
||||
if (dataSource == null) throw new SQLException("数据库连接不可用");
|
||||
try (Connection connection = dataSource.getConnection()) {
|
||||
DatabaseMetaData metadata = connection.getMetaData();
|
||||
String actual = findTable(connection, table);
|
||||
if (actual == null) return false;
|
||||
Map<String, Integer> sizes = new HashMap<>();
|
||||
Map<String, Boolean> sourceOnly = new HashMap<>();
|
||||
try (ResultSet rs = metadata.getIndexInfo(connection.getCatalog(), null, actual, true, false)) {
|
||||
while (rs.next()) {
|
||||
String index = rs.getString("INDEX_NAME");
|
||||
String column = rs.getString("COLUMN_NAME");
|
||||
if (index == null || column == null) continue;
|
||||
String key = index.toLowerCase(Locale.ROOT);
|
||||
sizes.put(key, sizes.containsKey(key) ? sizes.get(key) + 1 : 1);
|
||||
sourceOnly.put(key, "_kd_source_key".equalsIgnoreCase(column)
|
||||
&& !sourceOnly.containsKey(key));
|
||||
if (!"_kd_source_key".equalsIgnoreCase(column)) sourceOnly.put(key, false);
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, Integer> entry : sizes.entrySet())
|
||||
if (entry.getValue() == 1 && Boolean.TRUE.equals(sourceOnly.get(entry.getKey()))) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String shortHash(String value) {
|
||||
try { return hex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))).substring(0, 24); }
|
||||
catch (Exception e) { throw new IllegalStateException("索引名生成失败"); }
|
||||
}
|
||||
|
||||
private boolean compatible(ColumnInfo info, String expected) {
|
||||
int t = info.jdbcType; String name = info.typeName == null ? "" : info.typeName.toLowerCase(Locale.ROOT);
|
||||
if ("STRING".equals(expected)) return t == Types.VARCHAR || t == Types.CHAR || t == Types.LONGVARCHAR || name.contains("char") || name.contains("text");
|
||||
if ("INTEGER".equals(expected)) return t == Types.INTEGER || name.contains("int");
|
||||
if ("BIGINT".equals(expected)) return t == Types.BIGINT || name.contains("bigint");
|
||||
if ("DECIMAL".equals(expected)) return t == Types.DECIMAL || t == Types.NUMERIC || name.contains("decimal") || name.contains("numeric");
|
||||
if ("DATE".equals(expected)) return t == Types.DATE || name.equals("date");
|
||||
if ("DATETIME".equals(expected)) return t == Types.TIMESTAMP || t == Types.TIMESTAMP_WITH_TIMEZONE || name.contains("timestamp") || name.contains("datetime");
|
||||
if ("BOOLEAN".equals(expected)) return t == Types.BOOLEAN || t == Types.BIT || name.contains("bool");
|
||||
return t == Types.LONGVARCHAR || t == Types.VARCHAR || name.contains("json") || name.contains("text");
|
||||
}
|
||||
|
||||
private void addComments(SysKingdeeSyncConfig config, List<SysKingdeeSyncField> fields) {
|
||||
try {
|
||||
if (config.getTargetTableComment() != null)
|
||||
jdbc.execute("ALTER TABLE " + quote(identifier(config.getTargetTableName()))
|
||||
+ " COMMENT='" + sqlLiteral(config.getTargetTableComment()) + "'");
|
||||
} catch (Exception e) {
|
||||
// Comments are auxiliary; table integrity is the important operation.
|
||||
log.debug("金蝶同步表注释未写入: configId={}", config.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private String sqlLiteral(String value) { return value.replace("\\", "\\\\").replace("'", "''"); }
|
||||
private String identifier(String value) {
|
||||
if (value == null || !IDENTIFIER.matcher(value).matches()) throw new BadRequestException("动态标识符不安全");
|
||||
return value;
|
||||
}
|
||||
private String quote(String value) { return "`" + value + "`"; }
|
||||
|
||||
@FunctionalInterface
|
||||
interface DdlOperation<T> {
|
||||
T execute() throws SQLException;
|
||||
}
|
||||
|
||||
private Map<String, Object> runMap(SysKingdeeSyncRun run) {
|
||||
Map<String, Object> result = new LinkedHashMap<>(); result.put("id", run.getId()); result.put("configId", run.getConfigId());
|
||||
result.put("status", run.getStatus()); result.put("filterString", run.getFilterString());
|
||||
result.put("fetchedCount", run.getFetchedCount()); result.put("insertedCount", run.getInsertedCount());
|
||||
result.put("updatedCount", run.getUpdatedCount()); result.put("failedCount", run.getFailedCount());
|
||||
result.put("errorMessage", run.getErrorMessage()); result.put("startedAt", run.getStartedAt()); result.put("finishedAt", run.getFinishedAt());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class ColumnInfo {
|
||||
private final int jdbcType; private final String typeName; private final int nullability;
|
||||
private ColumnInfo(int jdbcType, String typeName, int nullability) {
|
||||
this.jdbcType = jdbcType; this.typeName = typeName; this.nullability = nullability;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.