diff --git a/README.md b/README.md index 5ded15d..59a71ad 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,29 @@ Before saving any `secret=true` value in `sys_integration_config`, configure `APP_INTEGRATION_ENCRYPTION_KEY` (preferably a randomly generated 32-byte or longer secret) in the backend runtime environment. Do not commit the key or place a real value in `src/main/resources/application.yml`. + +For rollout and operations of asynchronous Feishu directory synchronization, +see [`../docs/feishu-directory-sync.md`](../docs/feishu-directory-sync.md). + +## Database contract + +[`../database/init_schema.sql`](../database/init_schema.sql) is the only schema +and bootstrap source. Run it with a MySQL 5.7 client only when +`finance_system` does not yet exist. It intentionally fails against an existing +or partial installation. The application keeps Hibernate `ddl-auto: validate` +and never changes the application-owned schema during startup. The optional, +explicitly authorized Kingdee table-preparation feature can create or alter only +its configured target tables; use a narrowly scoped DDL account for that action +or have a DBA pre-create those tables and keep the runtime account DML-only. +Existing installations require a separately reviewed DBA release script and +procedure for every in-place upgrade; never run the clean-install script against +them. + +The sole script intentionally seeds exactly one environment-specific Feishu +identity and binds it to the built-in `SUPER_ADMIN_GROUP`. Treat the script as an +access-controlled deployment asset, verify that the identity is the intended +operator, and edit it before installing another tenant. The seed has no local +password, mobile, email, or avatar URL; it receives `SUPER_ADMIN` only through +group membership, while `DEFAULT_EMPLOYEE` has no materialized member. Default +passwords, local-profile bootstrap, and first-user auto-promotion remain +prohibited. diff --git a/pom.xml b/pom.xml index 5e5140a..eaf8e51 100644 --- a/pom.xml +++ b/pom.xml @@ -50,19 +50,10 @@ - org.postgresql - postgresql + com.mysql + mysql-connector-j runtime - - com.h2database - h2 - runtime - - - org.flywaydb - flyway-core - @@ -121,17 +112,6 @@ jackson-datatype-jsr310 - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - diff --git a/src/main/java/com/finance/system/FinanceSystemApplication.java b/src/main/java/com/finance/system/FinanceSystemApplication.java index 30795e6..9110f53 100644 --- a/src/main/java/com/finance/system/FinanceSystemApplication.java +++ b/src/main/java/com/finance/system/FinanceSystemApplication.java @@ -3,12 +3,14 @@ package com.finance.system; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableConfigurationProperties +@EnableScheduling public class FinanceSystemApplication { public static void main(String[] args) { SpringApplication.run(FinanceSystemApplication.class, args); } -} \ No newline at end of file +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalEventStateService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalEventStateService.java new file mode 100644 index 0000000..58468fd --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalEventStateService.java @@ -0,0 +1,153 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.*; +import com.finance.system.enums.*; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.*; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.*; + +@Service +@RequiredArgsConstructor +public class FeishuApprovalEventStateService { + private final IntFeishuApprovalRepository approvals; + private final ReimApplicationRepository applications; + private final FeishuInstanceTimelineNodeRepository timeline; + private final IntFeishuApprovalAttemptRepository attempts; + + @Transactional + public void applyInstanceStatus(String instanceCode, String status, LocalDateTime eventTime) { + String normalized = normalizeApprovalStatus(status); + if (normalized == null) throw retryable("飞书审批状态无效"); + LocalDateTime trustedTime = eventTime == null ? LocalDateTime.now() : eventTime; + IntFeishuApproval candidate = approvals.findByFeishuInstanceCode(instanceCode).orElse(null); + if (candidate == null) { + applyHistoricalStatus(instanceCode, normalized, trustedTime); + return; + } + // Global lock order: application first, then current mapping. + ReimApplication app = applications.findByIdForUpdate(candidate.getApplicationId()) + .orElseThrow(() -> retryable("报销申请尚未就绪")); + IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(candidate.getApplicationId()) + .orElseThrow(() -> retryable("飞书审批映射尚未就绪")); + if (!Objects.equals(instanceCode, mapping.getFeishuInstanceCode())) { + applyHistoricalStatus(instanceCode, normalized, trustedTime); + return; + } + if ("CREATING".equals(mapping.getStatus()) || "CREATED".equals(mapping.getStatus()) + || "CREATE_OUTCOME_UNKNOWN".equals(mapping.getStatus())) { + if (isTerminal(mapping.getDeferredStatus()) && ApprovalStatus.PENDING.name().equals(normalized)) return; + if (mapping.getDeferredEventAt() == null || !trustedTime.isBefore(mapping.getDeferredEventAt())) { + mapping.setDeferredStatus(normalized); mapping.setDeferredEventAt(trustedTime); + mapping.setSyncedAt(LocalDateTime.now()); approvals.save(mapping); + } + return; + } + if (mapping.getEventUpdatedAt() != null && trustedTime.isBefore(mapping.getEventUpdatedAt())) return; + String previous = normalizeApprovalStatus(mapping.getStatus()); + if (isTerminal(previous) && ApprovalStatus.PENDING.name().equals(normalized)) return; + mapping.setStatus(normalized); mapping.setSyncedAt(LocalDateTime.now()); mapping.setEventUpdatedAt(trustedTime); + approvals.save(mapping); + app.setApprovalStatus(normalized); + if (ApprovalStatus.PENDING.name().equals(normalized)) { + app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode("飞书审批"); + app.setCurrentApproverId(null); app.setApproveTime(null); + } else { + app.setCurrentApproverId(null); app.setCurrentApprovalNode(null); + if (ApprovalStatus.APPROVED.name().equals(normalized)) { + app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setApproveTime(LocalDateTime.now()); + } else { + app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setApproveTime(null); + } + } + applications.save(app); + } + + @Transactional + public void applyTask(Map task) { + String instanceCode = bounded(text(task, "instance_code", "instanceCode"), 200); + if (!StringUtils.hasText(instanceCode)) throw retryable("飞书任务缺少实例标识"); + IntFeishuApproval candidate = approvals.findByFeishuInstanceCode(instanceCode).orElse(null); + Long approvalId; + if (candidate != null) { + applications.findByIdForUpdate(candidate.getApplicationId()) + .orElseThrow(() -> retryable("报销申请尚未就绪")); + IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(candidate.getApplicationId()) + .orElseThrow(() -> retryable("飞书审批映射尚未就绪")); + if (Objects.equals(instanceCode, mapping.getFeishuInstanceCode())) approvalId = mapping.getId(); + else approvalId = historicalApprovalId(instanceCode); + } else approvalId = historicalApprovalId(instanceCode); + String taskId = bounded(text(task, "task_id", "taskId", "id"), 300); + String nodeKey = bounded(text(task, "node_id", "nodeId", "node_key", "approval_node_id"), 300); + String key = StringUtils.hasText(taskId) ? "TASK:" + taskId : "ACTUAL:" + (nodeKey == null ? "unknown" : nodeKey); + key = bounded(key, 400); + FeishuInstanceTimelineNode row = timeline + .findByFeishuApprovalIdAndInstanceCodeAndTimelineKey(approvalId, instanceCode, key).orElse(null); + if (row == null && StringUtils.hasText(taskId)) row = timeline + .findByFeishuApprovalIdAndInstanceCodeAndTaskId(approvalId, instanceCode, taskId).orElse(null); + if (row == null && StringUtils.hasText(nodeKey)) { + FeishuInstanceTimelineNode planned = timeline + .findFirstByFeishuApprovalIdAndInstanceCodeAndNodeKeyOrderByIdAsc(approvalId, instanceCode, nodeKey) + .orElse(null); + if (planned != null && !StringUtils.hasText(planned.getTaskId())) row = planned; + } + LocalDateTime eventTime = parseTime(first(task, "action_time", "end_time", "update_time", "create_time")); + String incoming = normalizeTaskStatus(text(task, "status", "task_status", "taskStatus")); + if (row != null && row.getActionTime() != null && eventTime != null && eventTime.isBefore(row.getActionTime())) return; + if (row != null && isTerminalTask(row.getStatus()) && !isTerminalTask(incoming)) return; + LocalDateTime now = LocalDateTime.now(); + if (row == null) row = FeishuInstanceTimelineNode.builder().feishuApprovalId(approvalId) + .instanceCode(instanceCode).timelineKey(key).nodeKey(nodeKey).planned(false).createdAt(now).build(); + if (incoming != null) row.setStatus(incoming); + row.setTaskId(taskId); row.setPlanned(false); + String nodeName = bounded(text(task, "node_name", "nodeName", "name"), 300); + if (StringUtils.hasText(nodeName)) row.setNodeName(nodeName); + String approver = text(task, "approver_name", "user_name", "approver", "operator_name"); + Map user = map(task.get("user")); + if (!StringUtils.hasText(approver) && user != null) approver = text(user, "name", "en_name"); + if (StringUtils.hasText(approver)) row.setApproverLabel(bounded(approver, 300)); + String comment = text(task, "comment", "opinion", "reason"); + if (comment != null) row.setComment(bounded(comment, 2000)); + if (eventTime != null) row.setActionTime(eventTime); + row.setUpdatedAt(now); timeline.save(row); + } + + private void applyHistoricalStatus(String instanceCode, String normalized, LocalDateTime eventTime) { + IntFeishuApprovalAttempt known = attempts.findByInstanceCode(instanceCode) + .orElseThrow(() -> retryable("飞书审批映射尚未就绪")); + applications.findByIdForUpdate(known.getApplicationId()) + .orElseThrow(() -> retryable("报销申请尚未就绪")); + IntFeishuApprovalAttempt attempt = attempts.findByInstanceCodeForUpdate(instanceCode) + .orElseThrow(() -> retryable("飞书历史审批映射尚未就绪")); + if (attempt.getEventUpdatedAt() != null && eventTime.isBefore(attempt.getEventUpdatedAt())) return; + String previous = normalizeApprovalStatus(attempt.getStatus()); + if (isTerminal(previous) && ApprovalStatus.PENDING.name().equals(normalized)) return; + attempt.setStatus(normalized); attempt.setEventUpdatedAt(eventTime); attempt.setUpdatedAt(LocalDateTime.now()); + attempts.save(attempt); + } + + private Long historicalApprovalId(String instanceCode) { + IntFeishuApprovalAttempt known = attempts.findByInstanceCode(instanceCode) + .orElseThrow(() -> retryable("飞书审批映射尚未就绪")); + applications.findByIdForUpdate(known.getApplicationId()) + .orElseThrow(() -> retryable("报销申请尚未就绪")); + return attempts.findByInstanceCodeForUpdate(instanceCode) + .orElseThrow(() -> retryable("飞书历史审批映射尚未就绪")).getFeishuApprovalId(); + } + + private Object first(Map map, String... keys) { for (String k:keys) if(map.get(k)!=null)return map.get(k); return null; } + private String text(Map map,String...keys){Object v=first(map,keys);return v==null?null:String.valueOf(v);} + @SuppressWarnings("unchecked") private Map map(Object v){return v instanceof Map?(Map)v:null;} + private String bounded(String v,int max){return v==null?null:v.substring(0,Math.min(max,v.length()));} + private String normalizeTaskStatus(String s){if(!StringUtils.hasText(s))return null;String v=s.trim().toUpperCase(Locale.ROOT);if("CANCELED".equals(v))v="CANCELLED";if("DONE".equals(v)||"COMPLETED".equals(v)||"PASS".equals(v))v="APPROVED";return v.length()<=50?v:null;} + private String normalizeApprovalStatus(String s){if(!StringUtils.hasText(s))return null;String v=s.trim().toUpperCase(Locale.ROOT);if("CANCELED".equals(v))v="CANCELLED";for(ApprovalStatus x:ApprovalStatus.values())if(x.name().equals(v))return v;return null;} + private boolean isTerminal(String s){return "APPROVED".equals(s)||"REJECTED".equals(s)||"CANCELLED".equals(s);} + private boolean isTerminalTask(String s){return "APPROVED".equals(s)||"REJECTED".equals(s)||"CANCELLED".equals(s)||"TRANSFERRED".equals(s);} + private LocalDateTime parseTime(Object v){if(v==null)return null;try{String s=String.valueOf(v);if(s.matches("\\d+")){long e=Long.parseLong(s);if(e>100000000000L)e/=1000;return LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(e),java.time.ZoneOffset.UTC);}return LocalDateTime.parse(s);}catch(Exception e){return null;}} + private BusinessException retryable(String message){return new BusinessException(message,503);} +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java index b4b0926..ddbb872 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java @@ -7,7 +7,7 @@ import com.finance.system.entity.SysDepartment; import com.finance.system.entity.SysExpenseType; import java.math.BigDecimal; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -24,7 +24,7 @@ public class FeishuApprovalFormBuilder { public static Map buildForm(ReimApplication app, SysUser applicant, SysDepartment department, SysExpenseType expenseType, List items) { - Map form = new HashMap<>(); + Map form = new LinkedHashMap<>(); // 基本字段 form.put("application_no", app.getApplicationNo()); @@ -38,7 +38,7 @@ public class FeishuApprovalFormBuilder { // 费用明细(多行文本展示) if (items != null && !items.isEmpty()) { - String itemDetail = items.stream() + String itemDetail = ReimbursementCanonicalizer.orderedItems(items).stream() .map(item -> String.format("%s | %s | ¥%.2f", item.getExpenseDate() != null ? item.getExpenseDate().toString() : "", item.getDescription() != null ? item.getDescription() : "", @@ -79,4 +79,4 @@ public class FeishuApprovalFormBuilder { .replace("\r", "\\r") .replace("\t", "\\t"); } -} \ No newline at end of file +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java index 1b4331d..c219de1 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java @@ -1,9 +1,13 @@ package com.finance.system.adapter.feishu; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.type.TypeReference; import com.finance.system.entity.*; import com.finance.system.enums.ApplicationStatus; import com.finance.system.enums.ApprovalStatus; import com.finance.system.exception.BusinessException; +import com.finance.system.exception.FeishuCreateOutcomeUnknownException; import com.finance.system.repository.*; import com.finance.system.service.IntegrationConfigReader; import lombok.RequiredArgsConstructor; @@ -13,6 +17,7 @@ import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; +import org.springframework.web.client.RestClientResponseException; import org.springframework.util.StringUtils; import java.nio.charset.StandardCharsets; @@ -27,6 +32,7 @@ import java.util.*; @Service @RequiredArgsConstructor public class FeishuApprovalService { + private static final ObjectMapper JSON = new ObjectMapper(); private final FeishuConfig feishuConfig; private final FeishuAuthService feishuAuthService; @@ -38,12 +44,24 @@ public class FeishuApprovalService { private final ReimApplicationRepository reimApplicationRepository; private final RestTemplate restTemplate; private IntegrationConfigReader integrationConfigReader; + private FeishuInstanceTimelineNodeRepository timelineNodeRepository; + private FeishuApprovalEventStateService eventStateService; @Autowired(required = false) public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) { this.integrationConfigReader = integrationConfigReader; } + @Autowired(required = false) + public void setTimelineNodeRepository(FeishuInstanceTimelineNodeRepository timelineNodeRepository) { + this.timelineNodeRepository = timelineNodeRepository; + } + + @Autowired(required = false) + public void setEventStateService(FeishuApprovalEventStateService eventStateService) { + this.eventStateService = eventStateService; + } + private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis"; /** @@ -94,6 +112,34 @@ public class FeishuApprovalService { } } + /** Raw transport response for server-side normalization only. Never expose this from a controller. */ + public JsonNode fetchApprovalDefinitionJson() { + String token = feishuAuthService.getTenantAccessToken(); + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(token); + headers.setContentType(MediaType.APPLICATION_JSON); + Map body = Collections.singletonMap("approval_code", approvalCode()); + try { + ResponseEntity response = restTemplate.exchange( + FEISHU_OPEN_API + "/approval/openapi/v2/approval/get", HttpMethod.POST, + new HttpEntity<>(body, headers), JsonNode.class); + JsonNode value = response.getBody(); + if (value == null || value.path("code").asInt(-1) != 0) { + throw new BusinessException("飞书审批定义同步失败", 502); + } + return value; + } catch (BusinessException e) { + throw e; + } catch (Exception e) { + log.warn("飞书审批定义请求失败: {}", e.getClass().getSimpleName()); + throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502); + } + } + + public String getConfiguredApprovalCode() { + return approvalCode(); + } + /** * 获取审批节点列表(用于前端展示审批流程) */ @@ -107,110 +153,78 @@ public class FeishuApprovalService { // ==================== 2. 创建审批实例 ==================== - /** - * 创建飞书审批实例 - * - * @param application 报销申请 - * @return 飞书审批实例编码 - */ - @Transactional - public String createApprovalInstance(ReimApplication application) { - if (application == null || application.getId() == null) { - throw new BusinessException("报销申请不存在,无法创建飞书审批", 400); - } - Optional existing = intFeishuApprovalRepository - .findByApplicationId(application.getId()); - IntFeishuApproval reusableRecord = existing.orElse(null); - if (existing.isPresent()) { - String existingStatus = normalizeApprovalStatus(existing.get().getStatus()); - if (!isRetryableTerminal(existingStatus) && StringUtils.hasText(existing.get().getFeishuInstanceCode())) { - log.info("飞书审批实例已存在,跳过重复创建: applicationNo={}, instanceCode={}", - application.getApplicationNo(), existing.get().getFeishuInstanceCode()); - return existing.get().getFeishuInstanceCode(); - } - if (!isRetryableTerminal(existingStatus)) { - throw new BusinessException("该申请已有未完成的飞书同步记录,请稍后重试"); - } - } + /** Performs only the remote create. The durable CREATING intent is managed by the coordinator. */ + public String createApprovalInstanceRemote(Long applicationId, String requestUuid, String intendedApprovalCode) { + if (applicationId == null || !StringUtils.hasText(requestUuid) || !StringUtils.hasText(intendedApprovalCode)) + throw new BusinessException("飞书审批创建参数无效", 400); + return createApprovalInstanceRemote(buildCreatePayload(applicationId, requestUuid, intendedApprovalCode), requestUuid); + } - if (application.getApplicantId() == null) { - throw new BusinessException("申请人不存在,无法创建飞书审批", 400); - } - SysUser applicant = sysUserRepository.findById(application.getApplicantId()) - .orElseThrow(() -> new BusinessException("申请人不存在,无法创建飞书审批", 400)); - if (!StringUtils.hasText(applicant.getFeishuUserId()) - && !StringUtils.hasText(applicant.getFeishuOpenId())) { + /** Built in Phase A while the application row is locked, then persisted verbatim. */ + public String buildCreatePayload(Long applicationId, String requestUuid, String intendedApprovalCode) { + ReimApplication application = reimApplicationRepository.findById(applicationId) + .orElseThrow(() -> new BusinessException("报销申请不存在,无法创建飞书审批", 400)); + SysUser applicant = application.getApplicantId() == null ? null + : sysUserRepository.findById(application.getApplicantId()).orElse(null); + if (applicant == null || (!StringUtils.hasText(applicant.getFeishuUserId()) + && !StringUtils.hasText(applicant.getFeishuOpenId()))) throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 400); - } - - String token = feishuAuthService.getTenantAccessToken(); - String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/create"; - - // 获取关联数据 - SysDepartment department = application.getDepartmentId() != null - ? sysDepartmentRepository.findById(application.getDepartmentId()).orElse(null) : null; - SysExpenseType expenseType = application.getExpenseTypeId() != null - ? sysExpenseTypeRepository.findById(application.getExpenseTypeId()).orElse(null) : null; - List items = reimExpenseItemRepository.findByApplicationId(application.getId()); - - // 构建表单数据 - Map formData = FeishuApprovalFormBuilder.buildForm( - application, applicant, department, expenseType, items); - String formJson = FeishuApprovalFormBuilder.buildFormJson(formData); - - // 构建请求体 - Map requestBody = new HashMap<>(); - requestBody.put("approval_code", approvalCode()); - requestBody.put("user_id", applicant != null ? applicant.getFeishuUserId() : ""); - requestBody.put("open_id", applicant != null ? applicant.getFeishuOpenId() : ""); - requestBody.put("form", formJson); - String requestId = createRequestId(application, reusableRecord); - requestBody.put("uuid", requestId); - - HttpHeaders headers = new HttpHeaders(); - headers.setBearerAuth(token); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.set("X-Request-ID", requestId); - - HttpEntity> 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 items = reimExpenseItemRepository.findByApplicationId(applicationId); + String formJson = FeishuApprovalFormBuilder.buildFormJson( + FeishuApprovalFormBuilder.buildForm(application, applicant, department, expenseType, items)); + Map 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 body; + try { body = JSON.readValue(persistedPayload, new TypeReference>() {}); } + 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 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 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 eventData) { - @SuppressWarnings("unchecked") - Map task = (Map) eventData.get("task"); + Map 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 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 map, String... keys) { + for (String key : keys) if (map.get(key) != null) return map.get(key); + return null; + } + + private String text(Map 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 nestedMap(Object value) { return value instanceof Map ? (Map) 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); - } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java index cde8a1e..bb4639e 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java @@ -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 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; diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionGenerationService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionGenerationService.java new file mode 100644 index 0000000..677c7ab --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionGenerationService.java @@ -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; + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java new file mode 100644 index 0000000..dcd8a1f --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java @@ -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 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 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 normalizeApprovers(JsonNode node) { + JsonNode values = first(node, "approvers", "approver", "approver_list", "approverList", "assignees"); + List result = new ArrayList<>(); + if (values == null) return result; + Iterable 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 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 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 approvers; + } + @Data @AllArgsConstructor + public static class NormalizedApprover { + private String type; private String ref; private String label; private boolean dynamic; + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java new file mode 100644 index 0000000..7c93b99 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java @@ -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 oldNodes = nodes + .findBySnapshotIdOrderByNodeOrderAsc(FeishuApprovalDefinitionSnapshot.CURRENT_ID); + List 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(); + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java new file mode 100644 index 0000000..38f36be --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java @@ -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); + } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java index 887d635..09eb601 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java @@ -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 state=com.finance.system.service.FeishuDirectoryLock.acquire(jdbc); + java.util.List> rows=authorizationRows(user.getId()); + if(rows.size()!=1)return false; + Map 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 state=com.finance.system.service.FeishuDirectoryLock.acquire(jdbc); + java.util.List> 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 userIds) { + if (jdbc == null) return null; try { - Map 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 state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1"); + Map> usersById=new LinkedHashMap<>(); + List 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;i0)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 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 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> 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 state,Map 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.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 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 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> rows = jdbc.queryForList(sql.toString(), args.toArray()); + Map> departments = currentDepartments(rows); + Map candidates = new LinkedHashMap<>(); + for (Map 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.emptyList()), + booleanValue(row.get("eligible")), nullableLong(row.get("assigned_group_id")), + generation, openId, userId, nullable(row.get("local_status")), conflict)); + } + Map 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 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> currentDepartments(List> users) { + Set openIds = new LinkedHashSet<>(); + for (Map 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 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> result = new LinkedHashMap<>(); + for (Map 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 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 before, Map 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 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 candidates) { + this(snapshotState, candidates, null, null, null, false); + } + private CandidateSearch(String snapshotState, List 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 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.emptyList(), null, false); + } + private static CandidateSearch empty(String state) { return new CandidateSearch(state, Collections.emptyList()); } + private static CandidateSearch unavailable() { return empty("UNAVAILABLE"); } + public static CandidateSearch of(String state, List candidates) { + return new CandidateSearch(state, candidates == null + ? Collections.emptyList() : candidates); + } + public static CandidateSearch of(String state, List candidates, + boolean blockedMatchesPresent) { + return new CandidateSearch(state, candidates == null + ? Collections.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 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 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 departmentNames, boolean eligible) { + this(localUserId, name, employeeNo, departmentNames, eligible, null); + } + public DirectoryCandidate(Long localUserId, String name, String employeeNo, + List 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 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 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 state; + private final Map> usersById; + private DirectoryObservation(Map state,Map> usersById){ + this.state=state;this.usersById=usersById; + } } private static boolean blank(String value) { return value == null || value.trim().isEmpty(); } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java new file mode 100644 index 0000000..030da4c --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java @@ -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 resolveForExplicitBinding(Collection identities) { + if (identities == null || identities.isEmpty()) return Collections.emptyList(); + try { + Map state = FeishuDirectoryLock.acquire(jdbc); + FeishuDirectoryPublication publication = FeishuDirectoryPublication.classify(state, time); + if (!publication.isAvailable()) throw conflict(); + String generation = publication.getRevision(); + String context = publication.getSuccessfulContext(); + LinkedHashSet 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> 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 directory = directoryRows.get(0); + + List> accountRows = jdbc.queryForList( + "SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user " + + "WHERE feishu_open_id=? FOR UPDATE", identity.getOpenId()); + Map openOwner = null; + for (Map 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 legacyIds=new LinkedHashSet<>(); + if(!blank(legacyRow))legacyIds.add(legacyRow); + if(!blank(legacyRequest))legacyIds.add(legacyRequest); + for(String legacyId:legacyIds){ + List> owners=jdbc.queryForList( + "SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user WHERE feishu_user_id=? FOR UPDATE", + legacyId); + for(Map 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 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); + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java index f78c63c..841322f 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java @@ -1,809 +1,386 @@ package com.finance.system.adapter.feishu; import com.fasterxml.jackson.databind.JsonNode; -import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; -import lombok.extern.slf4j.Slf4j; + +import javax.annotation.PreDestroy; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; import java.util.concurrent.locks.LockSupport; -/** Contact v3 only. No caller-controlled host, URL or identifier type. */ +/** Strict Directory-v1 bulk reader. Remote JSON is normalized before leaving this adapter. */ @Component @Slf4j public class FeishuDirectoryClient { - private static final BigInteger SUCCESS_CODE = BigInteger.ZERO; + static final String DEPARTMENTS_PATH = "/directory/v1/departments/filter"; + static final String EMPLOYEES_PATH = "/directory/v1/employees/filter"; + static final List DEPARTMENT_FIELDS = Collections.unmodifiableList(Arrays.asList( + "department_id", "name", "parent_department_id", "order_weight", "department_count")); + static final List EMPLOYEE_FIELDS = Collections.unmodifiableList(Arrays.asList( + "base_info.employee_id", "base_info.name", "base_info.mobile", "base_info.email", + "base_info.departments.department_id", "base_info.avatar", + "work_info.job_number", "work_info.job_title.job_title_name")); private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L); - private static final BigInteger DEFINITIVE_CODE_41012 = BigInteger.valueOf(41012L); - private static final BigInteger DEFINITIVE_CODE_41050 = BigInteger.valueOf(41050L); private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); - private static final String DEPARTMENT_STATUS_INVALID = "DIRECTORY_DEPARTMENT_STATUS_INVALID"; - private static final String IDENTITY_INVALID = "DIRECTORY_IDENTITY_INVALID"; - private static final String LIMIT_EXCEEDED = "DIRECTORY_LIMIT_EXCEEDED"; + private static final ObjectMapper JSON = new ObjectMapper(); - private enum PageKind { - DEPARTMENT("DIRECTORY_DEPARTMENT_PAGE_INVALID", "DIRECTORY_DEPARTMENT_ITEM_INVALID", - "DIRECTORY_DEPARTMENT_PAGE_TOKEN_INVALID", "DIRECTORY_DEPARTMENT_ITEMS_INVALID", - "DIRECTORY_DEPARTMENT_HAS_MORE_INVALID"), - USER("DIRECTORY_USER_PAGE_INVALID", "DIRECTORY_USER_ITEM_INVALID", - "DIRECTORY_USER_PAGE_TOKEN_INVALID", "DIRECTORY_USER_ITEMS_INVALID", - "DIRECTORY_USER_HAS_MORE_INVALID"); - - private final String pageInvalid; - private final String itemInvalid; - private final String pageTokenInvalid; - private final String itemsInvalid; - private final String hasMoreInvalid; - - PageKind(String pageInvalid, String itemInvalid, String pageTokenInvalid) { - this(pageInvalid, itemInvalid, pageTokenInvalid, pageInvalid, pageInvalid); - } - - PageKind(String pageInvalid, String itemInvalid, String pageTokenInvalid, - String itemsInvalid, String hasMoreInvalid) { - this.pageInvalid = pageInvalid; - this.itemInvalid = itemInvalid; - this.pageTokenInvalid = pageTokenInvalid; - this.itemsInvalid = itemsInvalid; - this.hasMoreInvalid = hasMoreInvalid; - } + private enum Kind { + DEPARTMENT("departments", "DIRECTORY_DEPARTMENT"), EMPLOYEE("employees", "DIRECTORY_USER"); + final String array; final String diagnostic; + Kind(String array, String diagnostic) { this.array=array; this.diagnostic=diagnostic; } } private final FeishuTenantTokenService tokens; private final FeishuDirectorySettings settings; private final RestTemplate http; private final RateGate rateGate; - // A hard wall-clock deadline also covers slow/trickling HTTP bodies. No unbounded work queue. - private final ExecutorService workers = new ThreadPoolExecutor(0, 2, 30, - TimeUnit.SECONDS, new SynchronousQueue<>(), task -> { - Thread thread = new Thread(task, "feishu-directory-http"); thread.setDaemon(true); return thread; - }); - // Department and user pages are fetched in bounded batches. The queue is - // bounded as well so concurrent snapshots cannot turn a large department - // tree into thousands of pending tasks. - private final ExecutorService directoryWorkers; + private final ExecutorService worker = Executors.newSingleThreadExecutor(task -> { + Thread thread=new Thread(task,"feishu-directory-http"); thread.setDaemon(true); return thread; + }); + @Autowired public FeishuDirectoryClient(FeishuTenantTokenService tokens, FeishuDirectorySettings settings) { this(tokens, settings, httpClient()); } FeishuDirectoryClient(FeishuTenantTokenService tokens, FeishuDirectorySettings settings, RestTemplate http) { - this.tokens = tokens; this.settings = settings; this.http = http; - this.rateGate = new RateGate(settings); - int concurrency = settings.getDirectoryConcurrency(); - this.directoryWorkers = new ThreadPoolExecutor(concurrency, concurrency, 0L, TimeUnit.MILLISECONDS, - new ArrayBlockingQueue<>(concurrency), task -> { - Thread thread = new Thread(task, "feishu-directory-user-http"); thread.setDaemon(true); return thread; - }); - } - @javax.annotation.PreDestroy - public void close() { - shutdownGracefully(workers); - shutdownGracefully(directoryWorkers); - } - private static void shutdownGracefully(ExecutorService executor) { - executor.shutdown(); - try { - if (!executor.awaitTermination(1, TimeUnit.SECONDS)) executor.shutdownNow(); - } catch (InterruptedException e) { - executor.shutdownNow(); Thread.currentThread().interrupt(); - } + this.tokens=tokens; this.settings=settings; this.http=http; this.rateGate=new RateGate(); } private static RestTemplate httpClient() { - SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); f.setConnectTimeout(3000); f.setReadTimeout(5000); - return new RestTemplate(f); + SimpleClientHttpRequestFactory f=new SimpleClientHttpRequestFactory(); + f.setConnectTimeout(3000); f.setReadTimeout(5000); return new RestTemplate(f); } + @PreDestroy public void close() { worker.shutdownNow(); } + public Snapshot fetch(FeishuTenantTokenService.Context context) { - final Budget budget = new Budget(); - return bounded(() -> fetchSnapshot(context, budget), settings.elapsed()); + Budget budget=new Budget(); + return bounded(() -> fetchAll(context,budget), settings.elapsed()); } - private Snapshot fetchSnapshot(FeishuTenantTokenService.Context context, Budget budget) { - budget.check(); - String token = tokens.token(context); - budget.check(); - Snapshot snapshot = new Snapshot(); - snapshot.departments.add("0"); - snapshot.departmentDetails.put("0", Department.root()); - discoverDepartments(snapshot, token, budget); - fetchUsers(snapshot, token, budget); + private Snapshot fetchAll(FeishuTenantTokenService.Context context, Budget budget) { + budget.check(); String token=tokens.token(context); budget.check(); + Snapshot snapshot=new Snapshot(); + snapshot.departments.add("0"); snapshot.departmentDetails.put("0",Department.root()); + + // Directory-v1 cursors are sequential. The entire graph is completed and + // validated before the first employee request is allowed to start. + Deque parents=new ArrayDeque<>(); + Set scheduledParents=new HashSet<>(), completedParents=new HashSet<>(); + parents.addLast("0"); scheduledParents.add("0"); + while(!parents.isEmpty()) { + budget.check(); + String parent=parents.removeFirst(); + if(!completedParents.add(parent)) fail("DIRECTORY_DEPARTMENT_GRAPH_INVALID"); + pages(DEPARTMENTS_PATH,Kind.DEPARTMENT,DEPARTMENT_FIELDS,departmentConditions(parent),token,budget,item -> { + String id=mergeDepartment(snapshot,item); + if(scheduledParents.add(id)) parents.addLast(id); + }); + } + validateGraph(snapshot); + for(int staffStatus=1;staffStatus<=5;staffStatus++) + pages(EMPLOYEES_PATH,Kind.EMPLOYEE,EMPLOYEE_FIELDS,employeeConditions(staffStatus),token,budget, + item -> mergeEmployee(snapshot,item)); budget.check(); return snapshot; } - private void discoverDepartments(Snapshot snapshot, String token, Budget budget) { - ArrayDeque pending = new ArrayDeque<>(); - pending.add("0"); - int concurrency = settings.getDirectoryConcurrency(); - while (!pending.isEmpty()) { - int end = Math.min(concurrency, pending.size()); - List wave = new ArrayList<>(end); - for (int i = 0; i < end; i++) wave.add(pending.remove()); - List> outstanding = new ArrayList<>(end); - Map> completed = new HashMap<>(); - try { - BlockingQueue> completionQueue = new ArrayBlockingQueue<>(end); - CompletionService completion = - new ExecutorCompletionService<>(directoryWorkers, completionQueue); - for (int i = 0; i < wave.size(); i++) { - final int departmentIndex = i; - final String department = wave.get(i); - outstanding.add(completion.submit(() -> new DepartmentFetchResult(departmentIndex, - fetchDepartmentChildren(department, token, budget)))); - } - // A completed result is retained only for this bounded wave. All - // directory mutations happen here, in discovery order. - for (int completedCount = 0; completedCount < wave.size(); completedCount++) { - Future future = completion.take(); - outstanding.remove(future); - DepartmentFetchResult result; - try { result = future.get(); } - catch (ExecutionException e) { throw workerFailure(e.getCause()); } - catch (CancellationException e) { - throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED"); - } - completed.put(result.departmentIndex, result.children); - } - for (int i = 0; i < wave.size(); i++) - mergeDepartments(snapshot, pending, wave.get(i), completed.get(i)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED"); - } catch (RejectedExecutionException e) { - throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_UNAVAILABLE"); - } finally { - cancelOutstanding(outstanding); - } - } - } - private List fetchDepartmentChildren(String department, String token, Budget budget) { - List children = new ArrayList<>(); - pages("/contact/v3/departments/" + segment(department) + "/children", null, - PageKind.DEPARTMENT, token, budget, children::add); - return children; - } - private void mergeDepartments(Snapshot snapshot, ArrayDeque pending, String parent, - List children) { - for (JsonNode node : children) { - JsonNode status = node.path("status"); - if (!status.isObject() || !status.path("is_deleted").isBoolean()) - throw FeishuTenantTokenService.diagnostic(DEPARTMENT_STATUS_INVALID); - // Deleted departments are a normal part of a directory response. Do not - // enqueue them, but keep failing closed for a malformed status object. - if (status.path("is_deleted").booleanValue()) continue; - // Default traversal must use the open identifier returned by the - // official endpoint. A legacy/custom field must not silently be - // used for the next request. - // The snapshot contract is always open-id based. Even if an - // installation requests a legacy department_id query mode, never - // reinterpret that custom identifier as open_department_id. - String child = requiredDepartmentIdentity(node, "open_department_id"); - if (snapshot.departments.add(child)) { - pending.add(child); - snapshot.departmentDetails.put(child, Department.from(node, child, parent)); - } - if (snapshot.departments.size() > Math.min(5000, settings.getMaxDepartments())) - throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED); - } - } - private void fetchUsers(Snapshot snapshot, String token, Budget budget) { - List departmentIds = new ArrayList<>(snapshot.departments); - int concurrency = settings.getDirectoryConcurrency(); - for (int offset = 0; offset < departmentIds.size(); offset += concurrency) { - List> outstanding = new ArrayList<>(concurrency); - Map> completed = new HashMap<>(); - int end = Math.min(departmentIds.size(), offset + concurrency); - try { - BlockingQueue> completionQueue = new ArrayBlockingQueue<>(concurrency); - CompletionService completion = new ExecutorCompletionService<>(directoryWorkers, completionQueue); - for (int i = offset; i < end; i++) { - final int departmentIndex = i; - final String department = departmentIds.get(i); - outstanding.add(completion.submit(() -> new UserFetchResult(departmentIndex, - fetchDepartmentUsers(department, token, budget)))); - } - // Observe completion order so a failed worker is propagated - // immediately, but retain results only for this bounded window. - for (int completedCount = 0; completedCount < end - offset; completedCount++) { - Future future = completion.take(); - outstanding.remove(future); - UserFetchResult result; - try { result = future.get(); } - catch (ExecutionException e) { throw workerFailure(e.getCause()); } - catch (CancellationException e) { - throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED"); - } - completed.put(result.departmentIndex, result.users); - } - // Merge on this caller/collector thread in department discovery - // order, never in completion order. - for (int i = offset; i < end; i++) - mergeUsers(snapshot, departmentIds.get(i), completed.get(i)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED"); - } catch (RejectedExecutionException e) { - throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_UNAVAILABLE"); - } finally { - cancelOutstanding(outstanding); - } - } - } - private List fetchDepartmentUsers(String department, String token, Budget budget) { - List users = new ArrayList<>(); - Set identities = new HashSet<>(); - pages("/contact/v3/users/find_by_department", department, PageKind.USER, token, budget, node -> { - String open = requiredIdentity(node, "open_id"); - requiredIdentity(node, "user_id"); - users.add(node); - if (identities.add(open) - && identities.size() > Math.min(50000, settings.getMaxUsers())) - throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED); - }); - return users; - } - private void mergeUsers(Snapshot snapshot, String department, List users) { - for (JsonNode node : users) { - String open = requiredIdentity(node, "open_id"); - String userId = requiredIdentity(node, "user_id"); - JsonNode previous = snapshot.users.putIfAbsent(open, node); - if (previous != null && (!requiredIdentity(previous, "user_id").equals(userId) - || eligible(previous) != eligible(node))) - throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); - UserSummary summary = snapshot.userSummaries.get(open); - if (summary == null) { - summary = UserSummary.from(node, department); - summary.departmentIds.removeIf(id -> !snapshot.departments.contains(id)); - summary.addDepartment(department); - snapshot.userSummaries.put(open, summary); - } else { - summary.departmentIds.removeIf(id -> !snapshot.departments.contains(id)); - summary.merge(node, snapshot.departments); - summary.addDepartment(department); - } - if (snapshot.users.size() > Math.min(50000, settings.getMaxUsers())) - throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED); - } - } - private static final class UserFetchResult { - private final int departmentIndex; - private final List users; - - private UserFetchResult(int departmentIndex, List users) { - this.departmentIndex = departmentIndex; - this.users = users; - } - } - private static final class DepartmentFetchResult { - private final int departmentIndex; - private final List children; - - private DepartmentFetchResult(int departmentIndex, List children) { - this.departmentIndex = departmentIndex; - this.children = children; - } - } - private static FeishuTenantTokenService.DiagnosticFailure workerFailure(Throwable cause) { - if (cause instanceof FeishuTenantTokenService.DiagnosticFailure) - return (FeishuTenantTokenService.DiagnosticFailure) cause; - return FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED"); - } - private static void cancelOutstanding(List> futures) { - for (Future future : futures) if (!future.isDone()) future.cancel(true); - } - public JsonNode verify(String openId, FeishuTenantTokenService.Context context) { - final Budget budget = new Budget(); - return bounded(() -> verifyUser(openId, context, budget), Math.min(15, settings.elapsed())); - } - private JsonNode verifyUser(String openId, FeishuTenantTokenService.Context context, Budget budget) { - budget.check(); - String token = tokens.token(context); - budget.check(); - JsonNode data; - try { data = get(UriComponentsBuilder.fromHttpUrl(FeishuTenantTokenService.API + "/contact/v3/users/" + segment(openId)) - .queryParam("user_id_type", "open_id").queryParam("department_id_type", settings.departmentIdType()).build().encode().toUri(), token, budget, true); } - catch (DefinitiveDenial e) { return null; } - JsonNode user = data.path("user"); - if (!openId.equals(requiredIdentity(user, "open_id"))) - throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); - requiredIdentity(user, "user_id"); return user; - } - private void pages(String path, String department, PageKind kind, String token, Budget budget, Consumer accept) { - String page = null; Set seen = new HashSet<>(); - do { - UriComponentsBuilder uri = UriComponentsBuilder.fromHttpUrl(FeishuTenantTokenService.API + path) - .queryParam("department_id_type", settings.departmentIdType()) - .queryParam("user_id_type", "open_id").queryParam("page_size", 50); - if (department != null) uri.queryParam("department_id", department); - else uri.queryParam("fetch_child", false); - if (page != null) uri.queryParam("page_token", "{pageToken}"); - // Tokens are opaque: strict URI-variable encoding escapes '+' as %2B, - // '/' as %2F, '=' as %3D, and literal '%' exactly once. - java.net.URI target = page == null ? uri.build().encode().toUri() - : uri.encode().buildAndExpand(java.util.Collections.singletonMap("pageToken", page)).toUri(); - // Contact v3's pagination object is body.data, not the response body. - // Keep the operation kind here so a malformed envelope or page can be - // diagnosed without retaining or exposing Feishu response content. - JsonNode data = get(target, token, budget, false, kind); - if (!data.path("has_more").isBoolean()) - throw FeishuTenantTokenService.diagnostic(kind.hasMoreInvalid); - JsonNode items = data.path("items"); - // Feishu may omit items for an empty terminal page. Treat only that - // unambiguous case as an empty list; a missing list on a paginated - // response remains fail-closed because it could hide directory data. - if (!data.has("items") && !data.path("has_more").booleanValue()) { - items = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.arrayNode(); - } else if (!data.has("items")) { - log.warn("Feishu directory page shape invalid: kind={}, itemsType=MISSING", kind); - throw FeishuTenantTokenService.diagnostic(kind.itemsInvalid + "_MISSING"); - } - if (!items.isArray()) { - log.warn("Feishu directory page shape invalid: kind={}, itemsType={}", kind, items.getNodeType()); - throw FeishuTenantTokenService.diagnostic(kind.itemsInvalid + "_TYPE_INVALID"); - } - if (items.size() > 50) { - log.warn("Feishu directory page exceeds contract: kind={}, itemCount={}", kind, items.size()); - throw FeishuTenantTokenService.diagnostic(kind.itemsInvalid + "_PAGE_TOO_LARGE"); - } - // Contact v3 documents a maximum page size of 50 for both endpoints. - // Keep this separate from the aggregate snapshot limits below. - int maxItems = kind == PageKind.DEPARTMENT - ? Math.min(5000, settings.getMaxDepartments()) - : Math.min(50000, settings.getMaxUsers()); - if (items.size() > maxItems) - throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED); - for (JsonNode item : items) { - if (item == null || !item.isObject()) throw FeishuTenantTokenService.diagnostic(kind.itemInvalid); - accept.accept(item); - } - if (!data.path("has_more").booleanValue()) return; - page = requiredPageToken(data, kind); - if (!seen.add(page)) throw FeishuTenantTokenService.diagnostic(kind.pageTokenInvalid); - } while (true); - } - private JsonNode get(java.net.URI uri, String token, Budget budget, boolean live) { - return get(uri, token, budget, live, null); - } - private JsonNode get(java.net.URI uri, String token, Budget budget, boolean live, PageKind pageKind) { - int retries = 0; + private void pages(String path, Kind kind, List fields, List> conditions, + String token, Budget budget, + java.util.function.Consumer consumer) { + String cursor=null; Set seen=new HashSet<>(); while (true) { budget.page(); - HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(token); + Map body=requestBody(fields,conditions,cursor); + JsonNode data=post(path,body,token,budget,kind); + validateAbnormals(data,kind); + JsonNode items=data.get(kind.array); + if(items==null||!items.isArray()||items.size()>100) + fail(kind.diagnostic+"_ITEMS_INVALID"); + for(JsonNode item:items) { + if(item==null||!item.isObject()) fail(kind.diagnostic+"_ITEM_INVALID"); + consumer.accept(item); + } + JsonNode page=data.get("page_response"); + if(page==null||!page.isObject()||!page.has("has_more")||!page.get("has_more").isBoolean()) + fail(kind.diagnostic+"_PAGE_RESPONSE_INVALID"); + if(!page.get("has_more").booleanValue()) { + JsonNode terminal=page.get("page_token"); + if(terminal!=null&&!terminal.isNull()&&!terminal.isTextual()) fail(kind.diagnostic+"_PAGE_TOKEN_INVALID"); + return; + } + JsonNode next=page.get("page_token"); + if(!boundedText(next,4096)) fail(kind.diagnostic+"_PAGE_TOKEN_INVALID"); + cursor=next.textValue(); + if(!seen.add(cursor)) fail(kind.diagnostic+"_PAGE_TOKEN_INVALID"); + } + } + private static Map requestBody(List fields,List> conditions,String cursor) { + if(conditions==null||conditions.isEmpty()||conditions.size()>10) fail("DIRECTORY_FILTER_INVALID"); + Map filter=new LinkedHashMap<>(); filter.put("conditions",conditions); + Map page=new LinkedHashMap<>(); page.put("page_size",100); + if(cursor!=null) page.put("page_token",cursor); + Map body=new LinkedHashMap<>(); body.put("filter",filter); + body.put("required_fields",fields); body.put("page_request",page); return body; + } + private static List> departmentConditions(String parent) { + final String serialized; + try { serialized=JSON.writeValueAsString(parent); } + catch(Exception ex) { fail("DIRECTORY_FILTER_INVALID"); return Collections.emptyList(); } + return Collections.singletonList(condition("parent_department_id","eq",serialized)); + } + private static List> employeeConditions(int staffStatus) { + return Collections.singletonList(condition("work_info.staff_status","eq",Integer.toString(staffStatus))); + } + private static Map condition(String field,String operator,String value) { + Map condition=new LinkedHashMap<>(); condition.put("field",field); + condition.put("operator",operator); condition.put("value",value); return condition; + } + private JsonNode post(String path,Map body,String token,Budget budget,Kind kind) { + String url=FeishuTenantTokenService.API+path + +"?employee_id_type=open_id&department_id_type=open_department_id"; + int retries=0; + while(true) { + budget.request(); rateGate.acquire(budget); + HttpHeaders headers=new HttpHeaders(); headers.setBearerAuth(token); + headers.setContentType(new MediaType("application","json", StandardCharsets.UTF_8)); try { - rateGate.acquire(budget); - ResponseEntity response = http.exchange(uri, HttpMethod.GET, - new HttpEntity(headers), JsonNode.class); - JsonNode body = response.getBody(); - budget.check(); - if (live && definitive(body)) throw new DefinitiveDenial(); - if (isRateLimited(body, null)) throw new RateLimited(parseResetSeconds( - response.getHeaders().getFirst("x-ogw-ratelimit-reset"))); - BigInteger code = responseCode(body); - if (code == null || !SUCCESS_CODE.equals(code) || !body.path("data").isObject()) { - RemoteFailure failure = remoteFailure(body, null); - if (failure != null) throw failure; - throw FeishuTenantTokenService.diagnostic(pageKind == null - ? "DIRECTORY_RESPONSE_INVALID" : pageKind.pageInvalid); + ResponseEntity response=http.exchange(url,HttpMethod.POST,new HttpEntity<>(body,headers),JsonNode.class); + JsonNode envelope=response.getBody(); budget.check(); + if(isRateLimited(envelope,null)) throw new RateLimited(reset(response.getHeaders())); + return successData(envelope,kind); + } catch(RateLimited limited) { + if(retries++>=settings.maxRetries()) fail("DIRECTORY_RATE_LIMIT_EXHAUSTED"); + rateGate.block(limited.seconds); budget.awaitRateLimit(limited.seconds,retries); + } catch(HttpStatusCodeException ex) { + JsonNode envelope=errorBody(ex.getResponseBodyAsString()); + if(isRateLimited(envelope,ex.getStatusCode().value())) { + if(retries++>=settings.maxRetries()) fail("DIRECTORY_RATE_LIMIT_EXHAUSTED"); + Long seconds=reset(ex.getResponseHeaders()); rateGate.block(seconds); + budget.awaitRateLimit(seconds,retries); continue; } - return body.path("data"); - } catch (DefinitiveDenial e) { throw e; } - catch (FeishuTenantTokenService.DiagnosticFailure e) { throw e; } - catch (RateLimited e) { - if (retries++ >= settings.maxRetries()) - throw FeishuTenantTokenService.diagnostic("DIRECTORY_RATE_LIMIT_EXHAUSTED"); - rateGate.block(e.resetSeconds); - budget.awaitRateLimit(e.resetSeconds, retries); - } catch (org.springframework.web.client.HttpStatusCodeException e) { - JsonNode body = null; - try { body = readErrorBody(e.getResponseBodyAsString()); } catch (Exception ignored) { } - if (live && definitive(body)) throw new DefinitiveDenial(); - if (isRateLimited(body, e.getStatusCode().value())) { - if (retries++ >= settings.maxRetries()) - throw FeishuTenantTokenService.diagnostic("DIRECTORY_RATE_LIMIT_EXHAUSTED"); - String reset = e.getResponseHeaders() == null ? null - : e.getResponseHeaders().getFirst("x-ogw-ratelimit-reset"); - Long resetSeconds = parseResetSeconds(reset); - rateGate.block(resetSeconds); - budget.awaitRateLimit(resetSeconds, retries); - continue; - } - RemoteFailure failure = remoteFailure(body, e.getStatusCode().value()); - if (failure != null) throw failure; - throw FeishuTenantTokenService.diagnostic("DIRECTORY_REQUEST_FAILED"); - } catch (Exception e) { throw FeishuTenantTokenService.diagnostic("DIRECTORY_REQUEST_FAILED"); } + RemoteFailure remote=remoteFailure(envelope,ex.getStatusCode().value(),kind); + if(remote!=null) throw remote; + fail("DIRECTORY_REQUEST_FAILED"); + } catch(FeishuTenantTokenService.DiagnosticFailure ex) { throw ex; + } catch(Exception ex) { fail("DIRECTORY_REQUEST_FAILED"); } } } - private static boolean isRateLimited(JsonNode body, Integer status) { - return (status != null && status == 429) || (body != null && body.path("code").isIntegralNumber() - && RATE_LIMIT_CODE.equals(responseCode(body))); - } - private static Long parseResetSeconds(String value) { - if (value == null || !value.trim().matches("[0-9]{1,10}")) return null; - try { return Long.valueOf(value.trim()); } catch (NumberFormatException ignored) { return null; } - } - private static JsonNode readErrorBody(String responseBody) throws java.io.IOException { - // Error text is deliberately never retained or included in an exception. Avoid - // parsing an unexpectedly large response while looking for its numeric code. - if (responseBody == null || responseBody.length() > 16384) return null; - return new com.fasterxml.jackson.databind.ObjectMapper().readTree(responseBody); - } - private static RemoteFailure remoteFailure(JsonNode body, Integer httpStatus) { - Long code = safeCode(body); - if (code != null) return new RemoteFailure("FEISHU_CODE_" + code); - if (httpStatus != null && httpStatus >= 100 && httpStatus <= 599) - return new RemoteFailure("HTTP_STATUS_" + httpStatus); - return null; - } - private static Long safeCode(JsonNode body) { - BigInteger code = responseCode(body); - if (code == null || code.signum() <= 0 || code.compareTo(MAX_DIAGNOSTIC_CODE) > 0) return null; - return code.longValueExact(); - } - private static boolean definitive(JsonNode body) { - BigInteger code = responseCode(body); - return DEFINITIVE_CODE_41050.equals(code) || DEFINITIVE_CODE_41012.equals(code); - } - private static BigInteger responseCode(JsonNode body) { - if (body == null) return null; - JsonNode value = body.path("code"); - if (!value.isIntegralNumber()) return null; - try { return value.bigIntegerValue(); } - catch (RuntimeException ignored) { return null; } - } - private static class DefinitiveDenial extends RuntimeException { } - /** Numeric-only diagnostic that is safe to cross the bounded worker boundary. */ - public static final class RemoteFailure extends FeishuTenantTokenService.DiagnosticFailure { - private RemoteFailure(String diagnosticCode) { - super(diagnosticCode); + private static JsonNode successData(JsonNode envelope,Kind kind) { + BigInteger code=responseCode(envelope); + if(code==null||code.signum()!=0||!envelope.path("data").isObject()) { + RemoteFailure failure=remoteFailure(envelope,null,kind); if(failure!=null) throw failure; + fail(kind.diagnostic+"_PAGE_INVALID"); } + return envelope.get("data"); } - private T bounded(java.util.concurrent.Callable task, long seconds) { - java.util.concurrent.Future future = null; - try { future = workers.submit(task); return future.get(seconds, java.util.concurrent.TimeUnit.SECONDS); } - catch (InterruptedException e) { Thread.currentThread().interrupt(); throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED"); } - catch (java.util.concurrent.ExecutionException e) { - Throwable cause = e.getCause(); - if (cause instanceof FeishuTenantTokenService.DiagnosticFailure) - throw (FeishuTenantTokenService.DiagnosticFailure) cause; - throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED"); - } catch (java.util.concurrent.TimeoutException e) { - throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEADLINE"); - } catch (java.util.concurrent.RejectedExecutionException e) { - throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_UNAVAILABLE"); - } - catch (Exception e) { throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED"); } - finally { if (future != null && !future.isDone()) future.cancel(true); } + private static void validateAbnormals(JsonNode data,Kind kind) { + JsonNode abnormal=data.get("abnormals"); + if(abnormal==null) return; + if(!abnormal.isArray()||abnormal.size()!=0) fail(kind.diagnostic+"_ABNORMAL"); } - public static boolean eligible(JsonNode user) { - JsonNode status = user.path("status"); - return status.path("is_activated").isBoolean() && status.path("is_activated").booleanValue() - && status.path("is_resigned").isBoolean() && !status.path("is_resigned").booleanValue() - && status.path("is_frozen").isBoolean() && !status.path("is_frozen").booleanValue() - && status.path("is_exited").isBoolean() && !status.path("is_exited").booleanValue() - && status.path("is_unjoin").isBoolean() && !status.path("is_unjoin").booleanValue() - && user.path("employee_type").isIntegralNumber() - && BigInteger.ONE.equals(user.path("employee_type").bigIntegerValue()); - } - static String required(JsonNode node, String key) { - return required(node, key, 100); - } - static String requiredIdentity(JsonNode node, String key) { - JsonNode value = node == null ? null : node.path(key); - if (!validText(value, 100)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); - return value.asText().trim(); - } - private static String requiredDepartmentIdentity(JsonNode node, String key) { - JsonNode value = node == null ? null : node.path(key); - if (!validText(value, 64)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); - return value.asText().trim(); - } - private static String required(JsonNode node, String key, int maxLength) { - JsonNode value = node == null ? null : node.path(key); - if (!validText(value, maxLength)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); - return value.asText(); - } - private static String requiredPageToken(JsonNode node, PageKind kind) { - JsonNode value = node == null ? null : node.path("page_token"); - if (!validText(value, 4096)) throw FeishuTenantTokenService.diagnostic(kind.pageTokenInvalid); - return value.asText(); - } - private static boolean validText(JsonNode value, int maxLength) { - return value != null && value.isTextual() && !value.asText().trim().isEmpty() - && value.asText().length() <= maxLength; - } - private static boolean validText(String value, int maxLength) { - return value != null && !value.trim().isEmpty() && value.length() <= maxLength; - } - private static String segment(String id) { - if (id == null || !id.matches("[A-Za-z0-9][A-Za-z0-9_@.\\-]{0,63}")) - throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); + + private String mergeDepartment(Snapshot snapshot,JsonNode node) { + String id=text(node,"department_id",64,true); + if("0".equals(id)) fail("DIRECTORY_DEPARTMENT_DUPLICATE_CONFLICT"); + String parent=text(node,"parent_department_id",64,true); + String name=i18n(node.get("name"),200,"DIRECTORY_DEPARTMENT_ITEM_INVALID"); + long order=numericStringLong(node.get("order_weight"),"DIRECTORY_DEPARTMENT_ITEM_INVALID"); + int members=departmentCount(node.get("department_count")); + // Directory-v1 has no documented enabled-status selector. Do not infer a + // lifecycle state from an absent field in a selectively projected response. + Department incoming=new Department(id,name,parent,order,"UNKNOWN",members); + Department old=snapshot.allDepartments.putIfAbsent(id,incoming); + if(old!=null&&!old.equals(incoming)) fail("DIRECTORY_DEPARTMENT_DUPLICATE_CONFLICT"); + if(old==null&&snapshot.allDepartments.size()>Math.min(5000,settings.getMaxDepartments())) + fail("DIRECTORY_LIMIT_EXCEEDED"); + // Directory-v1 filter is the authoritative full graph. Status is not used + // to prune nodes, so every returned structural member remains present. + snapshot.departments.add(id); snapshot.departmentDetails.put(id,incoming); return id; } + private static int departmentCount(JsonNode count) { + if(count==null||!count.isObject()) fail("DIRECTORY_DEPARTMENT_ITEM_INVALID"); + int direct=0; + for(String field:Arrays.asList("recursive_members_count","direct_members_count", + "recursive_members_count_exclude_leaders","recursive_departments_count","direct_departments_count")) { + JsonNode value=count.get(field); + if(value==null||!value.isTextual()||!value.textValue().matches("[0-9]{1,10}")) + fail("DIRECTORY_DEPARTMENT_ITEM_INVALID"); + try { int parsed=Integer.parseInt(value.textValue()); if("direct_members_count".equals(field))direct=parsed; } + catch(NumberFormatException ex){ fail("DIRECTORY_DEPARTMENT_ITEM_INVALID"); } + } + return direct; + } + private static void validateGraph(Snapshot snapshot) { + for(Department d:snapshot.departmentDetails.values()) { + if("0".equals(d.openDepartmentId)) continue; + if(d.openDepartmentId.equals(d.parentOpenDepartmentId)||!snapshot.departments.contains(d.parentOpenDepartmentId)) + fail("DIRECTORY_DEPARTMENT_GRAPH_INVALID"); + Set path=new HashSet<>(); String current=d.openDepartmentId; + while(!"0".equals(current)) { + if(!path.add(current)) fail("DIRECTORY_DEPARTMENT_GRAPH_INVALID"); + Department parent=snapshot.departmentDetails.get(current); + if(parent==null||!snapshot.departments.contains(parent.parentOpenDepartmentId)) + fail("DIRECTORY_DEPARTMENT_GRAPH_INVALID"); + current=parent.parentOpenDepartmentId; + } + } + } + + private void mergeEmployee(Snapshot snapshot,JsonNode node) { + UserSummary incoming=parseEmployee(node,snapshot.departments); + UserSummary old=snapshot.userSummaries.putIfAbsent(incoming.openId,incoming); + if(old!=null&&!old.equals(incoming)) fail("DIRECTORY_IDENTITY_CONFLICT"); + if(old==null) { + if(snapshot.userSummaries.size()>Math.min(50000,settings.getMaxUsers())) fail("DIRECTORY_LIMIT_EXCEEDED"); + // Compatibility view contains normalized fields only, never provider raw JSON. + ObjectNode normalized=JSON.createObjectNode(); normalized.put("open_id",incoming.openId); + normalized.put("name",incoming.name); normalized.put("eligible",incoming.eligible); + snapshot.users.put(incoming.openId,normalized); + } + } + private static UserSummary parseEmployee(JsonNode node,Set departments) { + JsonNode base=node.get("base_info"),work=node.get("work_info"); + if(base==null||!base.isObject()||work==null||!work.isObject()) fail("DIRECTORY_USER_ITEM_INVALID"); + UserSummary u=new UserSummary(); + u.openId=text(base,"employee_id",100,true); + JsonNode name=base.get("name"); + if(name==null||!name.isObject()||name.get("name")==null) fail("DIRECTORY_USER_ITEM_INVALID"); + u.name=i18n(name.get("name"),100,"DIRECTORY_USER_ITEM_INVALID"); + u.mobile=optionalText(base,"mobile",50,"DIRECTORY_USER_ITEM_INVALID"); + u.email=optionalText(base,"email",320,"DIRECTORY_USER_ITEM_INVALID"); + JsonNode ids=base.get("departments"); + if(ids==null||!ids.isArray()) fail("DIRECTORY_USER_ITEM_INVALID"); + for(JsonNode department:ids) { + if(department==null||!department.isObject()) fail("DIRECTORY_USER_ITEM_INVALID"); + String id=text(department,"department_id",64,true); + if(!departments.contains(id)) fail("DIRECTORY_USER_DEPARTMENT_INVALID"); + if(!u.departmentIds.contains(id))u.departmentIds.add(id); + } + if(u.departmentIds.isEmpty()&&departments.contains("0"))u.departmentIds.add("0"); + u.avatarUrl=avatar(base.get("avatar")); + u.employeeNo=optionalText(work,"job_number",50,"DIRECTORY_USER_ITEM_INVALID"); + JsonNode title=work.get("job_title"); + if(title==null||title.isNull())u.jobTitle=""; + else { + if(!title.isObject()||title.get("job_title_name")==null||title.get("job_title_name").isNull()) + fail("DIRECTORY_USER_ITEM_INVALID"); + u.jobTitle=i18n(title.get("job_title_name"),200,"DIRECTORY_USER_ITEM_INVALID"); + } + // Exhaustive traversal defines the current employee population. The status + // partition used by transport is deliberately neither projected nor parsed. + u.eligible=true; + return u; + } + private static String avatar(JsonNode avatar) { + if(avatar==null||avatar.isNull())return ""; + if(!avatar.isObject())fail("DIRECTORY_USER_ITEM_INVALID"); + String result=""; + for(String key:Arrays.asList("avatar_origin","avatar_640","avatar_240","avatar_72")) { + JsonNode value=avatar.get(key); + if(value==null)continue; + if(!value.isTextual()||value.textValue().length()>500)fail("DIRECTORY_USER_ITEM_INVALID"); + if(result.isEmpty()&&!value.textValue().trim().isEmpty())result=value.textValue().trim(); + } + return result; + } + private static String i18n(JsonNode value,int max,String diagnostic) { + if(value==null||!value.isObject())fail(diagnostic); + String result=text(value,"default_value",max,true); + JsonNode translations=value.get("i18n_value"); + if(translations==null||translations.isNull())return result; + if(!translations.isObject())fail(diagnostic); + Iterator> fields=translations.fields(); + while(fields.hasNext()){Map.Entry field=fields.next(); + if(!field.getValue().isTextual()||field.getValue().textValue().length()>max)fail(diagnostic);} + return result; + } + private static String optionalText(JsonNode object,String key,int max,String diagnostic) { + JsonNode value=object==null?null:object.get(key); + if(value==null||value.isNull())return ""; + if(!value.isTextual()||value.textValue().length()>max)fail(diagnostic); + return value.textValue().trim(); + } + private static long numericStringLong(JsonNode value,String diagnostic) { + if(value==null||!value.isTextual()||!value.textValue().matches("-?[0-9]{1,19}"))fail(diagnostic); + try{return Long.parseLong(value.textValue());}catch(NumberFormatException ex){fail(diagnostic);return 0;} + } + private static String text(JsonNode object,String key,int max,boolean nonblank) { + JsonNode value=object==null?null:object.get(key); + if(value==null||!value.isTextual()||value.textValue().length()>max||(nonblank&&value.textValue().trim().isEmpty())) + fail("DIRECTORY_IDENTITY_INVALID"); + return value.textValue().trim(); + } + public static boolean eligible(JsonNode normalized) { + return normalized!=null&&normalized.path("eligible").isBoolean()&&normalized.path("eligible").booleanValue(); + } + public static class Snapshot { - public final Set departments = new LinkedHashSet<>(); - public final Map users = new LinkedHashMap<>(); - /** Safe, presentation-independent department records from the same snapshot. */ - public final Map departmentDetails = new LinkedHashMap<>(); - /** Safe user summaries; raw users above are retained only for account application. */ - public final Map userSummaries = new LinkedHashMap<>(); + public final Set departments=new LinkedHashSet<>(); + /** Deprecated normalized compatibility view. */ + public final Map users=new LinkedHashMap<>(); + public final Map departmentDetails=new LinkedHashMap<>(); + public final Map userSummaries=new LinkedHashMap<>(); + private final Map allDepartments=new LinkedHashMap<>(); } public static class Department { - public String openDepartmentId; - public String name; - public String parentOpenDepartmentId; - public long order; - public String status; - public int memberCount; - - public static Department root() { - Department root = new Department(); - root.openDepartmentId = "0"; - root.name = "根部门"; - root.parentOpenDepartmentId = "0"; - root.status = "ACTIVE"; - return root; - } - - static Department from(JsonNode node, String id, String traversalParent) { - Department department = new Department(); - department.openDepartmentId = id; - department.name = optionalText(node, "name", ""); - // parent_department_id is deliberately not used here: with an - // open-id request it may still be a legacy/custom identifier. - // The traversal request already establishes the parent with an - // open id. Prefer it over any legacy parent_department_id-shaped - // value returned in the payload. - department.parentOpenDepartmentId = traversalParent; - department.order = optionalLong(node, "order", 0L); - department.status = "ACTIVE"; - return department; - } - - public String getOpenDepartmentId() { return openDepartmentId; } - public String getName() { return name; } - public String getParentOpenDepartmentId() { return parentOpenDepartmentId; } - public long getOrder() { return order; } - public String getStatus() { return status; } - public int getMemberCount() { return memberCount; } + public String openDepartmentId,name,parentOpenDepartmentId,status; public long order; public int memberCount; + Department(){} + Department(String id,String name,String parent,long order,String status,int count){this.openDepartmentId=id;this.name=name;this.parentOpenDepartmentId=parent;this.order=order;this.status=status;this.memberCount=count;} + public static Department root(){return new Department("0","根部门","0",0,"UNKNOWN",0);} + public String getOpenDepartmentId(){return openDepartmentId;} public String getName(){return name;} + public String getParentOpenDepartmentId(){return parentOpenDepartmentId;} public long getOrder(){return order;} + public String getStatus(){return status;} public int getMemberCount(){return memberCount;} + @Override public boolean equals(Object o){if(!(o instanceof Department))return false;Department d=(Department)o;return order==d.order&&memberCount==d.memberCount&&Objects.equals(openDepartmentId,d.openDepartmentId)&&Objects.equals(name,d.name)&&Objects.equals(parentOpenDepartmentId,d.parentOpenDepartmentId)&&Objects.equals(status,d.status);} + @Override public int hashCode(){return Objects.hash(openDepartmentId,name,parentOpenDepartmentId,order,status,memberCount);} } - public static class UserSummary { - public String openId; - public String userId; - public String name; - public String employeeNo; - public String email; - public String mobile; - public String jobTitle; - public Integer employeeType; - public String avatarUrl; - public String employmentStatus; - public final List departmentIds = new ArrayList<>(); + public String openId,userId,name,employeeNo,email,mobile,jobTitle,avatarUrl; public boolean eligible; - - static UserSummary from(JsonNode node, String fallbackDepartment) { - UserSummary summary = new UserSummary(); - summary.openId = optionalText(node, "open_id", ""); - summary.userId = optionalText(node, "user_id", ""); - summary.name = optionalText(node, "name", ""); - summary.employeeNo = optionalText(node, "employee_no", ""); - // Keep this allow-list deliberately explicit. Contact v3 user nodes - // contain more data than the directory API is allowed to retain. - summary.email = optionalText(node, "email", "", 320); - summary.mobile = optionalText(node, "mobile", "", 50); - summary.jobTitle = optionalText(node, "job_title", "", 200); - if (summary.jobTitle.isEmpty()) summary.jobTitle = optionalText(node, "position", "", 200); - summary.employeeType = optionalInteger(node, "employee_type"); - summary.avatarUrl = optionalAvatarUrl(node); - summary.employmentStatus = employmentStatus(node); - JsonNode ids = node == null ? null : node.path("department_ids"); - if (ids != null && ids.isArray()) { - for (JsonNode id : ids) { - if (id.isTextual() && validText(id, 64) && !summary.departmentIds.contains(id.asText().trim())) - summary.departmentIds.add(id.asText().trim()); - } - } - // A missing department_ids field is common on reduced contact - // responses. The requested department is already an open id and - // is therefore a safe fallback; department_id is never consulted. - if (summary.departmentIds.isEmpty() && validText(fallbackDepartment, 64)) - summary.departmentIds.add(fallbackDepartment.trim()); - summary.eligible = eligible(node); - return summary; - } - - void addDepartment(String department) { - if (validText(department, 64) && !departmentIds.contains(department.trim())) - departmentIds.add(department.trim()); - } - - void merge(JsonNode node, Set knownDepartments) { - if (name == null || name.isEmpty()) name = optionalText(node, "name", ""); - if (employeeNo == null || employeeNo.isEmpty()) employeeNo = optionalText(node, "employee_no", ""); - if (email == null || email.isEmpty()) email = optionalText(node, "email", "", 320); - if (mobile == null || mobile.isEmpty()) mobile = optionalText(node, "mobile", "", 50); - if (jobTitle == null || jobTitle.isEmpty()) { - jobTitle = optionalText(node, "job_title", "", 200); - if (jobTitle.isEmpty()) jobTitle = optionalText(node, "position", "", 200); - } - if (employeeType == null) employeeType = optionalInteger(node, "employee_type"); - if (avatarUrl == null || avatarUrl.isEmpty()) avatarUrl = optionalAvatarUrl(node); - if (employmentStatus == null || employmentStatus.isEmpty() || "UNKNOWN".equals(employmentStatus)) - employmentStatus = employmentStatus(node); - JsonNode ids = node == null ? null : node.path("department_ids"); - if (ids != null && ids.isArray()) for (JsonNode id : ids) - if (id.isTextual() && validText(id, 64) && knownDepartments.contains(id.asText().trim())) - addDepartment(id.asText()); - } - - public String getOpenId() { return openId; } - public String getUserId() { return userId; } - public String getName() { return name; } - public String getEmployeeNo() { return employeeNo; } - public String getEmail() { return email; } - public String getMobile() { return mobile; } - public String getJobTitle() { return jobTitle; } - public Integer getEmployeeType() { return employeeType; } - public String getAvatarUrl() { return avatarUrl; } - public String getEmploymentStatus() { return employmentStatus; } - public List getDepartmentIds() { return departmentIds; } - public boolean isEligible() { return eligible; } + public final List departmentIds=new ArrayList<>(); + public String getOpenId(){return openId;} public String getUserId(){return userId;} public String getName(){return name;} + public String getEmployeeNo(){return employeeNo;} public String getEmail(){return email;} public String getMobile(){return mobile;} + public String getJobTitle(){return jobTitle;} public String getAvatarUrl(){return avatarUrl;} + public List getDepartmentIds(){return departmentIds;} public boolean isEligible(){return eligible;} + @Override public boolean equals(Object o){if(!(o instanceof UserSummary))return false;UserSummary u=(UserSummary)o;return eligible==u.eligible&&Objects.equals(openId,u.openId)&&Objects.equals(name,u.name)&&Objects.equals(employeeNo,u.employeeNo)&&Objects.equals(email,u.email)&&Objects.equals(mobile,u.mobile)&&Objects.equals(jobTitle,u.jobTitle)&&Objects.equals(avatarUrl,u.avatarUrl)&&departmentIds.equals(u.departmentIds);} + @Override public int hashCode(){return Objects.hash(openId,name,employeeNo,email,mobile,jobTitle,avatarUrl,departmentIds,eligible);} } - private static String optionalText(JsonNode node, String key, String fallback) { - return optionalText(node, key, fallback, 100); + private T bounded(Callable task,long seconds){Future future=null;try{future=worker.submit(task);return future.get(seconds,TimeUnit.SECONDS);} + catch(InterruptedException ex){Thread.currentThread().interrupt();fail("DIRECTORY_INTERRUPTED");} + catch(TimeoutException ex){fail("DIRECTORY_DEADLINE");} + catch(ExecutionException ex){Throwable cause=ex.getCause();if(cause instanceof FeishuTenantTokenService.DiagnosticFailure)throw(FeishuTenantTokenService.DiagnosticFailure)cause;fail("DIRECTORY_WORKER_FAILED");} + catch(RejectedExecutionException ex){fail("DIRECTORY_WORKER_UNAVAILABLE");} + finally{if(future!=null&&!future.isDone())future.cancel(true);}return null;} + private static void fail(String code){throw FeishuTenantTokenService.diagnostic(code);} + private static boolean boundedText(JsonNode node,int max){return node!=null&&node.isTextual()&&!node.textValue().trim().isEmpty()&&node.textValue().length()<=max;} + private static BigInteger responseCode(JsonNode body){if(body==null||!body.path("code").isIntegralNumber())return null;try{return body.path("code").bigIntegerValue();}catch(RuntimeException ex){return null;}} + private static boolean isRateLimited(JsonNode body,Integer status){return status!=null&&status==429||RATE_LIMIT_CODE.equals(responseCode(body));} + private static JsonNode errorBody(String value){if(value==null||value.length()>16384)return null;try{return JSON.readTree(value);}catch(Exception ex){return null;}} + private static RemoteFailure remoteFailure(JsonNode body,Integer status,Kind kind){BigInteger code=responseCode(body);if(code!=null&&code.signum()>0&&code.compareTo(MAX_DIAGNOSTIC_CODE)<=0)return new RemoteFailure(kind.diagnostic+"_FEISHU_CODE_"+code);if(status!=null&&status>=100&&status<=599)return new RemoteFailure(kind.diagnostic+"_HTTP_STATUS_"+status);return null;} + 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(Exception ex){return null;}} + public static final class RemoteFailure extends FeishuTenantTokenService.DiagnosticFailure{private RemoteFailure(String code){super(code);}} + private static final class RateLimited extends RuntimeException{final Long seconds;RateLimited(Long seconds){this.seconds=seconds;}} + private final class Budget { + final long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(settings.elapsed()); + final AtomicInteger requests=new AtomicInteger(),pages=new AtomicInteger(); + void check(){if(Thread.currentThread().isInterrupted())fail("DIRECTORY_INTERRUPTED");if(System.nanoTime()>=deadline)fail("DIRECTORY_DEADLINE");} + void page(){check();if(pages.incrementAndGet()>Math.min(2000,settings.getMaxPages()))fail("DIRECTORY_LIMIT_EXCEEDED");} + void request(){check();if(requests.incrementAndGet()>2000)fail("DIRECTORY_LIMIT_EXCEEDED");} + void awaitRateLimit(Long seconds,int retry){long nanos=seconds==null?TimeUnit.MILLISECONDS.toNanos(Math.min(2000L,100L< 0) - return null; - return integer.intValueExact(); - } catch (RuntimeException ignored) { - return null; - } - } - - private static String optionalAvatarUrl(JsonNode node) { - String value = optionalText(node, "avatar_url", "", 500); - if (!value.isEmpty()) return value; - value = optionalText(node, "avatar", "", 500); - if (!value.isEmpty()) return value; - - // Some Contact v3 responses represent avatar as an object. Select only - // documented URL variants; never serialize the object itself. - JsonNode avatar = node == null ? null : node.path("avatar"); - if (avatar != null && avatar.isObject()) { - for (String key : new String[]{"avatar_url", "avatar_origin", "avatar_640", "avatar_240", "avatar_72"}) { - value = optionalText(avatar, key, "", 500); - if (!value.isEmpty()) return value; - } - } - return ""; - } - - /** Safe summary derived from the official status booleans, not a raw status object. */ - private static String employmentStatus(JsonNode node) { - JsonNode status = node == null ? null : node.path("status"); - if (status == null || !status.isObject()) return "UNKNOWN"; - if (status.path("is_exited").isBoolean() && status.path("is_exited").booleanValue()) return "EXITED"; - if (status.path("is_resigned").isBoolean() && status.path("is_resigned").booleanValue()) return "RESIGNED"; - if (status.path("is_frozen").isBoolean() && status.path("is_frozen").booleanValue()) return "FROZEN"; - if (status.path("is_unjoin").isBoolean() && status.path("is_unjoin").booleanValue()) return "UNJOINED"; - if (status.path("is_activated").isBoolean()) - return status.path("is_activated").booleanValue() ? "ACTIVE" : "INACTIVE"; - return "UNKNOWN"; - } - - private static long optionalLong(JsonNode node, String key, long fallback) { - JsonNode value = node == null ? null : node.path(key); - if (value == null) return fallback; - if (value.isIntegralNumber()) { - try { return value.bigIntegerValue().longValueExact(); } - catch (ArithmeticException ignored) { return fallback; } - } - if (!value.isTextual()) return fallback; - String text = value.asText().trim(); - // Contact v3 has returned order both as a JSON number and as a - // numeric string. Bound the text before parsing so malformed provider - // data cannot trigger unbounded numeric work. - if (text.length() == 0 || text.length() > 20 || !text.matches("[+-]?[0-9]+")) return fallback; - try { return new BigInteger(text).longValueExact(); } - catch (NumberFormatException | ArithmeticException ignored) { return fallback; } - } - private static final class RateLimited extends RuntimeException { - private final Long resetSeconds; - private RateLimited(Long resetSeconds) { this.resetSeconds = resetSeconds; } - } - /** One gate is shared by department discovery, user paging and verification. */ private final class RateGate { - private final FeishuDirectorySettings settings; - private final Deque requests = new ArrayDeque<>(); - private long lastRequest = Long.MIN_VALUE; - private long blockedUntil = Long.MIN_VALUE; - - private RateGate(FeishuDirectorySettings settings) { this.settings = settings; } - - private void acquire(Budget budget) { - while (true) { - budget.check(); - long now = System.nanoTime(); - long waitUntil; - synchronized (this) { - long minuteAgo = now - TimeUnit.SECONDS.toNanos(60); - while (!requests.isEmpty() && requests.peekFirst() < minuteAgo) requests.removeFirst(); - waitUntil = now; - if (lastRequest != Long.MIN_VALUE) { - long spacing = (TimeUnit.SECONDS.toNanos(1) + settings.requestsPerSecond() - 1L) - / settings.requestsPerSecond(); - waitUntil = Math.max(waitUntil, lastRequest + spacing); - } - if (requests.size() >= settings.requestsPerMinute() && !requests.isEmpty()) - waitUntil = Math.max(waitUntil, requests.peekFirst() + TimeUnit.SECONDS.toNanos(60)); - waitUntil = Math.max(waitUntil, blockedUntil); - if (waitUntil <= now) { - requests.addLast(now); - lastRequest = now; - return; - } - } - budget.awaitNanos(waitUntil - now); - } - } - private void block(Long resetSeconds) { - if (resetSeconds == null || resetSeconds <= 0) return; - long now = System.nanoTime(); - long duration = resetSeconds > Long.MAX_VALUE / 1000000000L - ? Long.MAX_VALUE : resetSeconds * 1000000000L; - long until = Long.MAX_VALUE - now < duration ? Long.MAX_VALUE : now + duration; - synchronized (this) { blockedUntil = Math.max(blockedUntil, until); } - } - } - private class Budget { - final long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(settings.elapsed()); - final AtomicInteger pages = new AtomicInteger(); - void check() { - if (Thread.currentThread().isInterrupted()) throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED"); - if (System.nanoTime() >= deadlineNanos) - throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEADLINE"); - } - void page() { - check(); - if (pages.incrementAndGet() > Math.min(2000, settings.getMaxPages())) - throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED); - check(); - } - void awaitRateLimit(Long resetSeconds, int retry) { - long nanos; - if (resetSeconds != null) { - nanos = resetSeconds > Long.MAX_VALUE / 1000000000L - ? Long.MAX_VALUE : resetSeconds * 1000000000L; - } else { - long backoffMillis = Math.min(2000L, 100L << Math.min(4, Math.max(0, retry - 1))); - nanos = TimeUnit.MILLISECONDS.toNanos(backoffMillis); - } - awaitNanos(nanos); - } - void awaitNanos(long requested) { - check(); - long remaining = deadlineNanos - System.nanoTime(); - if (remaining <= 0) throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEADLINE"); - LockSupport.parkNanos(Math.min(Math.max(0L, requested), remaining)); - check(); - } + final Deque minute=new ArrayDeque<>(); long last=Long.MIN_VALUE,blocked=Long.MIN_VALUE; + void acquire(Budget budget){while(true){budget.check();long now=System.nanoTime(),until; synchronized(this){long ago=now-TimeUnit.MINUTES.toNanos(1);while(!minute.isEmpty()&&minute.peekFirst()=settings.requestsPerMinute())until=Math.max(until,minute.peekFirst()+TimeUnit.MINUTES.toNanos(1));if(until<=now){minute.addLast(now);last=now;return;}}budget.await(until-now);}} + synchronized void block(Long seconds){if(seconds==null||seconds<=0)return;long now=System.nanoTime(),duration=seconds>Long.MAX_VALUE/1_000_000_000L?Long.MAX_VALUE:seconds*1_000_000_000L;blocked=Math.max(blocked,Long.MAX_VALUE-now> relations=relations(snapshot);Map counts=memberCounts(snapshot,relations); + Map oldDepartments=hashes("SELECT open_department_id,content_hash FROM feishu_directory_department"); + Map oldUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_user"); + Set wantedDepartments=new LinkedHashSet<>(),wantedUsers=new LinkedHashSet<>(); + List departmentRows=new ArrayList<>(),userRows=new ArrayList<>(); + List 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 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 oldMemberships=new LinkedHashSet<>();for(Map 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"))); + SetwantedMemberships=new LinkedHashSet<>();ListmembershipRows=new ArrayList<>(),retainedMembershipRows=new ArrayList<>(); + for(Map.Entry> 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 read(){ + List> departments=new ArrayList<>();for(Mapr: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")){Mapd=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> memberships=new HashMap<>();for(Mapr: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>users=new ArrayList<>();for(Mapr:jdbc.queryForList("SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id")){Mapu=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);} + Mapresult=new LinkedHashMap<>();result.put("departments",departments);result.put("users",users);return result; + } + private void batchDeleteMemberships(Setold,Setwanted){Listrows=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,Setold,Setwanted){Listrows=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,Listrows){for(int i=0;ihashes(String sql){Mapr=new LinkedHashMap<>();for(Maprow:jdbc.queryForList(sql)){Iteratori=row.values().iterator();r.put(string(i.next()),string(i.next()));}return r;} + private Map>relations(FeishuDirectoryClient.Snapshot s){Map>r=new LinkedHashMap<>();int total=0;for(Map.Entrye:s.userSummaries.entrySet()){LinkedHashSetids=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 MapmemberCounts(FeishuDirectoryClient.Snapshot s,Map>relations){Mapparents=new HashMap<>();for(String id:s.departments){FeishuDirectoryClient.Department d=s.departmentDetails.get(id);parents.put(id,d==null?"0":d.parentOpenDepartmentId);}Map>members=new HashMap<>();int expanded=0;for(Map.Entry>e:relations.entrySet()){String employee=e.getKey();for(String id:e.getValue()){Setvisited=new HashSet<>();String current=id;while(current!=null&&parents.containsKey(current)&&visited.add(current)){Setset=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;}}}Mapr=new HashMap<>();for(Map.Entry>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;} +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublication.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublication.java new file mode 100644 index 0000000..0f03035 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublication.java @@ -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 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; + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java new file mode 100644 index 0000000..8f43269 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java @@ -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 opens=new LinkedHashSet<>(), employeeNumbers=new LinkedHashSet<>(); + for(Map.Entry 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 byOpen=new HashMap<>();Set 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 updates=new ArrayList<>(ACCOUNT_UPDATE_BATCH); + for(Map.Entry 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 updates,Object[] update){updates.add(update);if(updates.size()>=ACCOUNT_UPDATE_BATCH)flushAccountUpdates(updates);} + void flushAccountUpdates(List 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 updates){ + Map 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 ids=new ArrayList<>(expectedById.keySet()); + Set verified=new HashSet<>(); + for(int start=0;start 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 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 values,Map byOpen,Set employees){ + List all=new ArrayList<>(values);for(int start=0;start 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 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 values,Set result){Listall=new ArrayList<>(values);for(int start=0;startb=all.subList(start,Math.min(all.size(),start+LOOKUP_BATCH));for(Maprow: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(Maprow){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;i0)b.append(',');b.append('?');}return b.toString();} + private static String trim(String value){return value==null?"":value.trim();} + private static String requiredOpen(Map.Entry 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;}} +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java new file mode 100644 index 0000000..dd56b45 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java @@ -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 state = lockState(); + List> rows = jdbc.queryForList( + "SELECT run_id,trigger_type,attempt_count FROM feishu_directory_sync_run " + + "WHERE (state='QUEUED' OR (state='RUNNING' AND lease_until 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 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 requireLease(Claim claim) { + Map state = lockState(); + List 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 state = lockState(); + List> 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 expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE state='RUNNING' " + + "AND lease_until=? 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 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; + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java index aebdf93..ff479fb 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java @@ -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 status(){ + Map 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 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 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 organization(){ + Map unavailable=emptyOrganization(FeishuDirectoryPublication.unavailable(),null,"UNKNOWN"); + if(!organizationPermits.tryAcquire())return unavailable; + try{ + OrganizationSnapshot captured=organizationSnapshot.execute(status->{ + Map state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1"); + FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time); + Instant success=publication.getSuccessfulAt(); + Map result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN"); + if(!publication.isAvailable())return new OrganizationSnapshot(publication,result); + Map 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> relationships = new LinkedHashMap<>(); - for (Map.Entry entry : snapshot.users.entrySet()) { - FeishuDirectoryClient.UserSummary summary = snapshot.userSummaries.get(entry.getKey()); - if (summary == null) summary = FeishuDirectoryClient.UserSummary.from(entry.getValue(), "0"); - List departmentIds = normalizedDepartmentIds(snapshot, summary); - relationships.put(entry.getKey(), departmentIds); - } - Map 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 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 userArgs = new ArrayList<>(snapshot.users.size()); - for (Map.Entry 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 relationshipArgs = new ArrayList<>(); - for (Map.Entry> 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 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 columns, String table, String... required) { - Set 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 normalizedDepartmentIds(FeishuDirectoryClient.Snapshot snapshot, - FeishuDirectoryClient.UserSummary summary) { - LinkedHashSet 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 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 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 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 emptyOrganization(FeishuDirectoryPublication publication,String at,String contextState){Mapresult=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 Mapvalue;private OrganizationSnapshot(FeishuDirectoryPublication publication,Mapvalue){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 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 existingUsers = users.findAll(); - Map byOpenId = new HashMap<>(); - Map byUserId = new HashMap<>(); - Map 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 newUsers = new ArrayList<>(); - List statusUpdates = new ArrayList<>(); - List statusUsers = new ArrayList<>(); - Set 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 status() { - Map 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 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 organization() { - Map 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 captured = tx.execute(s -> { - Map 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 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 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>) organization.get("departments"), - (List>) 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>()); - result.put("users", new ArrayList>()); - return result; - } - } - - private JsonNode safeReadSnapshot(String value) { - try { return value == null ? null : mapper.readTree(value); } - catch (Exception ignored) { return null; } - } - - private Map 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> departments = new ArrayList<>(); - List> 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 row : departmentRows) { - Map 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> userDepartments = new HashMap<>(); - List> 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 row : relationRows) { - String openId = stringValue(row.get("open_id")); - List 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> users = new ArrayList<>(); - List> 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 row : userRows) { - Map 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 ids = userDepartments.get(openId); - user.put("departmentIds", ids == null ? new ArrayList() : 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 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 emptyOrganization(String state, String at) { - Map result = new LinkedHashMap<>(); - result.put("snapshotState", state); - result.put("lastSuccessfulAt", at); - result.put("departments", new ArrayList>()); - result.put("users", new ArrayList>()); - 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> safeDepartments(JsonNode nodes) { - List> departments = new ArrayList<>(); - if (!nodes.isArray()) return departments; - for (JsonNode node : nodes) { - if (!node.isObject()) continue; - Map 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> safeUsers(JsonNode nodes) { - List> users = new ArrayList<>(); - if (!nodes.isArray()) return users; - for (JsonNode node : nodes) { - if (!node.isObject()) continue; - Map 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 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> departments, List> users) { - Map parents = new HashMap<>(); - for (Map department : departments) - parents.put(stringValue(department.get("id")), stringValue(department.get("parentId"))); - Map> members = new HashMap<>(); - int row = 0; - for (Map user : users) { - String employee = stringValue(user.get("openId")); - if (employee.isEmpty()) employee = "\u0000" + row; - Object ids = user.get("departmentIds"); - if (ids instanceof Iterable) { - LinkedHashSet 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 department : departments) { - Set 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 normalizedMemberCounts(FeishuDirectoryClient.Snapshot snapshot, - Map> relationships) { - Map 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> members = new HashMap<>(); - for (Map.Entry> 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 counts = new HashMap<>(); - for (Map.Entry> 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 parents, - Map> members) { - Set visited = new HashSet<>(); - String current = departmentId; - while (current != null && parents.containsKey(current) && visited.add(current)) { - Set 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 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 parents = new HashMap<>(); - for (JsonNode department : departments) - parents.put(department.path("id").asText(), department.path("parentId").asText()); - Map> members = new HashMap<>(); - int row = 0; - for (JsonNode user : users) { - String employee = user.path("openId").asText(); - if (employee.isEmpty()) employee = "\u0000" + row; - LinkedHashSet 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 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;}} } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java index 82df451..b7c28f8 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java @@ -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)); } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java new file mode 100644 index 0000000..caef0f3 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java @@ -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;} +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java new file mode 100644 index 0000000..6226d0f --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java @@ -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; + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryTime.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryTime.java new file mode 100644 index 0000000..c51f623 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryTime.java @@ -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; + } + +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java index 7f3c5a0..a97bca0 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java @@ -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; }); diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java index fc80b6b..44061a4 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java @@ -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 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 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<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"); } diff --git a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java new file mode 100644 index 0000000..21ff7c2 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java @@ -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 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 orderedItems(List items) { + List 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('|'); + } +} diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java index ac92d86..34bc45a 100644 --- a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java +++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java @@ -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 response = restTemplate.postForEntity(url, request, Map.class); Map body = response.getBody(); - if (body != null && Boolean.TRUE.equals(body.get("IsSuccess"))) { - Map result = (Map) body.get("Result"); - if (result != null) { - this.sessionToken = (String) result.get("SessionId"); + if (body != null && loginSucceeded(body)) { + Map context = asMap(body.get("Context")); + Map 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 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> 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> query(String formId, String filterString, + String fieldKeys, int startRow, int topRowCount) { + String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc"; Map 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> request = new HttpEntity<>(data, headers); try { - ResponseEntity response = restTemplate.postForEntity(url, request, Map.class); - Map body = response.getBody(); - if (body != null && body.containsKey("Result")) { - Object result = body.get("Result"); - if (result instanceof List) { - return objectMapper.convertValue(result, new TypeReference>>() {}); - } - } - return java.util.Collections.emptyList(); + ResponseEntity 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 response = restTemplate.postForEntity(url, request, Map.class); Map 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 body) { + if (Boolean.TRUE.equals(body.get("IsSuccess"))) return true; + Object resultType = body.get("LoginResultType"); + return "1".equals(String.valueOf(resultType)); + } + + private List> 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 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 keys = new ArrayList<>(); + for (String key : (fieldKeys == null ? "" : fieldKeys).split(",")) { + if (!key.trim().isEmpty()) keys.add(key.trim()); + } + List> rows = new ArrayList<>(); + for (Object rawRow : rawRows) { + if (rawRow instanceof Map) rows.add(objectMapper.convertValue(rawRow, new TypeReference>() {})); + else if (rawRow instanceof List) { + Map 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 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 asMap(Object value) { + return value instanceof Map ? (Map) 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; diff --git a/src/main/java/com/finance/system/config/FeishuDirectoryAsyncConfig.java b/src/main/java/com/finance/system/config/FeishuDirectoryAsyncConfig.java new file mode 100644 index 0000000..a9ce1be --- /dev/null +++ b/src/main/java/com/finance/system/config/FeishuDirectoryAsyncConfig.java @@ -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;};} +} diff --git a/src/main/java/com/finance/system/config/KingdeeAsyncSyncConfig.java b/src/main/java/com/finance/system/config/KingdeeAsyncSyncConfig.java new file mode 100644 index 0000000..2e4b33f --- /dev/null +++ b/src/main/java/com/finance/system/config/KingdeeAsyncSyncConfig.java @@ -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; + } +} diff --git a/src/main/java/com/finance/system/config/LocalDataInitializer.java b/src/main/java/com/finance/system/config/LocalDataInitializer.java index f421129..e5fb53c 100644 --- a/src/main/java/com/finance/system/config/LocalDataInitializer.java +++ b/src/main/java/com/finance/system/config/LocalDataInitializer.java @@ -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 groupMembers = members.findByIdGroupId(group.getId()); + List userMemberships = members.findByIdUserId(user.getId()); + List 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 groupMembers = members.findByIdGroupId(group.getId()); + for (SysUserGroupMember membership : groupMembers) { + if (!user.getId().equals(membership.getId().getUserId())) { + throw new IllegalStateException("本地初始化专属用户组包含其他用户: " + groupCode); + } + } + List userMemberships = members.findByIdUserId(user.getId()); + for (SysUserGroupMember membership : userMemberships) { + if (!group.getId().equals(membership.getId().getGroupId())) { + throw new IllegalStateException("本地初始化用户已属于其他用户组: " + user.getEmployeeNo()); + } + } + List 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; } diff --git a/src/main/java/com/finance/system/config/SecurityConfig.java b/src/main/java/com/finance/system/config/SecurityConfig.java index 437e440..3e1ef38 100644 --- a/src/main/java/com/finance/system/config/SecurityConfig.java +++ b/src/main/java/com/finance/system/config/SecurityConfig.java @@ -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; } } diff --git a/src/main/java/com/finance/system/controller/AccountsPayableController.java b/src/main/java/com/finance/system/controller/AccountsPayableController.java index 7cd36f4..3d6190e 100644 --- a/src/main/java/com/finance/system/controller/AccountsPayableController.java +++ b/src/main/java/com/finance/system/controller/AccountsPayableController.java @@ -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>> 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> 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> 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> 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>> getHistory() { Long userId = AuditUtil.getCurrentUserId(); List history = reimApprovalService.getApprovalHistoryByUser(userId); diff --git a/src/main/java/com/finance/system/controller/ApplicationController.java b/src/main/java/com/finance/system/controller/ApplicationController.java index 2bd764a..5fd5a00 100644 --- a/src/main/java/com/finance/system/controller/ApplicationController.java +++ b/src/main/java/com/finance/system/controller/ApplicationController.java @@ -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>>> 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>> getApplicationDetail(@PathVariable Long id) { try { Map application = MOCK_APPLICATIONS.stream() diff --git a/src/main/java/com/finance/system/controller/AuthController.java b/src/main/java/com/finance/system/controller/AuthController.java index 9d063cb..58cc041 100644 --- a/src/main/java/com/finance/system/controller/AuthController.java +++ b/src/main/java/com/finance/system/controller/AuthController.java @@ -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> 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>> listUsers() { List users = sysUserRepository.findAll(); List 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> updateUserRole( @PathVariable Long id, @RequestBody Map 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> toggleUserStatus( @PathVariable Long id, @RequestBody Map 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> updateUserRoles(@PathVariable Long id, @RequestBody Map 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(); } diff --git a/src/main/java/com/finance/system/controller/CashierController.java b/src/main/java/com/finance/system/controller/CashierController.java index 8374a9b..c409648 100644 --- a/src/main/java/com/finance/system/controller/CashierController.java +++ b/src/main/java/com/finance/system/controller/CashierController.java @@ -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>> 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> 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> 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> 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>> getPaymentHistory() { Long userId = AuditUtil.getCurrentUserId(); List history = reimPaymentService.getPaymentHistoryByOperator(userId); @@ -76,18 +81,26 @@ public class CashierController { } @GetMapping("/payments/{paymentNo}") + @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") public ResponseEntity> 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; } } diff --git a/src/main/java/com/finance/system/controller/DashboardController.java b/src/main/java/com/finance/system/controller/DashboardController.java index 3acd851..264ca7e 100644 --- a/src/main/java/com/finance/system/controller/DashboardController.java +++ b/src/main/java/com/finance/system/controller/DashboardController.java @@ -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> 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>> getRecent( @RequestParam(defaultValue = "5") int limit) { Long userId = AuditUtil.getCurrentUserId(); diff --git a/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java b/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java new file mode 100644 index 0000000..10c0e89 --- /dev/null +++ b/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java @@ -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> sync() { + return ResponseEntity.ok(ApiResponse.success(syncService.sync())); + } +} diff --git a/src/main/java/com/finance/system/controller/FeishuAuthController.java b/src/main/java/com/finance/system/controller/FeishuAuthController.java index 9a8bdd9..0e37614 100644 --- a/src/main/java/com/finance/system/controller/FeishuAuthController.java +++ b/src/main/java/com/finance/system/controller/FeishuAuthController.java @@ -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 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> 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 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> processWebhookEvent( String eventId, Map 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> 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> getApprovalNodes() { try { java.util.List 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> 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> getApprovalTimelineByApplication( @PathVariable Long applicationId) { + reimApplicationService.getApplicationDetail(applicationId, AuditUtil.getCurrentUserId()); try { java.util.List 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, "获取审批进度失败,请稍后重试")); } } } diff --git a/src/main/java/com/finance/system/controller/FeishuCallbackController.java b/src/main/java/com/finance/system/controller/FeishuCallbackController.java index 53152d4..803c448 100644 --- a/src/main/java/com/finance/system/controller/FeishuCallbackController.java +++ b/src/main/java/com/finance/system/controller/FeishuCallbackController.java @@ -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(); } diff --git a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java index 7f0db76..a299e95 100644 --- a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java +++ b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java @@ -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> 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> 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> organization() { return ApiResponse.success(directory.organization()); } diff --git a/src/main/java/com/finance/system/controller/IntegrationConfigController.java b/src/main/java/com/finance/system/controller/IntegrationConfigController.java index f8b08ad..f32d0c9 100644 --- a/src/main/java/com/finance/system/controller/IntegrationConfigController.java +++ b/src/main/java/com/finance/system/controller/IntegrationConfigController.java @@ -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>> 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> put(@RequestBody Map 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>> test(@RequestBody Map body) { Object provider = body == null ? null : body.get("provider"); return ResponseEntity.ok(ApiResponse.success(service.test(provider == null ? null : String.valueOf(provider)))); } diff --git a/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java b/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java new file mode 100644 index 0000000..a2d2604 --- /dev/null +++ b/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java @@ -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>>> list() { + return ResponseEntity.ok(ApiResponse.success(service.list())); + } + + @PostMapping + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.create')") + public ResponseEntity>> create(@RequestBody KingdeeSyncConfigService.ConfigRequest request) { + return ResponseEntity.ok(ApiResponse.success(service.create(request))); + } + + @GetMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + public ResponseEntity>> 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>> 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> 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>> 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>> 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>> sync(@PathVariable Long id) { + return ResponseEntity.ok(ApiResponse.success(service.sync(id))); + } + + @GetMapping("/{id}/runs") + @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + public ResponseEntity>>> runs(@PathVariable Long id) { + return ResponseEntity.ok(ApiResponse.success(service.runs(id))); + } +} diff --git a/src/main/java/com/finance/system/controller/LogController.java b/src/main/java/com/finance/system/controller/LogController.java index 5f94c55..0cb7c97 100644 --- a/src/main/java/com/finance/system/controller/LogController.java +++ b/src/main/java/com/finance/system/controller/LogController.java @@ -62,7 +62,7 @@ public class LogController { * 获取操作日志列表 */ @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.operation-log')") public ResponseEntity>>> listLogs( @RequestParam(required = false) String category, @RequestParam(required = false) String operator, diff --git a/src/main/java/com/finance/system/controller/MetadataController.java b/src/main/java/com/finance/system/controller/MetadataController.java index 421ac2e..b0875c6 100644 --- a/src/main/java/com/finance/system/controller/MetadataController.java +++ b/src/main/java/com/finance/system/controller/MetadataController.java @@ -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>>> 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>>> getPayees( @RequestParam(required = false) String keyword) { try { diff --git a/src/main/java/com/finance/system/controller/PaymentController.java b/src/main/java/com/finance/system/controller/PaymentController.java index 69e9bbb..49fcf72 100644 --- a/src/main/java/com/finance/system/controller/PaymentController.java +++ b/src/main/java/com/finance/system/controller/PaymentController.java @@ -114,7 +114,7 @@ public class PaymentController { * 获取付款列表(资金出纳B视图,过滤 expenseType=员工报销类) */ @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'payment:register')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") public ResponseEntity>> 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>> registerPayment(@RequestBody Map request) { try { UserPrincipal principal = AuditUtil.getCurrentUser(); diff --git a/src/main/java/com/finance/system/controller/ReimApplicationController.java b/src/main/java/com/finance/system/controller/ReimApplicationController.java index 9ed6566..380870c 100644 --- a/src/main/java/com/finance/system/controller/ReimApplicationController.java +++ b/src/main/java/com/finance/system/controller/ReimApplicationController.java @@ -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> 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>> 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> 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> 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> 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> 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> submit(@PathVariable Long id) { + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.submit')") + public ResponseEntity> 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> 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>> 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> 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> delete(@PathVariable Long id) { reimApplicationService.deleteApplication(id, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); diff --git a/src/main/java/com/finance/system/controller/RoleController.java b/src/main/java/com/finance/system/controller/RoleController.java index 2407143..c21efbe 100644 --- a/src/main/java/com/finance/system/controller/RoleController.java +++ b/src/main/java/com/finance/system/controller/RoleController.java @@ -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> ROLE_PROFILES = new ArrayList<>(); static { @@ -52,42 +52,44 @@ public class RoleController { String userType = RoleService.normalize(user.getUserType()); Map 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 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 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>>> 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>> create(@RequestBody Map 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>> update(@PathVariable Long id, @RequestBody Map 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> 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>>> 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>> 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> setPermissions(@PathVariable Long id, @RequestBody Map 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 findProfile(String code) { for (Map 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 toMap(SysRole role) { Map 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; } } diff --git a/src/main/java/com/finance/system/controller/ScheduledTaskController.java b/src/main/java/com/finance/system/controller/ScheduledTaskController.java new file mode 100644 index 0000000..7a5fed4 --- /dev/null +++ b/src/main/java/com/finance/system/controller/ScheduledTaskController.java @@ -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() { + return ApiResponse.success(service.list()); + } + + @GetMapping("/{code}") + @PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')") + public ApiResponse> detail(@PathVariable String code) { + return ApiResponse.success(service.detail(code)); + } + + @PutMapping("/{code}/schedule") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.scheduled-task.config.update')") + public ApiResponse> 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> 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> runs(@PathVariable String code, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ApiResponse.success(service.runs(code, page, size)); + } +} diff --git a/src/main/java/com/finance/system/controller/SourceDocumentController.java b/src/main/java/com/finance/system/controller/SourceDocumentController.java index bbf425b..36d8f83 100644 --- a/src/main/java/com/finance/system/controller/SourceDocumentController.java +++ b/src/main/java/com/finance/system/controller/SourceDocumentController.java @@ -129,7 +129,7 @@ public class SourceDocumentController { * 获取业务单据列表 */ @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.source-documents')") public ResponseEntity>>> 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>> getSourceDetail(@PathVariable Long id) { try { Map source = MOCK_SOURCES.stream() diff --git a/src/main/java/com/finance/system/controller/UserGroupController.java b/src/main/java/com/finance/system/controller/UserGroupController.java index fa0c039..2ee88bc 100644 --- a/src/main/java/com/finance/system/controller/UserGroupController.java +++ b/src/main/java/com/finance/system/controller/UserGroupController.java @@ -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>>> 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>> create(@RequestBody Map 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>> update(@PathVariable Long id, @RequestBody Map 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> 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>> roles(@PathVariable Long id) { Map 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> setRoles(@PathVariable Long id, @RequestBody Map 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>> members(@PathVariable Long id) { - Map 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> setMembers(@PathVariable Long id, @RequestBody Map body) { - roleService.replaceGroupMembers(id, requiredList(body, "userIds"), AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind')") + public ResponseEntity>> setMembers(@PathVariable Long id, + @RequestBody Map body) { + List userIds = requiredLongList(body, "userIds"); + List expectedUserIds = requiredLongList(body, "expectedUserIds"); + List identities = requiredDirectoryIdentities(body, "directoryIdentities"); + if (userIds.size() + identities.size() > MAX_MEMBER_IDS) + throw new com.finance.system.exception.BadRequestException("提交的最终成员数量不能超过5000"); + List committed = roleService.replaceGroupMembers(id, userIds, identities, + expectedUserIds, AuditUtil.getCurrentUserId()); + Map result = new LinkedHashMap<>(); + result.put("userIds", committed); + return ResponseEntity.ok(ApiResponse.success(result)); } @GetMapping("/candidates") - @PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')") - public ResponseEntity>>> 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>>> 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> 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>>> candidates(Long groupId) { + return ResponseEntity.ok(ApiResponse.success(roleService.candidates(groupId))); + } @SuppressWarnings("unchecked") private List requiredList(Map body, String key) { @@ -72,8 +108,64 @@ public class UserGroupController { return (List) value; } - private Map groupMap(SysUserGroup group) { - Map 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 requiredLongList(Map body, String key) { + List values = requiredList(body, key); + if (values.size() > MAX_MEMBER_IDS) + throw new com.finance.system.exception.BadRequestException(key + " 数量不能超过5000"); + List result = new ArrayList<>(); + Set 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 requiredDirectoryIdentities(Map body, String key) { + List values = requiredList(body, key); + if (values.size() > MAX_DIRECTORY_IDENTITIES) + throw new com.finance.system.exception.BadRequestException(key + " 数量不能超过200"); + List result = new ArrayList<>(); + Set 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; + } + } diff --git a/src/main/java/com/finance/system/dto/DirectoryIdentityDto.java b/src/main/java/com/finance/system/dto/DirectoryIdentityDto.java new file mode 100644 index 0000000..c56bff1 --- /dev/null +++ b/src/main/java/com/finance/system/dto/DirectoryIdentityDto.java @@ -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); } +} diff --git a/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java b/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java new file mode 100644 index 0000000..838ff2b --- /dev/null +++ b/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java @@ -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; +} diff --git a/src/main/java/com/finance/system/dto/MemberCandidateDto.java b/src/main/java/com/finance/system/dto/MemberCandidateDto.java new file mode 100644 index 0000000..728166f --- /dev/null +++ b/src/main/java/com/finance/system/dto/MemberCandidateDto.java @@ -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 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 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 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.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 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; } +} diff --git a/src/main/java/com/finance/system/dto/MemberCandidatesResponse.java b/src/main/java/com/finance/system/dto/MemberCandidatesResponse.java new file mode 100644 index 0000000..7ae9ca1 --- /dev/null +++ b/src/main/java/com/finance/system/dto/MemberCandidatesResponse.java @@ -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 currentMembers; + private final List matches; + private final int limit; + private final boolean truncated; + private final boolean blockedMatchesPresent; + + public MemberCandidatesResponse(String snapshotState, List currentMembers, + List 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 currentMembers, List 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 immutable(List value) { + return Collections.unmodifiableList(new ArrayList<>(value == null + ? Collections.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 getCurrentMembers() { return currentMembers; } + public List getMatches() { return matches; } + public int getLimit() { return limit; } + public boolean isTruncated() { return truncated; } + public boolean isBlockedMatchesPresent() { return blockedMatchesPresent; } +} diff --git a/src/main/java/com/finance/system/dto/RoutePreviewDto.java b/src/main/java/com/finance/system/dto/RoutePreviewDto.java new file mode 100644 index 0000000..5486cbe --- /dev/null +++ b/src/main/java/com/finance/system/dto/RoutePreviewDto.java @@ -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 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 approverLabels; + private boolean dynamic; + } +} diff --git a/src/main/java/com/finance/system/dto/RouteTimelineNodeDto.java b/src/main/java/com/finance/system/dto/RouteTimelineNodeDto.java new file mode 100644 index 0000000..99034c4 --- /dev/null +++ b/src/main/java/com/finance/system/dto/RouteTimelineNodeDto.java @@ -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; +} diff --git a/src/main/java/com/finance/system/dto/ScheduledTaskRunDto.java b/src/main/java/com/finance/system/dto/ScheduledTaskRunDto.java new file mode 100644 index 0000000..a3b7a38 --- /dev/null +++ b/src/main/java/com/finance/system/dto/ScheduledTaskRunDto.java @@ -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; + } +} diff --git a/src/main/java/com/finance/system/dto/SubmitApplicationRequest.java b/src/main/java/com/finance/system/dto/SubmitApplicationRequest.java new file mode 100644 index 0000000..2cdd35d --- /dev/null +++ b/src/main/java/com/finance/system/dto/SubmitApplicationRequest.java @@ -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; +} diff --git a/src/main/java/com/finance/system/dto/UserProfile.java b/src/main/java/com/finance/system/dto/UserProfile.java index 3c38bb0..89471ab 100644 --- a/src/main/java/com/finance/system/dto/UserProfile.java +++ b/src/main/java/com/finance/system/dto/UserProfile.java @@ -25,4 +25,6 @@ public class UserProfile { private String lastLoginAt; private List roleCodes; private List groupNames; + /** True only for a currently active recovery or group-authorized super administrator. */ + private Boolean isSuperAdmin; } diff --git a/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionApprover.java b/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionApprover.java new file mode 100644 index 0000000..fe6394a --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionApprover.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionNode.java b/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionNode.java new file mode 100644 index 0000000..58b3993 --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionNode.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionSnapshot.java b/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionSnapshot.java new file mode 100644 index 0000000..54cdd54 --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuApprovalDefinitionSnapshot.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/FeishuDefinitionSyncFence.java b/src/main/java/com/finance/system/entity/FeishuDefinitionSyncFence.java new file mode 100644 index 0000000..1adc1ed --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuDefinitionSyncFence.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/FeishuDirectoryState.java b/src/main/java/com/finance/system/entity/FeishuDirectoryState.java deleted file mode 100644 index 8994ad7..0000000 --- a/src/main/java/com/finance/system/entity/FeishuDirectoryState.java +++ /dev/null @@ -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; } -} diff --git a/src/main/java/com/finance/system/entity/FeishuInstanceTimelineNode.java b/src/main/java/com/finance/system/entity/FeishuInstanceTimelineNode.java new file mode 100644 index 0000000..90c3277 --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuInstanceTimelineNode.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/IntFeishuApproval.java b/src/main/java/com/finance/system/entity/IntFeishuApproval.java index c6cbd74..d5466dd 100644 --- a/src/main/java/com/finance/system/entity/IntFeishuApproval.java +++ b/src/main/java/com/finance/system/entity/IntFeishuApproval.java @@ -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; diff --git a/src/main/java/com/finance/system/entity/IntFeishuApprovalAttempt.java b/src/main/java/com/finance/system/entity/IntFeishuApprovalAttempt.java new file mode 100644 index 0000000..4be584c --- /dev/null +++ b/src/main/java/com/finance/system/entity/IntFeishuApprovalAttempt.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/ReimRoutePreviewToken.java b/src/main/java/com/finance/system/entity/ReimRoutePreviewToken.java new file mode 100644 index 0000000..2864cbc --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimRoutePreviewToken.java @@ -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; +} diff --git a/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java b/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java new file mode 100644 index 0000000..3cf6808 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java @@ -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(); } +} diff --git a/src/main/java/com/finance/system/entity/SysKingdeeSyncField.java b/src/main/java/com/finance/system/entity/SysKingdeeSyncField.java new file mode 100644 index 0000000..24b04d9 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysKingdeeSyncField.java @@ -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(); } +} diff --git a/src/main/java/com/finance/system/entity/SysKingdeeSyncFilter.java b/src/main/java/com/finance/system/entity/SysKingdeeSyncFilter.java new file mode 100644 index 0000000..a1779fb --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysKingdeeSyncFilter.java @@ -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(); } +} diff --git a/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java b/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java new file mode 100644 index 0000000..fbeeb79 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java @@ -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(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysUserGroup.java b/src/main/java/com/finance/system/entity/SysUserGroup.java index 4e92a8e..9a2b5aa 100644 --- a/src/main/java/com/finance/system/entity/SysUserGroup.java +++ b/src/main/java/com/finance/system/entity/SysUserGroup.java @@ -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(); } } diff --git a/src/main/java/com/finance/system/entity/SysUserGroupMember.java b/src/main/java/com/finance/system/entity/SysUserGroupMember.java index c977d2d..54638b3 100644 --- a/src/main/java/com/finance/system/entity/SysUserGroupMember.java +++ b/src/main/java/com/finance/system/entity/SysUserGroupMember.java @@ -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); } diff --git a/src/main/java/com/finance/system/entity/SysWebhookEvent.java b/src/main/java/com/finance/system/entity/SysWebhookEvent.java index 8b6fb48..d63f0ec 100644 --- a/src/main/java/com/finance/system/entity/SysWebhookEvent.java +++ b/src/main/java/com/finance/system/entity/SysWebhookEvent.java @@ -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) { diff --git a/src/main/java/com/finance/system/exception/FeishuCreateOutcomeUnknownException.java b/src/main/java/com/finance/system/exception/FeishuCreateOutcomeUnknownException.java new file mode 100644 index 0000000..85151e2 --- /dev/null +++ b/src/main/java/com/finance/system/exception/FeishuCreateOutcomeUnknownException.java @@ -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); } +} diff --git a/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java b/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java index edd1aae..e8173b3 100644 --- a/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java @@ -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> handleUnreadableBody(HttpMessageNotReadableException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(400, "请求体不能为空或格式不正确")); + } + + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity> handleDataIntegrityViolation(DataIntegrityViolationException e) { + log.warn("Database constraint conflict"); + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(ApiResponse.error(409, "数据冲突,请刷新后重试")); + } + @ExceptionHandler(Exception.class) public ResponseEntity> handleGeneral(Exception e) { log.error("Unexpected error", e); diff --git a/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionApproverRepository.java b/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionApproverRepository.java new file mode 100644 index 0000000..9b77dc3 --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionApproverRepository.java @@ -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 { + List findByNodeIdOrderByApproverOrderAsc(Long nodeId); + void deleteByNodeIdIn(List nodeIds); +} diff --git a/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionNodeRepository.java b/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionNodeRepository.java new file mode 100644 index 0000000..695f8fd --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionNodeRepository.java @@ -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 { + List findBySnapshotIdOrderByNodeOrderAsc(Long snapshotId); + void deleteBySnapshotId(Long snapshotId); +} diff --git a/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionSnapshotRepository.java b/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionSnapshotRepository.java new file mode 100644 index 0000000..3a8ab9f --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuApprovalDefinitionSnapshotRepository.java @@ -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 { + @Lock(LockModeType.PESSIMISTIC_READ) + @Query("select s from FeishuApprovalDefinitionSnapshot s where s.id = :id") + Optional findByIdForRouteValidation(@Param("id") Long id); +} diff --git a/src/main/java/com/finance/system/repository/FeishuDefinitionSyncFenceRepository.java b/src/main/java/com/finance/system/repository/FeishuDefinitionSyncFenceRepository.java new file mode 100644 index 0000000..f79aa6c --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuDefinitionSyncFenceRepository.java @@ -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 { + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select f from FeishuDefinitionSyncFence f where f.id=:id") + Optional findByIdForUpdate(@Param("id") Long id); +} diff --git a/src/main/java/com/finance/system/repository/FeishuInstanceTimelineNodeRepository.java b/src/main/java/com/finance/system/repository/FeishuInstanceTimelineNodeRepository.java new file mode 100644 index 0000000..1303357 --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuInstanceTimelineNodeRepository.java @@ -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 { + Optional findByFeishuApprovalIdAndInstanceCodeAndTimelineKey(Long approvalId, String instanceCode, String timelineKey); + Optional findFirstByFeishuApprovalIdAndInstanceCodeAndNodeKeyOrderByIdAsc(Long approvalId, String instanceCode, String nodeKey); + Optional findByFeishuApprovalIdAndInstanceCodeAndTaskId(Long approvalId, String instanceCode, String taskId); + List findByFeishuApprovalIdAndInstanceCodeOrderByNodeOrderAscIdAsc(Long approvalId, String instanceCode); +} diff --git a/src/main/java/com/finance/system/repository/IntFeishuApprovalAttemptRepository.java b/src/main/java/com/finance/system/repository/IntFeishuApprovalAttemptRepository.java new file mode 100644 index 0000000..4a87049 --- /dev/null +++ b/src/main/java/com/finance/system/repository/IntFeishuApprovalAttemptRepository.java @@ -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 { + Optional findByInstanceCode(String instanceCode); + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select a from IntFeishuApprovalAttempt a where a.instanceCode=:instanceCode") + Optional findByInstanceCodeForUpdate(@Param("instanceCode") String instanceCode); +} diff --git a/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java b/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java index bb48ce9..972e872 100644 --- a/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java +++ b/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java @@ -19,4 +19,8 @@ public interface IntFeishuApprovalRepository extends JpaRepository findByFeishuInstanceCodeForUpdate(@Param("instanceCode") String instanceCode); Optional findByApplicationId(Long applicationId); + + @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("select a from IntFeishuApproval a where a.applicationId = :applicationId") + Optional findByApplicationIdForUpdate(@Param("applicationId") Long applicationId); } diff --git a/src/main/java/com/finance/system/repository/ReimRoutePreviewTokenRepository.java b/src/main/java/com/finance/system/repository/ReimRoutePreviewTokenRepository.java new file mode 100644 index 0000000..4b0e35e --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimRoutePreviewTokenRepository.java @@ -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 { + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select t from ReimRoutePreviewToken t where t.tokenHash = :hash") + Optional 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 findCleanupIds(@Param("now") LocalDateTime now, Pageable pageable); + @Modifying + @Query("delete from ReimRoutePreviewToken t where t.id in :ids") + int deleteCleanupIds(@Param("ids") List ids); +} diff --git a/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java b/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java new file mode 100644 index 0000000..279c315 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java @@ -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 { + boolean existsByTargetTableName(String targetTableName); + boolean existsByTargetTableNameAndIdNot(String targetTableName, Long id); + Optional findByTargetTableName(String targetTableName); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select c from SysKingdeeSyncConfig c where c.id = :id") + Optional findByIdForUpdate(@Param("id") Long id); +} diff --git a/src/main/java/com/finance/system/repository/SysKingdeeSyncFieldRepository.java b/src/main/java/com/finance/system/repository/SysKingdeeSyncFieldRepository.java new file mode 100644 index 0000000..ba03063 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysKingdeeSyncFieldRepository.java @@ -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 { + List findByConfigIdOrderBySortOrderAscIdAsc(Long configId); + void deleteByConfigId(Long configId); +} diff --git a/src/main/java/com/finance/system/repository/SysKingdeeSyncFilterRepository.java b/src/main/java/com/finance/system/repository/SysKingdeeSyncFilterRepository.java new file mode 100644 index 0000000..8267cd7 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysKingdeeSyncFilterRepository.java @@ -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 { + List findByConfigIdOrderBySortOrderAscIdAsc(Long configId); + void deleteByConfigId(Long configId); +} diff --git a/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java b/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java new file mode 100644 index 0000000..86b074b --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java @@ -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 { + List findTop100ByConfigIdOrderByStartedAtDescIdDesc(Long configId); + Optional findFirstByConfigIdAndStatusOrderByStartedAtDesc(Long configId, String status); + void deleteByConfigId(Long configId); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select r from SysKingdeeSyncRun r where r.id = :id") + Optional 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); +} diff --git a/src/main/java/com/finance/system/repository/SysRoleRepository.java b/src/main/java/com/finance/system/repository/SysRoleRepository.java index 431f96a..d54dbb2 100644 --- a/src/main/java/com/finance/system/repository/SysRoleRepository.java +++ b/src/main/java/com/finance/system/repository/SysRoleRepository.java @@ -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 { Optional findByRoleCode(String roleCode); + @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("select r from SysRole r where r.roleCode = :roleCode") + Optional findByRoleCodeForUpdate(@Param("roleCode") String roleCode); boolean existsByRoleCode(String roleCode); } diff --git a/src/main/java/com/finance/system/repository/SysUserGroupMemberRepository.java b/src/main/java/com/finance/system/repository/SysUserGroupMemberRepository.java index f4087ec..95b3f4e 100644 --- a/src/main/java/com/finance/system/repository/SysUserGroupMemberRepository.java +++ b/src/main/java/com/finance/system/repository/SysUserGroupMemberRepository.java @@ -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 { List findByIdGroupId(Long groupId); List findByIdUserId(Long userId); + List findByIdUserIdIn(Collection userIds); + boolean existsByIdUserId(Long userId); void deleteByIdGroupId(Long groupId); void deleteByIdUserId(Long userId); } diff --git a/src/main/java/com/finance/system/repository/SysUserGroupRepository.java b/src/main/java/com/finance/system/repository/SysUserGroupRepository.java index 17ad7d6..83ea4d2 100644 --- a/src/main/java/com/finance/system/repository/SysUserGroupRepository.java +++ b/src/main/java/com/finance/system/repository/SysUserGroupRepository.java @@ -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 { Optional findByGroupCode(String groupCode); + @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("select g from SysUserGroup g where g.id = :id") + Optional findByIdForUpdate(@Param("id") Long id); boolean existsByGroupCode(String groupCode); } diff --git a/src/main/java/com/finance/system/repository/SysUserRepository.java b/src/main/java/com/finance/system/repository/SysUserRepository.java index b8c35d8..1d848ae 100644 --- a/src/main/java/com/finance/system/repository/SysUserRepository.java +++ b/src/main/java/com/finance/system/repository/SysUserRepository.java @@ -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 { @@ -16,4 +20,8 @@ public interface SysUserRepository extends JpaRepository { SysUser findByEmployeeNo(String employeeNo); List findByUserType(String userType); -} \ No newline at end of file + + @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("select u from SysUser u where u.id = :id") + Optional findByIdForUpdate(@Param("id") Long id); +} diff --git a/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java b/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java index f400947..ccc9a80 100644 --- a/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java +++ b/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java @@ -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); } diff --git a/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java b/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java index d22d70b..26d4f0e 100644 --- a/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java +++ b/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java @@ -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 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); } } diff --git a/src/main/java/com/finance/system/security/PermissionChecker.java b/src/main/java/com/finance/system/security/PermissionChecker.java index f556063..6ca893a 100644 --- a/src/main/java/com/finance/system/security/PermissionChecker.java +++ b/src/main/java/com/finance/system/security/PermissionChecker.java @@ -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; + } } } diff --git a/src/main/java/com/finance/system/security/UserPrincipal.java b/src/main/java/com/finance/system/security/UserPrincipal.java index a3be5bc..33dd0bb 100644 --- a/src/main/java/com/finance/system/security/UserPrincipal.java +++ b/src/main/java/com/finance/system/security/UserPrincipal.java @@ -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 getAuthorities() { - return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + RoleService.normalize(userType))); + return Collections.emptyList(); } @Override diff --git a/src/main/java/com/finance/system/service/FeishuWebhookInboxService.java b/src/main/java/com/finance/system/service/FeishuWebhookInboxService.java new file mode 100644 index 0000000..868ce24 --- /dev/null +++ b/src/main/java/com/finance/system/service/FeishuWebhookInboxService.java @@ -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);});} +} diff --git a/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java b/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java new file mode 100644 index 0000000..9cd0b15 --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java @@ -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 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> 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 fields = fieldRepository.findByConfigIdOrderBySortOrderAscIdAsc(configId); + List 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 runMap(SysKingdeeSyncRun run) { + Map 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; + } + } +} diff --git a/src/main/java/com/finance/system/service/KingdeeDocumentSyncService.java b/src/main/java/com/finance/system/service/KingdeeDocumentSyncService.java new file mode 100644 index 0000000..46701b4 --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeDocumentSyncService.java @@ -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 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 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> 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 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 prepareTable(KingdeeSyncConfigService.Aggregate aggregate) { + return prepareTable(aggregate, null); + } + + private Map 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 prepareTableLocked(String table, SysKingdeeSyncConfig config, + List fields) throws SQLException { + Map 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 result = new LinkedHashMap<>(); + result.put("tableName", table); result.put("created", created); result.put("columnCount", columns.size()); + return result; + } + + T withDdlLock(String table, Runnable leaseCheck, DdlOperation operation) { + String lockName = "finance:kingdee-ddl:" + shortHash(table); + return jdbc.execute((ConnectionCallback) 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 declaredColumns(List fields) { + Map 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> 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 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 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 fields, Map row) { + String table = identifier(rawTable); + String sourceKey = buildDeterministicSourceKey(formId, fields, row); + if (sourceKey.length() > 255) throw new IllegalArgumentException("来源主键长度超过255"); + List 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 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 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 row, String key) { + if (row == null) return null; + if (row.containsKey(key)) return row.get(key); + for (Map.Entry 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 fields, + Map 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 row, String key) { + if (row == null) return null; + if (row.containsKey(key)) return row.get(key); + for (Map.Entry 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 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 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 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 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 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 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 sizes = new HashMap<>(); + Map 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 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 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 execute() throws SQLException; + } + + private Map runMap(SysKingdeeSyncRun run) { + Map 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; + } + } +} diff --git a/src/main/java/com/finance/system/service/KingdeeFencedRowWriteService.java b/src/main/java/com/finance/system/service/KingdeeFencedRowWriteService.java new file mode 100644 index 0000000..b63ebef --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeFencedRowWriteService.java @@ -0,0 +1,106 @@ +package com.finance.system.service; + +import com.finance.system.repository.SysKingdeeSyncRunRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.Duration; +import java.util.function.Supplier; + +/** Owns the short transaction which fences and accounts for one target-table row write. */ +@Service +public class KingdeeFencedRowWriteService { + static final Duration LEASE_DURATION = Duration.ofSeconds(90); + + private final SysKingdeeSyncRunRepository runRepository; + private final TransactionTemplate transaction; + private final TransactionTemplate renewalTransaction; + + public KingdeeFencedRowWriteService(SysKingdeeSyncRunRepository runRepository, + PlatformTransactionManager transactionManager) { + this.runRepository = runRepository; + this.transaction = new TransactionTemplate(transactionManager); + this.transaction.setTimeout(30); + this.renewalTransaction = new TransactionTemplate(transactionManager); + this.renewalTransaction.setTimeout(5); + } + + public boolean renewLease(Long runId, String token) { + Boolean renewed = renewalTransaction.execute(status -> runRepository.renewLease(runId, token) == 1); + return Boolean.TRUE.equals(renewed); + } + + public WriteResult write(Long runId, String token, RowOperation operation) { + try { + WriteResult result = transaction.execute(status -> { + lockAndVerify(runId, token); + final int affected; + try { + affected = operation.execute(); + } catch (RuntimeException rowFailure) { + // Let TransactionTemplate roll the target-table transaction + // back before attempting to account for the failed row. + throw new RowOperationException(rowFailure); + } + WriteResult writeResult; + if (affected == 1) { + writeResult = WriteResult.INSERTED; + } else { + writeResult = WriteResult.UPDATED; + } + int progress = runRepository.incrementSuccessIfValid(runId, token, + affected == 1 ? 1 : 0, affected == 1 ? 0 : 1); + if (progress != 1) throw new KingdeeSyncFenceException(); + return writeResult; + }); + if (result == null) throw new KingdeeSyncFenceException(); + return result; + } catch (RowOperationException rowFailure) { + return recordFailedRow(runId, token); + } + } + + public T executeFenced(Long runId, String token, Supplier operation) { + T result = transaction.execute(status -> { + lockAndVerify(runId, token); + T operationResult = operation.get(); + if (runRepository.countValidFence(runId, token) != 1) throw new KingdeeSyncFenceException(); + return operationResult; + }); + if (result == null) throw new KingdeeSyncFenceException(); + return result; + } + + private WriteResult recordFailedRow(Long runId, String token) { + WriteResult result = transaction.execute(status -> { + if (runRepository.incrementFailureIfValid(runId, token) != 1) + throw new KingdeeSyncFenceException(); + return WriteResult.FAILED; + }); + if (result == null) throw new KingdeeSyncFenceException(); + return result; + } + + private void lockAndVerify(Long runId, String token) { + runRepository.findByIdForUpdate(runId) + .orElseThrow(KingdeeSyncFenceException::new); + if (token == null || runRepository.countValidFence(runId, token) != 1) + throw new KingdeeSyncFenceException(); + } + + private static class RowOperationException extends RuntimeException { + private RowOperationException(RuntimeException cause) { super(cause); } + } + + @FunctionalInterface + public interface RowOperation { + int execute(); + } + + public enum WriteResult { INSERTED, UPDATED, FAILED } + + public static class KingdeeSyncFenceException extends RuntimeException { + public KingdeeSyncFenceException() { super("Kingdee sync worker lease is no longer valid"); } + } +} diff --git a/src/main/java/com/finance/system/service/KingdeeFilterCompiler.java b/src/main/java/com/finance/system/service/KingdeeFilterCompiler.java new file mode 100644 index 0000000..330c1f4 --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeFilterCompiler.java @@ -0,0 +1,87 @@ +package com.finance.system.service; + +import com.finance.system.entity.SysKingdeeSyncFilter; +import com.finance.system.exception.BadRequestException; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Pattern; + +/** Converts structured filter data to the small, non-SQL Kingdee filter language. */ +@Service +public class KingdeeFilterCompiler { + public static final int MAX_FILTER_STRING_LENGTH = 3500; + private static final Pattern SOURCE_KEY = Pattern.compile("[A-Za-z_][A-Za-z0-9_.]*"); + private static final Set OPERATORS = Collections.unmodifiableSet(new HashSet(Arrays.asList( + "EQ", "NE", "GT", "GE", "LT", "LE", "LIKE", "IN"))); + + public String compile(Collection filters) { + if (filters == null || filters.isEmpty()) return ""; + List ordered = new ArrayList<>(filters); + for (SysKingdeeSyncFilter filter : ordered) + if (filter == null) throw new BadRequestException("过滤条件不能为空"); + Collections.sort(ordered, Comparator.comparingInt(f -> f.getSortOrder() == null ? 0 : f.getSortOrder())); + List expressions = new ArrayList<>(); + for (SysKingdeeSyncFilter filter : ordered) { + String field = text(filter.getSourceFieldKey()); + if (!SOURCE_KEY.matcher(field).matches()) throw new BadRequestException("过滤字段标识不安全"); + String operator = text(filter.getOperator()).toUpperCase(Locale.ROOT); + if (!OPERATORS.contains(operator)) throw new BadRequestException("不支持的过滤操作符: " + operator); + String value = filter.getFilterValue(); + if (!StringUtils.hasText(value)) throw new BadRequestException("过滤值不能为空"); + if ("IN".equals(operator)) { + List values = new ArrayList<>(); + for (String item : value.split(",", -1)) { + if (!StringUtils.hasText(item)) throw new BadRequestException("IN 过滤值不能包含空项"); + values.add(field + " = '" + escape(item.trim()) + "'"); + } + expressions.add("(" + join(values, " OR ") + ")"); + } else { + String filterValue = "LIKE".equals(operator) ? "*" + value + "*" : value; + expressions.add(field + " " + symbol(operator) + " '" + escape(filterValue) + "'"); + } + } + String compiled = join(expressions, " AND "); + if (compiled.length() > MAX_FILTER_STRING_LENGTH) + throw new BadRequestException("过滤条件生成结果过长,不能超过" + MAX_FILTER_STRING_LENGTH + "个字符"); + return compiled; + } + + public String compile(List filters) { + return compile((Collection) filters); + } + + public static boolean isSafeSourceField(String value) { + return value != null && SOURCE_KEY.matcher(value).matches(); + } + + private String symbol(String operator) { + if ("EQ".equals(operator)) return "="; + if ("NE".equals(operator)) return "<>"; + if ("GT".equals(operator)) return ">"; + if ("GE".equals(operator)) return ">="; + if ("LT".equals(operator)) return "<"; + if ("LE".equals(operator)) return "<="; + return "LIKE"; + } + + private String escape(String value) { return value.replace("'", "''"); } + private String text(String value) { return value == null ? "" : value.trim(); } + private String join(List values, String separator) { + StringBuilder result = new StringBuilder(); + for (String value : values) { + if (result.length() > 0) result.append(separator); + result.append(value); + } + return result.toString(); + } +} diff --git a/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java b/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java new file mode 100644 index 0000000..0da46df --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java @@ -0,0 +1,332 @@ +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.BadRequestException; +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +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; + +@Service +public class KingdeeSyncConfigService { + private static final Pattern FORM_ID = Pattern.compile("[A-Za-z0-9_.-]+", Pattern.CASE_INSENSITIVE); + private static final Pattern TABLE_NAME = Pattern.compile("[a-z][a-z0-9_]{0,62}"); + private static final Pattern COLUMN_NAME = TABLE_NAME; + private static final Set DATA_TYPES = new HashSet<>(Arrays.asList( + "STRING", "INTEGER", "BIGINT", "DECIMAL", "DATE", "DATETIME", "BOOLEAN", "JSON")); + + private final SysKingdeeSyncConfigRepository configRepository; + private final SysKingdeeSyncFieldRepository fieldRepository; + private final SysKingdeeSyncFilterRepository filterRepository; + private final SysKingdeeSyncRunRepository runRepository; + private final KingdeeDocumentSyncService documentSyncService; + private KingdeeAsyncSyncService asyncSyncService; + + public KingdeeSyncConfigService(SysKingdeeSyncConfigRepository configRepository, + SysKingdeeSyncFieldRepository fieldRepository, + SysKingdeeSyncFilterRepository filterRepository, + SysKingdeeSyncRunRepository runRepository, + KingdeeDocumentSyncService documentSyncService) { + this.configRepository = configRepository; + this.fieldRepository = fieldRepository; + this.filterRepository = filterRepository; + this.runRepository = runRepository; + this.documentSyncService = documentSyncService; + } + + @Autowired + public void setAsyncSyncService(KingdeeAsyncSyncService asyncSyncService) { + this.asyncSyncService = asyncSyncService; + } + + @Transactional(readOnly = true) + public List> list() { + List> result = new ArrayList<>(); + for (SysKingdeeSyncConfig config : configRepository.findAll()) result.add(toMap(config, true)); + return result; + } + + @Transactional(readOnly = true) + public Map get(Long id) { + return toMap(load(id), true); + } + + @Transactional + public Map create(ConfigRequest request) { + validate(request, null); + SysKingdeeSyncConfig config = new SysKingdeeSyncConfig(); + copyConfig(request, config); + try { + config = configRepository.saveAndFlush(config); + replaceChildren(config.getId(), request); + return toMap(config, true); + } catch (DataIntegrityViolationException e) { + throw new BusinessException("目标表名已被使用", 409); + } + } + + @Transactional + public Map update(Long id, ConfigRequest request) { + validate(request, id); + SysKingdeeSyncConfig config = loadForUpdate(id); + rejectActiveRun(id, "同步任务正在运行,不能修改配置"); + copyConfig(request, config); + try { + configRepository.saveAndFlush(config); + replaceChildren(id, request); + return toMap(config, true); + } catch (DataIntegrityViolationException e) { + throw new BusinessException("目标表名已被使用", 409); + } + } + + @Transactional + public void delete(Long id) { + SysKingdeeSyncConfig config = loadForUpdate(id); + rejectActiveRun(id, "同步任务正在运行,不能删除配置"); + runRepository.deleteByConfigId(config.getId()); + fieldRepository.deleteByConfigId(config.getId()); + filterRepository.deleteByConfigId(config.getId()); + configRepository.delete(config); + } + + public Map preview(Long id) { + return documentSyncService.preview(loadAggregate(id)); + } + + @Transactional + public Map prepareTable(Long id) { + Aggregate aggregate = loadAggregate(id, true); + rejectActiveRun(id, "同步任务正在运行,不能准备目标表"); + return documentSyncService.prepareTable(aggregate); + } + + public Map sync(Long id) { + if (asyncSyncService == null) throw new IllegalStateException("金蝶异步同步服务未初始化"); + return asyncSyncService.start(id); + } + + @Transactional(readOnly = true) + public List> runs(Long id) { + load(id); + List> result = new ArrayList<>(); + for (SysKingdeeSyncRun run : runRepository.findTop100ByConfigIdOrderByStartedAtDescIdDesc(id)) result.add(runMap(run)); + return result; + } + + /** Exposed for focused unit tests and for callers that validate before persistence. */ + public void validate(ConfigRequest request) { validate(request, null); } + + private void validate(ConfigRequest request, Long id) { + if (request == null) throw new BadRequestException("请求体不能为空"); + required(request.configName, "configName", 200); + text(request.formId, "formId", 120); + if (!FORM_ID.matcher(request.formId.trim()).matches()) throw new BadRequestException("formId 格式不安全"); + text(request.targetTableName, "targetTableName", 63); + String table = request.targetTableName.trim(); + if (!TABLE_NAME.matcher(table).matches() || table.startsWith("sys_") + || table.startsWith("pg_") || table.startsWith("flyway")) { + throw new BadRequestException("targetTableName 格式不安全或为保留名称"); + } + if (request.targetTableComment != null && request.targetTableComment.length() > 500) + throw new BadRequestException("targetTableComment 长度不能超过500"); + if (request.maxRowsPerRun != null && (request.maxRowsPerRun < 1 || request.maxRowsPerRun > 100000)) + throw new BadRequestException("maxRowsPerRun 必须在1到100000之间"); + if (configRepository.existsByTargetTableNameAndIdNot(table, id == null ? -1L : id)) + throw new BusinessException("目标表名已被使用", 409); + + if (request.fields == null || request.fields.isEmpty()) throw new BadRequestException("至少配置一个同步字段"); + if (request.fields.size() > 200) throw new BadRequestException("同步字段不能超过200个"); + Set sourceKeys = new HashSet<>(); + Set targetColumns = new HashSet<>(); + boolean hasBillNumber = false; + for (FieldRequest field : request.fields) { + if (field == null) throw new BadRequestException("同步字段不能为空"); + text(field.sourceFieldKey, "sourceFieldKey", 200); + text(field.targetColumnName, "targetColumnName", 63); + if (!KingdeeFilterCompiler.isSafeSourceField(field.sourceFieldKey.trim())) + throw new BadRequestException("sourceFieldKey 格式不安全"); + String column = field.targetColumnName.trim(); + if (!COLUMN_NAME.matcher(column).matches() || isReservedColumn(column)) + throw new BadRequestException("targetColumnName 格式不安全或为保留列"); + String source = field.sourceFieldKey.trim(); + if ("FBillNo".equalsIgnoreCase(source)) hasBillNumber = true; + if (!sourceKeys.add(source)) throw new BadRequestException("同步字段源标识重复: " + source); + if (!targetColumns.add(column)) throw new BadRequestException("同步字段目标列重复: " + column); + String type = upper(field.dataType); + if (!DATA_TYPES.contains(type)) throw new BadRequestException("不支持的数据类型: " + type); + if ("STRING".equals(type)) { + if (field.fieldLength == null) field.fieldLength = 200; + if (field.fieldLength < 1 || field.fieldLength > 10000) + throw new BadRequestException("STRING fieldLength 必须在1到10000之间"); + } else if (field.fieldLength != null) { + throw new BadRequestException("非 STRING 类型不能设置 fieldLength"); + } + if (field.fieldComment != null && field.fieldComment.length() > 500) + throw new BadRequestException("fieldComment 长度不能超过500"); + } + if (!hasBillNumber) throw new BadRequestException("同步字段必须包含不可变的 FBillNo 作为来源主键"); + if (request.filters != null && request.filters.size() > 50) throw new BadRequestException("过滤条件不能超过50个"); + for (FilterRequest filter : request.filters == null ? Collections.emptyList() : request.filters) { + if (filter == null) throw new BadRequestException("过滤条件不能为空"); + text(filter.sourceFieldKey, "sourceFieldKey", 200); + if (!KingdeeFilterCompiler.isSafeSourceField(filter.sourceFieldKey.trim())) + throw new BadRequestException("过滤字段标识不安全"); + String op = upper(filter.operator); + if (!KingdeeFilterCompilerOperators.contains(op)) throw new BadRequestException("不支持的过滤操作符: " + op); + if (!StringUtils.hasText(filter.filterValue)) throw new BadRequestException("过滤值不能为空"); + if (filter.filterValue.length() > 1000) throw new BadRequestException("filterValue 长度不能超过1000"); + } + } + + private static final Set KingdeeFilterCompilerOperators = new HashSet<>(Arrays.asList( + "EQ", "NE", "GT", "GE", "LT", "LE", "LIKE", "IN")); + + private boolean isReservedColumn(String value) { + return "_kd_id".equals(value) || "_kd_source_key".equals(value) || "_kd_synced_at".equals(value); + } + + private void copyConfig(ConfigRequest request, SysKingdeeSyncConfig config) { + config.setConfigName(request.configName.trim()); + config.setFormId(request.formId.trim()); + config.setTargetTableName(request.targetTableName.trim()); + config.setTargetTableComment(request.targetTableComment); + config.setEnabled(request.enabled == null ? Boolean.TRUE : request.enabled); + config.setMaxRowsPerRun(request.maxRowsPerRun == null ? 10000 : request.maxRowsPerRun); + } + + private void replaceChildren(Long id, ConfigRequest request) { + fieldRepository.deleteByConfigId(id); + filterRepository.deleteByConfigId(id); + List fields = new ArrayList<>(); + for (FieldRequest item : request.fields) { + fields.add(SysKingdeeSyncField.builder().configId(id).sourceFieldKey(item.sourceFieldKey.trim()) + .targetColumnName(item.targetColumnName.trim()).fieldComment(item.fieldComment) + .dataType(upper(item.dataType)).fieldLength("STRING".equals(upper(item.dataType)) ? item.fieldLength : null) + .sortOrder(item.sortOrder == null ? 0 : item.sortOrder).build()); + } + fieldRepository.saveAll(fields); + List filters = new ArrayList<>(); + if (request.filters != null) for (FilterRequest item : request.filters) { + filters.add(SysKingdeeSyncFilter.builder().configId(id).sourceFieldKey(item.sourceFieldKey.trim()) + .operator(upper(item.operator)).filterValue(item.filterValue).sortOrder(item.sortOrder == null ? 0 : item.sortOrder).build()); + } + filterRepository.saveAll(filters); + } + + private Aggregate loadAggregate(Long id) { return loadAggregate(id, false); } + + private Aggregate loadAggregate(Long id, boolean forUpdate) { + SysKingdeeSyncConfig config = forUpdate ? loadForUpdate(id) : load(id); + return new Aggregate(config, fieldRepository.findByConfigIdOrderBySortOrderAscIdAsc(id), + filterRepository.findByConfigIdOrderBySortOrderAscIdAsc(id)); + } + + private SysKingdeeSyncConfig load(Long id) { + if (id == null) throw new ResourceNotFoundException("金蝶同步配置不存在"); + return configRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + id)); + } + + private SysKingdeeSyncConfig loadForUpdate(Long id) { + if (id == null) throw new ResourceNotFoundException("金蝶同步配置不存在"); + return configRepository.findByIdForUpdate(id) + .orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + id)); + } + + private void rejectActiveRun(Long id, String message) { + if (runRepository.findFirstByConfigIdAndStatusOrderByStartedAtDesc(id, "RUNNING").isPresent()) + throw new BusinessException(message, 409); + } + + private Map toMap(SysKingdeeSyncConfig config, boolean children) { + Map result = new LinkedHashMap<>(); + result.put("id", config.getId()); result.put("configName", config.getConfigName()); + result.put("formId", config.getFormId()); result.put("targetTableName", config.getTargetTableName()); + result.put("targetTableComment", config.getTargetTableComment()); result.put("enabled", config.getEnabled()); + result.put("maxRowsPerRun", config.getMaxRowsPerRun()); result.put("createdAt", config.getCreatedAt()); + result.put("updatedAt", config.getUpdatedAt()); + if (children) { + List> fields = new ArrayList<>(); + for (SysKingdeeSyncField f : fieldRepository.findByConfigIdOrderBySortOrderAscIdAsc(config.getId())) { + Map item = new LinkedHashMap<>(); item.put("id", f.getId()); + item.put("sourceFieldKey", f.getSourceFieldKey()); item.put("targetColumnName", f.getTargetColumnName()); + item.put("fieldComment", f.getFieldComment()); item.put("dataType", f.getDataType()); + item.put("fieldLength", f.getFieldLength()); item.put("sortOrder", f.getSortOrder()); fields.add(item); + } + List> filters = new ArrayList<>(); + for (SysKingdeeSyncFilter f : filterRepository.findByConfigIdOrderBySortOrderAscIdAsc(config.getId())) { + Map item = new LinkedHashMap<>(); item.put("id", f.getId()); + item.put("sourceFieldKey", f.getSourceFieldKey()); item.put("operator", f.getOperator()); + item.put("filterValue", f.getFilterValue()); item.put("sortOrder", f.getSortOrder()); filters.add(item); + } + result.put("fields", fields); result.put("filters", filters); + } + return result; + } + + private Map runMap(SysKingdeeSyncRun run) { + Map 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 void required(String value, String name, int max) { text(value, name, max); } + private void text(String value, String name, int max) { + if (!StringUtils.hasText(value)) throw new BadRequestException(name + " 不能为空"); + if (value.trim().length() > max) throw new BadRequestException(name + " 长度不能超过" + max); + } + private String upper(String value) { return value == null ? "" : value.trim().toUpperCase(Locale.ROOT); } + + @Data @NoArgsConstructor @AllArgsConstructor + public static class ConfigRequest { + private String configName; private String formId; private String targetTableName; private String targetTableComment; + private Boolean enabled; private Integer maxRowsPerRun; private List fields; private List filters; + } + @Data @NoArgsConstructor @AllArgsConstructor + public static class FieldRequest { + private String sourceFieldKey; private String targetColumnName; private String fieldComment; + private String dataType; private Integer fieldLength; private Integer sortOrder; + } + @Data @NoArgsConstructor @AllArgsConstructor + public static class FilterRequest { + private String sourceFieldKey; private String operator; private String filterValue; private Integer sortOrder; + } + + public static class Aggregate { + private final SysKingdeeSyncConfig config; private final List fields; private final List filters; + public Aggregate(SysKingdeeSyncConfig config, List fields, List filters) { + this.config = config; this.fields = fields; this.filters = filters; + } + public SysKingdeeSyncConfig getConfig() { return config; } + public List getFields() { return fields; } + public List getFilters() { return filters; } + } +} diff --git a/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java b/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java new file mode 100644 index 0000000..38deff6 --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java @@ -0,0 +1,28 @@ +package com.finance.system.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class KingdeeSyncRunRecovery { + private final KingdeeSyncRunStateService stateService; + + public KingdeeSyncRunRecovery(KingdeeSyncRunStateService stateService) { + this.stateService = stateService; + } + + @EventListener(ApplicationReadyEvent.class) + public void failStaleRunningRecords() { + reapExpiredLeases(); + } + + @Scheduled(fixedDelay = 30000L) + public void reapExpiredLeases() { + int count = stateService.reapExpiredLeases(); + if (count > 0) log.warn("Marked {} expired Kingdee sync runs as FAILED", count); + } +} diff --git a/src/main/java/com/finance/system/service/KingdeeSyncRunStateService.java b/src/main/java/com/finance/system/service/KingdeeSyncRunStateService.java new file mode 100644 index 0000000..bc2f6c0 --- /dev/null +++ b/src/main/java/com/finance/system/service/KingdeeSyncRunStateService.java @@ -0,0 +1,40 @@ +package com.finance.system.service; + +import com.finance.system.repository.SysKingdeeSyncRunRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class KingdeeSyncRunStateService { + static final String TIMEOUT_MESSAGE = "同步任务超过30分钟,已标记为失败"; + + private final SysKingdeeSyncRunRepository runRepository; + + public KingdeeSyncRunStateService(SysKingdeeSyncRunRepository runRepository) { + this.runRepository = runRepository; + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public boolean finish(Long runId, String token, KingdeeDocumentSyncService.ExecutionResult result) { + if ("FAILED".equals(result.getStatus())) + return runRepository.failIfRunning(runId, token, result.getErrorMessage()) == 1; + return runRepository.finishSuccessIfValid(runId, result.getStatus(), token, + result.getErrorMessage()) == 1; + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public boolean fail(Long runId, String token, String message) { + return runRepository.failIfRunning(runId, token, message) == 1; + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public boolean timeoutIfHardDeadlineExpired(Long runId, String token) { + return runRepository.timeoutIfHardDeadlineExpired(runId, token, TIMEOUT_MESSAGE) == 1; + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public int reapExpiredLeases() { + return runRepository.failExpiredLeases(TIMEOUT_MESSAGE); + } +} diff --git a/src/main/java/com/finance/system/service/ReimApplicationService.java b/src/main/java/com/finance/system/service/ReimApplicationService.java index 03bb78d..6cd7b24 100644 --- a/src/main/java/com/finance/system/service/ReimApplicationService.java +++ b/src/main/java/com/finance/system/service/ReimApplicationService.java @@ -33,6 +33,12 @@ public interface ReimApplicationService { ReimApplicationDetail submitApplication(Long id, Long userId); + ReimApplicationDetail submitApplication(Long id, Long userId, String previewToken); + + RoutePreviewDto previewRoute(Long id, Long userId); + + java.util.List getRouteTimeline(Long id, Long userId); + default ReimApplicationDetail submitApplication(Long id) { return submitApplication(id, com.finance.system.util.AuditUtil.getCurrentUserId()); } diff --git a/src/main/java/com/finance/system/service/ReimbursementFingerprintService.java b/src/main/java/com/finance/system/service/ReimbursementFingerprintService.java new file mode 100644 index 0000000..18ba19c --- /dev/null +++ b/src/main/java/com/finance/system/service/ReimbursementFingerprintService.java @@ -0,0 +1,32 @@ +package com.finance.system.service; + +import com.finance.system.adapter.feishu.ReimbursementCanonicalizer; +import com.finance.system.entity.*; +import com.finance.system.repository.*; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class ReimbursementFingerprintService { + private final SysUserRepository users; + private final SysDepartmentRepository departments; + private final SysExpenseTypeRepository expenseTypes; + private final SysBankAccountRepository banks; + private final ReimExpenseItemRepository items; + + public String fingerprint(ReimApplication app) { + SysUser user = app.getApplicantId() == null ? null : users.findById(app.getApplicantId()).orElse(null); + SysDepartment department = app.getDepartmentId() == null ? null : departments.findById(app.getDepartmentId()).orElse(null); + SysExpenseType type = app.getExpenseTypeId() == null ? null : expenseTypes.findById(app.getExpenseTypeId()).orElse(null); + SysBankAccount bank = app.getPayeeBankId() == null ? null : banks.findById(app.getPayeeBankId()).orElse(null); + return ReimbursementCanonicalizer.fingerprint(app, user, department, type, bank, + items.findByApplicationId(app.getId())); + } + + /** Stable across directory/config label changes; used only to prove the applicant did not edit an unknown attempt. */ + public String submissionContentFingerprint(ReimApplication app) { + return ReimbursementCanonicalizer.fingerprint(app, null, null, null, null, + items.findByApplicationId(app.getId())); + } +} diff --git a/src/main/java/com/finance/system/service/ReimbursementPreviewTokenCleanup.java b/src/main/java/com/finance/system/service/ReimbursementPreviewTokenCleanup.java new file mode 100644 index 0000000..05ce61a --- /dev/null +++ b/src/main/java/com/finance/system/service/ReimbursementPreviewTokenCleanup.java @@ -0,0 +1,24 @@ +package com.finance.system.service; + +import com.finance.system.repository.ReimRoutePreviewTokenRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import java.time.LocalDateTime; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class ReimbursementPreviewTokenCleanup { + private static final int BATCH_SIZE = 500; + private final ReimRoutePreviewTokenRepository tokens; + + @Scheduled(fixedDelayString = "${reimbursement.preview-token-cleanup-ms:300000}") + @Transactional + public int cleanupBatch() { + List ids = tokens.findCleanupIds(LocalDateTime.now(), PageRequest.of(0, BATCH_SIZE)); + return ids.isEmpty() ? 0 : tokens.deleteCleanupIds(ids); + } +} diff --git a/src/main/java/com/finance/system/service/RoleService.java b/src/main/java/com/finance/system/service/RoleService.java index 2c8ce39..6a4e262 100644 --- a/src/main/java/com/finance/system/service/RoleService.java +++ b/src/main/java/com/finance/system/service/RoleService.java @@ -1,11 +1,15 @@ package com.finance.system.service; import com.finance.system.entity.*; +import com.finance.system.dto.MemberCandidateDto; +import com.finance.system.dto.MemberCandidatesResponse; +import com.finance.system.dto.DirectoryIdentityDto; import com.finance.system.exception.BusinessException; import com.finance.system.exception.ResourceNotFoundException; import com.finance.system.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; @@ -20,27 +24,22 @@ public class RoleService { public static final String EMPLOYEE = "EMPLOYEE"; public static final String ADMIN = "ADMIN"; public static final String SUPER_ADMIN = "SUPER_ADMIN"; + public static final String DEFAULT_EMPLOYEE_GROUP = "DEFAULT_EMPLOYEE"; private static final Set ACCESS_LEVELS = new HashSet<>(Arrays.asList("HIDDEN", "READ", "EDIT")); - private static final Set SUPER_ADMIN_ONLY_PERMISSIONS = new HashSet<>(Arrays.asList( - "payment:register", "receipt:manage", "reimbursement:view-all", "master-data:manage", "approval:view")); - private static final Set EMPLOYEE_DEFAULTS = new LinkedHashSet<>(Arrays.asList( - "dashboard", "applications", "application:create", "application:view-own", - "reimbursement:create", "reimbursement:view-own")); + private static final Set PERMISSION_TYPES = new HashSet<>(Arrays.asList("MENU", "BUTTON", "FIELD")); private static final Set SAFE_EMPLOYEE_PERMISSIONS = new LinkedHashSet<>(Arrays.asList( "dashboard", "applications", "application:create", "application:view-own", "application:amount", "application:payeeName", "application:bankAccount", "reimbursement:create", "reimbursement:view-own")); - private static final Set FINANCE_DEFAULTS = new LinkedHashSet<>(Arrays.asList( - "dashboard", "applications", "application:create", "application:view-own", - "reimbursement:create", "reimbursement:view-own", "reimbursement:view-all", - "receipt:manage", "payment:register", "approval:view", "master-data:manage")); private static final Set LEGACY_APPLICATION_FIELDS = new LinkedHashSet<>(Arrays.asList( "application:amount", "application:payeeName", "application:bankAccount")); + private static final int MAX_CANDIDATE_RESULTS = 200; + private static final int MAX_DIRECTORY_IDENTITIES_PER_BIND = 200; + private static final int MAX_MEMBER_IDS_PER_BIND = 5_000; private final SysRoleRepository roles; private final SysPermissionRepository permissions; private final SysRolePermissionRepository rolePermissions; - private final SysUserRoleRepository userRoles; private final SysUserRepository users; private final SysUserGroupRepository groups; private final SysUserGroupMemberRepository members; @@ -50,15 +49,16 @@ public class RoleService { private com.finance.system.adapter.feishu.FeishuDirectoryAccessService directoryAccess; @Autowired private JdbcTemplate jdbc; + @Autowired(required = false) + private com.finance.system.adapter.feishu.FeishuDirectoryBindingProvisioner directoryBindingProvisioner; public RoleService(SysRoleRepository roles, SysPermissionRepository permissions, - SysRolePermissionRepository rolePermissions, SysUserRoleRepository userRoles, - SysUserRepository users, SysUserGroupRepository groups, + SysRolePermissionRepository rolePermissions, SysUserRepository users, + SysUserGroupRepository groups, SysUserGroupMemberRepository members, SysUserGroupRoleRepository groupRoles) { this.roles = roles; this.permissions = permissions; this.rolePermissions = rolePermissions; - this.userRoles = userRoles; this.users = users; this.groups = groups; this.members = members; @@ -73,20 +73,56 @@ public class RoleService { List> result = new ArrayList<>(); for (SysRole role : roles.findAll()) { Map item = roleMap(role); - item.put("memberCount", userRoles.countByIdRoleId(role.getId())); + item.put("memberCount", groupAuthorizedMemberCount(role)); item.put("permissionCount", rolePermissions.countByIdRoleId(role.getId())); result.add(item); } return result; } + /** Counts distinct users who receive the role from an enabled group. */ + private long groupAuthorizedMemberCount(SysRole role) { + if (role == null || role.getId() == null || !isActiveStatus(role.getStatus())) return 0L; + Set userIds = new HashSet<>(); + for (SysUserGroupRole assignment : safe(groupRoles.findByIdRoleId(role.getId()))) { + if (assignment.getId() == null) continue; + SysUserGroup group = groups.findById(assignment.getId().getGroupId()).orElse(null); + if (group == null || !isActiveStatus(group.getStatus())) continue; + if (isDefaultGroup(group)) { + if (EMPLOYEE.equals(normalize(role.getRoleCode()))) userIds.addAll(dynamicMembership().userIds); + continue; + } + for (SysUserGroupMember member : safe(members.findByIdGroupId(group.getId()))) { + if (member.getId() != null && member.getId().getUserId() != null) { + Long userId = member.getId().getUserId(); + if (users.findById(userId).map(user -> isActiveStatus(user.getStatus())).orElse(false)) { + userIds.add(userId); + } + } + } + } + return userIds.size(); + } + @Transactional public SysRole saveRole(Long id, Map body) { + return saveRole(id, body, AuditUtil.getCurrentUserId()); + } + + @Transactional + public SysRole saveRole(Long id, Map body, Long actorId) { String code = requiredCode(body, "roleCode"); String name = requiredText(body, "roleName"); if (id == null && roles.existsByRoleCode(code)) throw new BusinessException("角色编码已存在", 409); SysRole role = id == null ? new SysRole() : roles.findById(id) .orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + String existingStatus = role.getStatus(); + if (id != null && Boolean.TRUE.equals(role.getBuiltIn()) && !isSuperAdmin(actorId)) { + throw new BusinessException("只有超级管理员可以修改内置角色", 403); + } + boolean privilegedBuiltIn = id != null && Boolean.TRUE.equals(role.getBuiltIn()) + && (ADMIN.equals(normalize(role.getRoleCode())) || SUPER_ADMIN.equals(normalize(role.getRoleCode()))); + if (privilegedBuiltIn) lockPrivilegeChanges(); if (id != null && !code.equals(role.getRoleCode()) && roles.existsByRoleCode(code)) { throw new BusinessException("角色编码已存在", 409); } @@ -96,7 +132,16 @@ public class RoleService { role.setRoleCode(code); role.setRoleName(name); role.setDescription(text(body.get("description"))); - role.setStatus(status(body.get("status"))); + String requestedStatus = status(body.get("status")); + if (id != null && !Boolean.TRUE.equals(role.getBuiltIn()) + && !isActiveStatus(existingStatus) && "ACTIVE".equals(requestedStatus)) { + validateDelegatedRolesFromExplicitGroups(actorId, Collections.singleton(id)); + } + if (EMPLOYEE.equals(normalize(role.getRoleCode())) && "INACTIVE".equals(requestedStatus)) + throw new BusinessException("默认用户组依赖的 EMPLOYEE 角色不可停用", 409); + if (SUPER_ADMIN.equals(normalize(role.getRoleCode())) && "INACTIVE".equals(requestedStatus)) + throw new BusinessException("超级管理员内置角色不可停用", 400); + role.setStatus(requestedStatus); if (role.getBuiltIn() == null) role.setBuiltIn(false); return roles.save(role); } @@ -110,7 +155,6 @@ public class RoleService { throw new BusinessException("不能删除最后一个管理员角色", 400); } rolePermissions.deleteByIdRoleId(id); - userRoles.deleteByIdRoleId(id); groupRoles.deleteByIdRoleId(id); roles.delete(role); } @@ -125,6 +169,7 @@ public class RoleService { item.put("type", permission.getPermissionType()); item.put("parentCode", permission.getParentCode()); item.put("resource", permission.getResource()); + item.put("defaultAccess", permission.getDefaultAccess()); result.add(item); } return result; @@ -135,19 +180,28 @@ public class RoleService { requireRole(roleId); Map field = new LinkedHashMap<>(); List codes = new ArrayList<>(); - Map catalog = permissionMap(rolePermissions.findByIdRoleId(roleId)); - for (SysRolePermission assignment : safe(rolePermissions.findByIdRoleId(roleId))) { + Map access = new LinkedHashMap<>(); + for (SysPermission permission : safe(permissions.findAll())) { + access.put(permission.getPermissionCode(), "HIDDEN"); + if ("FIELD".equals(permission.getPermissionType())) field.put(permission.getPermissionCode(), "HIDDEN"); + } + List assignments = safe(rolePermissions.findByIdRoleId(roleId)); + Map catalog = permissionMap(assignments); + for (SysRolePermission assignment : assignments) { SysPermission permission = catalog.get(assignment.getId().getPermissionId()); - if (permission == null) continue; + String level = normalizedAccess(assignment.getAccessLevel()); + if (permission == null || level == null) continue; + access.put(permission.getPermissionCode(), level); if ("FIELD".equals(permission.getPermissionType())) { - field.put(permission.getPermissionCode(), assignment.getAccessLevel()); - } else if (!"HIDDEN".equals(assignment.getAccessLevel())) { + field.put(permission.getPermissionCode(), level); + } else if (!"HIDDEN".equals(level)) { codes.add(permission.getPermissionCode()); } } Map result = new LinkedHashMap<>(); result.put("permissionCodes", codes); result.put("fieldPermissions", field); + result.put("permissionAccess", access); return result; } @@ -160,40 +214,27 @@ public class RoleService { public void replaceRolePermissions(Long roleId, Map body, Long actorId) { SysRole targetRole = requireRole(roleId); boolean superAdmin = isSuperAdmin(actorId); - if (!superAdmin && !hasPermission(actorId, "system:role:manage")) { + if (!superAdmin && !hasEditPermission(actorId, "system.role.permission.configure")) { throw new BusinessException("无权管理角色权限", 403); } if (!superAdmin && Boolean.TRUE.equals(targetRole.getBuiltIn())) { throw new BusinessException("普通管理员不能修改内置角色权限", 403); } if (body == null) throw new BusinessException("权限请求不能为空", 400); - if (body.containsKey("permissionCodes") && !(body.get("permissionCodes") instanceof Collection)) { - throw new BusinessException("permissionCodes 必须是数组", 400); - } - if (body.containsKey("fieldPermissions") && !(body.get("fieldPermissions") instanceof Map)) { - throw new BusinessException("fieldPermissions 必须是对象", 400); - } - Set codes = stringSet(body.get("permissionCodes")); - Map field = stringMap(body.get("fieldPermissions")); - codes.addAll(field.keySet()); Map catalog = permissions.findAll().stream() .collect(Collectors.toMap(SysPermission::getPermissionCode, p -> p)); - for (String code : codes) { - if (!catalog.containsKey(code)) throw new BusinessException("权限不存在: " + code, 400); - if (field.containsKey(code) && !"FIELD".equals(catalog.get(code).getPermissionType())) { - throw new BusinessException("只有字段权限可以设置 fieldPermissions", 400); - } - String access = field.containsKey(code) ? field.get(code) : "READ"; - if (!ACCESS_LEVELS.contains(access)) throw new BusinessException("无效的访问级别", 400); - if (!superAdmin && !canDelegatePermission(actorId, catalog.get(code), access)) { + Map requested = requestedAccess(body, catalog); + addReadableAncestors(requested, catalog); + for (Map.Entry entry : requested.entrySet()) { + SysPermission permission = catalog.get(entry.getKey()); + if (!superAdmin && !canDelegatePermission(actorId, permission, entry.getValue())) { throw new BusinessException("不能授予超出操作者自身有效权限的权限", 403); } } rolePermissions.deleteByIdRoleId(roleId); List replacements = new ArrayList<>(); - for (String code : codes) { - replacements.add(new SysRolePermission(roleId, catalog.get(code).getId(), - field.containsKey(code) ? field.get(code) : "READ")); + for (Map.Entry entry : requested.entrySet()) { + replacements.add(new SysRolePermission(roleId, catalog.get(entry.getKey()).getId(), entry.getValue())); } if (!replacements.isEmpty()) rolePermissions.saveAll(replacements); } @@ -201,78 +242,74 @@ public class RoleService { @Transactional(readOnly = true) public ResolvedPermissions currentPermissions(Long userId) { SysUser user = users.findById(userId).orElse(null); - if (user == null) return new ResolvedPermissions(Collections.singleton(EMPLOYEE), EMPLOYEE_DEFAULTS, + if (user == null || !isActiveStatus(user.getStatus())) return new ResolvedPermissions(Collections.emptySet(), Collections.emptySet(), Collections.emptyMap(), Collections.emptyMap(), false); - LinkedHashSet configuredRoleIds = new LinkedHashSet<>(); - for (SysUserRole assignment : safe(userRoles.findByIdUserId(userId))) { - if (assignment.getId() != null) configuredRoleIds.add(assignment.getId().getRoleId()); - } LinkedHashSet groupIds = new LinkedHashSet<>(); - for (SysUserGroupMember member : safe(members.findByIdUserId(userId))) { + List explicitMemberships = safe(members.findByIdUserId(userId)); + for (SysUserGroupMember member : explicitMemberships) { if (member.getId() != null) groupIds.add(member.getId().getGroupId()); } for (SysUserGroup group : groups.findAllById(groupIds)) { - if (!"INACTIVE".equalsIgnoreCase(group.getStatus())) { + if (isActiveStatus(group.getStatus())) { for (SysUserGroupRole assignment : safe(groupRoles.findByIdGroupId(group.getId()))) { if (assignment.getId() != null) configuredRoleIds.add(assignment.getId().getRoleId()); } } } - boolean configured = !configuredRoleIds.isEmpty(); - List effectiveRoles; - if (configured) { - effectiveRoles = roles.findAllById(configuredRoleIds).stream() - .filter(r -> !"INACTIVE".equalsIgnoreCase(r.getStatus())).collect(Collectors.toList()); - } else { - String fallback = legacyRoleCode(user.getUserType()); - effectiveRoles = roles.findByRoleCode(fallback).map(Collections::singletonList) - .orElse(Collections.emptyList()); + boolean configured = !explicitMemberships.isEmpty(); + LinkedHashSet effectiveRoleIds = new LinkedHashSet<>(configuredRoleIds); + // DEFAULT_EMPLOYEE is additive. An eligible directory user keeps the + // implicit EMPLOYEE role even while assigned to one explicit group. + if (isDynamicDefaultMember(user)) { + roles.findByRoleCode(EMPLOYEE).filter(r -> isActiveStatus(r.getStatus())) + .map(SysRole::getId).ifPresent(effectiveRoleIds::add); } + List effectiveRoles = effectiveRoleIds.isEmpty() ? Collections.emptyList() + : roles.findAllById(effectiveRoleIds).stream() + .filter(r -> isActiveStatus(r.getStatus())).collect(Collectors.toList()); LinkedHashSet roleCodes = effectiveRoles.stream().map(SysRole::getRoleCode) .collect(Collectors.toCollection(LinkedHashSet::new)); LinkedHashSet permissionCodes = new LinkedHashSet<>(); Map permissionAccess = new LinkedHashMap<>(); Map fieldPermissions = new LinkedHashMap<>(); + for (SysPermission permission : safe(permissions.findAll())) { + permissionAccess.put(permission.getPermissionCode(), "HIDDEN"); + if ("FIELD".equals(permission.getPermissionType())) fieldPermissions.put(permission.getPermissionCode(), "HIDDEN"); + } if (!effectiveRoles.isEmpty()) { Set roleIds = effectiveRoles.stream().map(SysRole::getId).collect(Collectors.toSet()); List assignments = safe(rolePermissions.findByIdRoleIdIn(roleIds)); Map catalog = permissionMap(assignments); for (SysRolePermission assignment : assignments) { SysPermission permission = catalog.get(assignment.getId().getPermissionId()); - if (permission == null || "HIDDEN".equals(assignment.getAccessLevel())) continue; + String level = normalizedAccess(assignment.getAccessLevel()); + if (permission == null || level == null || "HIDDEN".equals(level)) continue; if ("FIELD".equals(permission.getPermissionType())) { - fieldPermissions.put(permission.getPermissionCode(), stronger(fieldPermissions.get(permission.getPermissionCode()), assignment.getAccessLevel())); + fieldPermissions.put(permission.getPermissionCode(), stronger(fieldPermissions.get(permission.getPermissionCode()), level)); } else { permissionCodes.add(permission.getPermissionCode()); - permissionAccess.put(permission.getPermissionCode(), stronger(permissionAccess.get(permission.getPermissionCode()), assignment.getAccessLevel())); + permissionAccess.put(permission.getPermissionCode(), stronger(permissionAccess.get(permission.getPermissionCode()), level)); } + permissionAccess.put(permission.getPermissionCode(), stronger(permissionAccess.get(permission.getPermissionCode()), level)); } - } else if (!configured) { - String legacy = legacyRoleCode(user.getUserType()); - roleCodes.add(legacy); - if (ADMIN.equals(legacy) || SUPER_ADMIN.equals(legacy)) { - for (SysPermission permission : permissions.findAll()) { - if ("FIELD".equals(permission.getPermissionType())) fieldPermissions.put(permission.getPermissionCode(), "EDIT"); - else { permissionCodes.add(permission.getPermissionCode()); permissionAccess.put(permission.getPermissionCode(), "EDIT"); } + } + // SUPER_ADMIN's full-access behavior is reached only through an active + // group-derived role; sys_user.user_type is never consulted. + if (roleCodes.contains(SUPER_ADMIN)) { + roleCodes.add(SUPER_ADMIN); + for (SysPermission permission : safe(permissions.findAll())) { + if ("FIELD".equals(permission.getPermissionType())) { + fieldPermissions.put(permission.getPermissionCode(), "EDIT"); + } else { + permissionCodes.add(permission.getPermissionCode()); + permissionAccess.put(permission.getPermissionCode(), "EDIT"); } - for (String field : LEGACY_APPLICATION_FIELDS) fieldPermissions.put(field, "EDIT"); - } else { - Set defaults = "FINANCE".equals(legacy) ? FINANCE_DEFAULTS : EMPLOYEE_DEFAULTS; - permissionCodes.addAll(defaults); - for (String code : defaults) permissionAccess.put(code, legacyPermissionAccess(legacy, code)); - // Pre-RBAC installations have no field rows at all. Preserve - // the historical employee/finance fallback while still - // requiring explicit EDIT rows for configured custom roles. - for (SysPermission permission : permissions.findAll()) { - if ("FIELD".equals(permission.getPermissionType())) { - fieldPermissions.put(permission.getPermissionCode(), "EDIT"); - } - } - for (String field : LEGACY_APPLICATION_FIELDS) fieldPermissions.put(field, "EDIT"); + permissionAccess.put(permission.getPermissionCode(), "EDIT"); } + for (String field : LEGACY_APPLICATION_FIELDS) fieldPermissions.put(field, "EDIT"); } return new ResolvedPermissions(roleCodes, permissionCodes, fieldPermissions, permissionAccess, configured); } @@ -284,19 +321,29 @@ public class RoleService { result.put("roleCodes", new ArrayList<>(current.getRoleCodes())); result.put("permissionCodes", new ArrayList<>(current.getPermissionCodes())); result.put("fieldPermissions", current.getFieldPermissions()); + result.put("permissionAccess", current.getPermissionAccess()); return result; } + @Transactional(readOnly = true) public boolean hasPermission(Long userId, String code) { - SysUser user = users.findById(userId).orElse(null); - if (user != null && (ADMIN.equalsIgnoreCase(normalize(user.getUserType())) - || SUPER_ADMIN.equalsIgnoreCase(normalize(user.getUserType())))) return true; ResolvedPermissions current = currentPermissions(userId); - if (current.getRoleCodes().contains(ADMIN) || current.getRoleCodes().contains(SUPER_ADMIN)) return true; + if (current.getRoleCodes().contains(SUPER_ADMIN)) return true; String fieldAccess = current.getFieldPermissions().get(code); return current.getPermissionCodes().contains(code) || (fieldAccess != null && !"HIDDEN".equals(fieldAccess)); } + /** + * Checks write access for an operation permission. Menu visibility and + * read access deliberately remain separate from mutating operations. + */ + @Transactional(readOnly = true) + public boolean hasEditPermission(Long userId, String code) { + ResolvedPermissions current = currentPermissions(userId); + if (current.getRoleCodes().contains(SUPER_ADMIN)) return true; + return accessRank(current.getPermissionAccess().get(code)) >= accessRank("EDIT"); + } + /** * Returns the effective access level of a field permission. A missing * assignment is deliberately treated as HIDDEN; callers must not infer @@ -306,7 +353,7 @@ public class RoleService { public String fieldAccess(Long userId, String code) { if (userId == null || code == null) return "HIDDEN"; ResolvedPermissions resolved = currentPermissions(userId); - if (resolved.getRoleCodes().contains(ADMIN) || resolved.getRoleCodes().contains(SUPER_ADMIN)) return "EDIT"; + if (resolved.getRoleCodes().contains(SUPER_ADMIN)) return "EDIT"; String access = resolved.getFieldPermissions().get(code); return access == null ? "HIDDEN" : access; } @@ -322,8 +369,8 @@ public class RoleService { if (userId == null) return false; SysUser user = users.findById(userId).orElse(null); if (user == null) return false; - if (SUPER_ADMIN.equals(normalize(user.getUserType()))) return true; - return currentPermissions(userId).getRoleCodes().contains(SUPER_ADMIN); + if (!isActiveStatus(user.getStatus())) return false; + return hasActiveExplicitRole(userId, SUPER_ADMIN); } @Transactional @@ -333,29 +380,7 @@ public class RoleService { @Transactional public void replaceUserRoles(Long userId, Collection roleIds, Long actorId) { - SysUser user = requireUser(userId); - Set ids = longSet(roleIds); - validateRoleIds(ids); - validateDelegatedRoles(actorId, ids); - ensurePrivilegedRoleDelegation(actorId, userId, ids); - userRoles.deleteByIdUserId(userId); - for (Long roleId : ids) userRoles.save(new SysUserRole(userId, roleId)); - if (ids.size() == 1) { - SysRole selected = requireRole(ids.iterator().next()); - if (EMPLOYEE.equals(selected.getRoleCode()) || "FINANCE".equals(selected.getRoleCode()) - || ADMIN.equals(selected.getRoleCode())) { - user.setUserType(selected.getRoleCode()); - } else { - user.setUserType(EMPLOYEE); - } - } else { - // Empty assignments fall back to ordinary-user behavior. For - // multi-role/custom assignments the legacy field must not make a - // client mistake the user for an administrator; roleCodes is the - // authoritative representation in that case. - user.setUserType(EMPLOYEE); - } - users.save(user); + throw new BusinessException("用户角色只能通过用户组管理", 410); } /** Actor-first form for service callers that pass the security subject first. */ @@ -364,7 +389,7 @@ public class RoleService { replaceUserRoles(userId, roleIds, actorId); } - /** Compatibility endpoint: userType is kept, and the corresponding built-in role is assigned. */ + /** Retired compatibility operation. Roles are assigned only through groups. */ @Transactional public void syncLegacyRole(Long userId, String roleCode) { syncLegacyRole(userId, roleCode, AuditUtil.getCurrentUserId()); @@ -372,13 +397,7 @@ public class RoleService { @Transactional public void syncLegacyRole(Long userId, String roleCode, Long actorId) { - String normalized = normalize(roleCode); - if (!(EMPLOYEE.equals(normalized) || "FINANCE".equals(normalized) - || ADMIN.equals(normalized) || SUPER_ADMIN.equals(normalized))) { - throw new BusinessException("角色必须是 EMPLOYEE、FINANCE、ADMIN 或 SUPER_ADMIN", 400); - } - SysRole role = roles.findByRoleCode(normalized).orElseThrow(() -> new BusinessException("内置角色不存在", 409)); - replaceUserRoles(userId, Collections.singletonList(role.getId()), actorId); + throw new BusinessException("用户角色只能通过用户组管理", 410); } @Transactional @@ -392,50 +411,105 @@ public class RoleService { @Transactional(readOnly = true) public List userGroupNames(Long userId) { List result = new ArrayList<>(); - for (SysUserGroupMember member : safe(members.findByIdUserId(userId))) { + List explicitMemberships = safe(members.findByIdUserId(userId)); + for (SysUserGroupMember member : explicitMemberships) { if (member.getId() == null) continue; - groups.findById(member.getId().getGroupId()).filter(g -> !"INACTIVE".equalsIgnoreCase(g.getStatus())) - .ifPresent(g -> result.add(g.getGroupName())); + groups.findById(member.getId().getGroupId()).ifPresent(g -> result.add( + "INACTIVE".equalsIgnoreCase(g.getStatus()) + ? g.getGroupName() + "(已停用)" : g.getGroupName())); } + SysUser user = users.findById(userId).orElse(null); + if (isDynamicDefaultMember(user)) groups.findByGroupCode(DEFAULT_EMPLOYEE_GROUP) + .ifPresent(g -> result.add(g.getGroupName())); return result; } @Transactional(readOnly = true) public List> listGroups() { List> result = new ArrayList<>(); + DynamicMembership dynamic = dynamicMembership(); for (SysUserGroup group : groups.findAll()) { - Map item = groupMap(group); - item.put("memberCount", members.findByIdGroupId(group.getId()).size()); - item.put("roleCount", groupRoles.findByIdGroupId(group.getId()).size()); - result.add(item); + result.add(groupDetails(group, dynamic)); } return result; } + @Transactional(readOnly = true) + public Map groupDetails(Long id) { + SysUserGroup group = requireGroup(id); + return groupDetails(group, isDefaultGroup(group) ? dynamicMembership() : null); + } + @Transactional public SysUserGroup saveGroup(Long id, Map body) { String code = requiredCode(body, "groupCode"); String name = requiredText(body, "groupName"); if (id == null && groups.existsByGroupCode(code)) throw new BusinessException("用户组编码已存在", 409); - SysUserGroup group = id == null ? new SysUserGroup() : groups.findById(id) - .orElseThrow(() -> new ResourceNotFoundException("用户组不存在")); + lockPrivilegeChanges(); + SysUserGroup group = id == null ? new SysUserGroup() : requireGroupForUpdate(id); + if (id != null && isDefaultGroup(group)) { + throw new BusinessException("默认用户组不可修改", 409); + } + boolean privileged = id != null && containsPrivilegedGroupRole(id); + if (privileged && !isSuperAdmin(AuditUtil.getCurrentUserId())) + throw new BusinessException("只有超级管理员可以修改管理员用户组", 403); if (id != null && !code.equals(group.getGroupCode()) && groups.existsByGroupCode(code)) { throw new BusinessException("用户组编码已存在", 409); } + String requestedStatus = status(body.get("status")); + if (id != null && !isActiveStatus(group.getStatus()) && "ACTIVE".equals(requestedStatus)) { + Set assigned = groupRoleIdSet(id); + validateRoleIds(assigned); + validateDelegatedRolesFromExplicitGroups(AuditUtil.getCurrentUserId(), assigned); + } group.setGroupCode(code); group.setGroupName(name); group.setDescription(text(body.get("description"))); - group.setStatus(status(body.get("status"))); - return groups.save(group); + group.setStatus(requestedStatus); + if (group.getBuiltIn() == null) group.setBuiltIn(false); + SysUserGroup saved = groups.save(group); + if (privileged && "INACTIVE".equalsIgnoreCase(saved.getStatus())) ensureActiveSuperAdminRemains(); + return saved; } @Transactional public void deleteGroup(Long id) { - requireGroup(id); members.deleteByIdGroupId(id); groupRoles.deleteByIdGroupId(id); groups.deleteById(id); + lockPrivilegeChanges(); + SysUserGroup target = requireGroupForUpdate(id); + if (isDefaultGroup(target)) throw new BusinessException("默认用户组不可删除", 409); + boolean privileged = containsPrivilegedGroupRole(id); + if (privileged && !isSuperAdmin(AuditUtil.getCurrentUserId())) + throw new BusinessException("只有超级管理员可以删除管理员用户组", 403); + members.deleteByIdGroupId(id); groupRoles.deleteByIdGroupId(id); groups.deleteById(id); + if (privileged) ensureActiveSuperAdminRemains(); } @Transactional(readOnly = true) - public List groupRoleIds(Long id) { requireGroup(id); return groupRoles.findByIdGroupId(id).stream().map(x -> x.getId().getRoleId()).collect(Collectors.toList()); } + public List groupRoleIds(Long id) { + SysUserGroup group = requireGroup(id); + if (isDefaultGroup(group)) return Collections.singletonList(roles.findByRoleCode(EMPLOYEE) + .orElseThrow(() -> new BusinessException("内置 EMPLOYEE 角色不存在", 409)).getId()); + return safe(groupRoles.findByIdGroupId(id)).stream().map(x -> x.getId().getRoleId()).collect(Collectors.toList()); + } @Transactional(readOnly = true) - public List groupMemberIds(Long id) { requireGroup(id); return members.findByIdGroupId(id).stream().map(x -> x.getId().getUserId()).collect(Collectors.toList()); } + public List groupMemberIds(Long id) { + SysUserGroup group = requireGroup(id); + if (isDefaultGroup(group)) return dynamicMembership().userIds; + return safe(members.findByIdGroupId(id)).stream().map(x -> x.getId().getUserId()).collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public Map groupMembers(Long id) { + SysUserGroup group = requireGroup(id); + boolean dynamic = isDefaultGroup(group); + DynamicMembership membership = dynamic ? dynamicMembership() : null; + Map result = new LinkedHashMap<>(); + result.put("userIds", dynamic ? membership.userIds : safe(members.findByIdGroupId(id)).stream() + .map(x -> x.getId().getUserId()).collect(Collectors.toList())); + result.put("dynamic", dynamic); + result.put("editable", !dynamic); + result.put("membershipResolved", !dynamic || membership.resolved); + result.put("snapshotState", dynamic ? membership.snapshotState : null); + return result; + } @Transactional public void replaceGroupRoles(Long id, Collection roleIds) { @@ -444,10 +518,28 @@ public class RoleService { @Transactional public void replaceGroupRoles(Long id, Collection roleIds, Long actorId) { - requireGroup(id); Set ids = longSet(roleIds); validateRoleIds(ids); + replaceGroupRoles(id, roleIds, null, actorId); + } + + /** Public optimistic-concurrency variant. A null baseline is reserved for trusted internal callers. */ + @Transactional + public void replaceGroupRoles(Long id, Collection roleIds, Collection expectedRoleIds, Long actorId) { + lockPrivilegeChanges(); + SysUserGroup group = requireGroupForUpdate(id); + if (isDefaultGroup(group)) throw new BusinessException("默认用户组角色固定为 EMPLOYEE", 409); + if (expectedRoleIds != null && !groupRoleIdSet(id).equals(longSet(expectedRoleIds))) { + throw new BusinessException("用户组角色已被其他管理员修改,请刷新后重试", 409); + } + Set ids = longSet(roleIds); validateRoleIds(ids); + boolean hadPrivileged = containsPrivilegedGroupRole(id); + boolean requestsPrivileged = containsPrivilegedRole(ids); + if (!isSuperAdmin(actorId) && (hadPrivileged || requestsPrivileged)) { + throw new BusinessException("只有超级管理员可以变更管理员用户组角色", 403); + } validateDelegatedRoles(actorId, ids); ensurePrivilegedRoleDelegation(actorId, null, ids); groupRoles.deleteByIdGroupId(id); for (Long roleId : ids) groupRoles.save(new SysUserGroupRole(id, roleId)); + if (hadPrivileged || requestsPrivileged) ensureActiveSuperAdminRemains(); } @Transactional @@ -461,7 +553,22 @@ public class RoleService { @Transactional public void replaceGroupMembers(Long id, Collection userIds, Long actorId) { - requireGroup(id); + replaceGroupMembers(id, userIds, null, actorId); + } + + /** Trusted compatibility variant; HTTP callers use the directory-identity overload below. */ + @Transactional + public void replaceGroupMembers(Long id, Collection userIds, Collection expectedUserIds, Long actorId) { + lockPrivilegeChanges(); + SysUserGroup group = requireGroupForUpdate(id); + if (isDefaultGroup(group)) throw new BusinessException("默认用户组成员由目录动态计算", 409); + Set existing = null; + if (expectedUserIds != null) { + existing = currentMemberIdSet(id); + if (!existing.equals(longSet(expectedUserIds))) { + throw new BusinessException("用户组成员已被其他管理员修改,请刷新后重试", 409); + } + } List assignedRoleIds = safe(groupRoles.findByIdGroupId(id)).stream() .filter(assignment -> assignment.getId() != null) .map(assignment -> assignment.getId().getRoleId()) @@ -480,18 +587,128 @@ public class RoleService { throw new BusinessException("只有超级管理员可以管理管理员用户组成员", 403); } Set ids = longSet(userIds); - Set existing = safe(members.findByIdGroupId(id)).stream().map(m -> m.getId().getUserId()).collect(Collectors.toSet()); + if (existing == null) existing = currentMemberIdSet(id); + final Set existingIds = existing; + List occupied = ids.isEmpty() ? Collections.emptyList() + : safe(members.findByIdUserIdIn(ids)); + for (SysUserGroupMember assignment : occupied) { + if (assignment.getId() != null && !id.equals(assignment.getId().getGroupId())) + throw new BusinessException("用户已属于其他用户组", 409); + } // Only additions are checked against the directory. Acquire the // publication lock before reading those users and keep it until the // replacement rows are committed. - if (ids.stream().anyMatch(userId -> !existing.contains(userId))) { + if (ids.stream().anyMatch(userId -> !existingIds.contains(userId))) { FeishuDirectoryLock.acquire(jdbc); } for (Long userId : ids) { SysUser user = requireUser(userId); - if (!existing.contains(userId)) directoryAccess.requireSynced(user); + if (!existingIds.contains(userId)) directoryAccess.requireSyncedUnderDirectoryLock(user); } - members.deleteByIdGroupId(id); for (Long userId : ids) members.save(new SysUserGroupMember(id, userId)); + members.deleteByIdGroupId(id); + try { + if (!ids.isEmpty()) members.saveAllAndFlush(ids.stream() + .map(userId -> new SysUserGroupMember(id, userId)).collect(Collectors.toList())); + } catch (DataIntegrityViolationException ex) { + throw new BusinessException("用户已属于其他用户组", 409); + } + if (privilegedGroup) ensureActiveSuperAdminRemains(); + } + + /** + * Public directory-identity binding contract. Local IDs can retain or + * remove baseline members, but can never introduce a new account. + */ + @Transactional + public List replaceGroupMembers(Long id, Collection userIds, + Collection directoryIdentities, + Collection expectedUserIds, Long actorId) { + Set retained = strictMemberIds(userIds, "userIds"); + Set expected = strictMemberIds(expectedUserIds, "expectedUserIds"); + List additions = strictDirectoryIdentities(directoryIdentities); + if (retained.size() + additions.size() > MAX_MEMBER_IDS_PER_BIND) { + throw new BusinessException("提交的最终成员数量不能超过5000", 400); + } + lockPrivilegeChanges(); + SysUserGroup group = requireGroupForUpdate(id); + if (isDefaultGroup(group)) throw new BusinessException("默认用户组成员由目录动态计算", 409); + + Set existing = currentMemberIdSet(id); + // The optimistic baseline is deliberately checked before any account + // can be provisioned by the submitted directory identities. + if (!existing.equals(expected)) { + throw new BusinessException("用户组成员已被其他管理员修改,请刷新后重试", 409); + } + if (!expected.containsAll(retained)) { + throw new BusinessException("新增成员必须使用目录身份", 400); + } + + List assignedRoleIds = safe(groupRoles.findByIdGroupId(id)).stream() + .filter(assignment -> assignment.getId() != null) + .map(assignment -> assignment.getId().getRoleId()).collect(Collectors.toList()); + validateDelegatedRoles(actorId, assignedRoleIds); + boolean privilegedGroup = containsPrivilegedRole(assignedRoleIds); + if (privilegedGroup && !isSuperAdmin(actorId)) { + throw new BusinessException("只有超级管理员可以管理管理员用户组成员", 403); + } + + List provisioned; + if (additions.isEmpty()) { + provisioned = Collections.emptyList(); // removals remain available without a snapshot + } else { + if (directoryBindingProvisioner == null) { + throw new BusinessException("目录身份服务暂不可用,请刷新后重试", 409); + } + provisioned = directoryBindingProvisioner.resolveForExplicitBinding(additions); + } + + LinkedHashSet committed = new LinkedHashSet<>(retained); + for (Long provisionedId : provisioned) { + if (provisionedId == null || existing.contains(provisionedId) || !committed.add(provisionedId)) { + throw new BusinessException("目录身份或成员状态已变更,请刷新后重试", 409); + } + } + List occupied = committed.isEmpty() ? Collections.emptyList() + : safe(members.findByIdUserIdIn(committed)); + for (SysUserGroupMember assignment : occupied) { + if (assignment.getId() != null && !id.equals(assignment.getId().getGroupId())) { + throw new BusinessException("用户已属于其他用户组", 409); + } + } + + members.deleteByIdGroupId(id); + try { + if (!committed.isEmpty()) members.saveAllAndFlush(committed.stream() + .map(userId -> new SysUserGroupMember(id, userId)).collect(Collectors.toList())); + } catch (DataIntegrityViolationException ex) { + throw new BusinessException("用户已属于其他用户组", 409); + } + if (privilegedGroup) ensureActiveSuperAdminRemains(); + return new ArrayList<>(committed); + } + + @Transactional + public SysUser changeUserStatus(Long userId, String requestedStatus, Long actorId) { + lockPrivilegeChanges(); + SysUser user = users.findByIdForUpdate(userId) + .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); + String normalizedStatus = status(requestedStatus); + Set targetRoleIds = activeExplicitRoleIds(userId); + boolean privileged = containsRoleCode(targetRoleIds, ADMIN) || containsRoleCode(targetRoleIds, SUPER_ADMIN); + if (privileged && !hasActiveExplicitRole(actorId, SUPER_ADMIN)) { + throw new BusinessException("只有超级管理员可以变更管理员状态", 403); + } + if (userId.equals(actorId) && "INACTIVE".equals(normalizedStatus)) { + throw new BusinessException("不能停用当前登录账号", 400); + } + if (!isActiveStatus(user.getStatus()) && "ACTIVE".equals(normalizedStatus)) { + validateRoleIds(targetRoleIds); + validateDelegatedRolesFromExplicitGroups(actorId, targetRoleIds); + } + user.setStatus(normalizedStatus); + users.save(user); + if (privileged && "INACTIVE".equals(normalizedStatus)) ensureActiveSuperAdminRemains(); + return user; } @Transactional @@ -500,32 +717,190 @@ public class RoleService { } @Transactional(readOnly = true) - public List> candidates() { - List> result = new ArrayList<>(); + public List> candidates() { return candidates(null); } + + @Transactional(readOnly = true) + public List> candidates(Long groupId) { + return candidates(groupId, null); + } + + @Transactional(readOnly = true) + public List> candidates(Long groupId, String query) { + if (groupId != null) requireGroup(groupId); + String needle = query == null ? "" : query.trim().toLowerCase(Locale.ROOT); + if (needle.length() > 100) throw new BusinessException("搜索关键字不能超过100个字符", 400); + Map assignments = new HashMap<>(); + for (SysUserGroupMember membership : safe(members.findAll())) { + if (membership.getId() != null) assignments.put(membership.getId().getUserId(), membership); + } + Map groupById = safe(groups.findAll()).stream() + .filter(g -> g.getId() != null).collect(Collectors.toMap(SysUserGroup::getId, g -> g)); + List candidateRows = new ArrayList<>(); for (SysUser user : users.findAll()) { - if (!directoryAccess.directoryAllowed(user) || user.getDirectoryLastSeenRunId() == null) continue; - if (!StringUtils.hasText(user.getFeishuOpenId()) && !StringUtils.hasText(user.getFeishuUserId())) continue; - Map item = new LinkedHashMap<>(); - item.put("id", user.getId()); item.put("realName", user.getRealName()); item.put("employeeNo", user.getEmployeeNo()); + SysUserGroupMember assignment = assignments.get(user.getId()); + Long assignedGroupId = assignment == null ? null : assignment.getId().getGroupId(); + boolean existingMember = groupId != null && groupId.equals(assignedGroupId); String departmentName = null; if (departments != null && user.getDepartmentId() != null) { departmentName = departments.findById(user.getDepartmentId()).map(d -> d.getDeptName()).orElse(null); } - item.put("departmentName", departmentName); item.put("feishuOpenId", mask(user.getFeishuOpenId())); - item.put("feishuUserId", mask(user.getFeishuUserId())); item.put("status", user.getStatus()); result.add(item); + // Existing members are always observed and returned. Ordinary rows + // are narrowed before the directory transaction to avoid needless + // authorization-row reads for a selective query. + if (existingMember || matchesCandidate(needle, user.getRealName(), user.getEmployeeNo(), departmentName)) { + candidateRows.add(new CandidateRow(user, assignedGroupId, existingMember, departmentName)); + } + } + com.finance.system.adapter.feishu.FeishuDirectoryAccessService.DirectoryObservation observation = + directoryAccess.captureObservation(candidateRows.stream().map(row -> row.user.getId()) + .collect(Collectors.toCollection(LinkedHashSet::new))); + List> result = new ArrayList<>(); + int ordinaryResults = 0; + for (CandidateRow row : candidateRows) { + SysUser user = row.user; + boolean eligible = directoryAccess.directoryAllowed(user, observation); + // Keep existing members visible so an administrator can remove + // them, but never make an ineligible user selectable for addition. + if (!eligible && !row.existingMember) continue; + // Evaluate every matching ordinary row so database row order cannot + // turn later eligible users into an authoritative-looking empty + // result. Only the returned ordinary portion is capped. + if (!row.existingMember && ordinaryResults >= MAX_CANDIDATE_RESULTS) continue; + Map item = new LinkedHashMap<>(); + item.put("id", user.getId()); item.put("realName", user.getRealName()); item.put("employeeNo", user.getEmployeeNo()); + item.put("departmentName", row.departmentName); item.put("feishuOpenId", mask(user.getFeishuOpenId())); + item.put("feishuUserId", mask(user.getFeishuUserId())); item.put("status", user.getStatus()); + SysUserGroup assignedGroup = row.assignedGroupId == null ? null : groupById.get(row.assignedGroupId); + item.put("assignedGroupId", row.assignedGroupId); + item.put("assignedGroupName", assignedGroup == null ? null : assignedGroup.getGroupName()); + item.put("eligible", eligible); + item.put("selectable", row.existingMember || (eligible && row.assignedGroupId == null)); + result.add(item); + if (!row.existingMember) ordinaryResults++; } return result; } + /** Snapshot-backed candidate contract used by the group member editor. */ + @Transactional(readOnly = true) + public MemberCandidatesResponse memberCandidates(Long groupId, String query) { + Long actorId = AuditUtil.getCurrentUserId(); + boolean includeSensitiveFields = false; + if (actorId != null) { + try { + includeSensitiveFields = hasEditPermission(actorId, "system.group.member.bind"); + } catch (RuntimeException ignored) { + // Permission lookup failures must not widen directory search. + includeSensitiveFields = false; + } + } + return memberCandidates(groupId, query, includeSensitiveFields); + } + + private MemberCandidatesResponse memberCandidates(Long groupId, String query, boolean includeSensitiveFields) { + SysUserGroup targetGroup = requireGroup(groupId); // Preserve 404 behavior before directory capture. + String needle = query == null ? "" : query.trim().toLowerCase(Locale.ROOT); + if (needle.length() > 100) throw new BusinessException("搜索关键字不能超过100个字符", 400); + + List currentAssignments = safe(members.findByIdGroupId(groupId)); + LinkedHashSet currentIds = currentAssignments.stream().filter(Objects::nonNull) + .map(SysUserGroupMember::getId).filter(Objects::nonNull) + .map(SysUserGroupMember.SysUserGroupMemberId::getUserId).filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Map currentUsers = safe(users.findAllById(currentIds)).stream() + .filter(Objects::nonNull).filter(user -> user.getId() != null) + .collect(Collectors.toMap(SysUser::getId, user -> user, (left, right) -> left, LinkedHashMap::new)); + com.finance.system.adapter.feishu.FeishuDirectoryAccessService.DirectoryObservation currentObservation = + directoryAccess == null ? null : directoryAccess.captureObservation(currentIds); + + List current = new ArrayList<>(); + for (Long userId : currentIds) { + SysUser user = currentUsers.get(userId); + if (user == null) continue; // A valid FK makes this unreachable; do not invent account data. + boolean eligible = directoryAccess != null && directoryAccess.directoryAllowed(user, currentObservation); + current.add(new MemberCandidateDto(user.getId(), user.getRealName(), user.getEmployeeNo(), + localDepartmentNames(user), groupId, targetGroup.getGroupName(), eligible, true)); + } + + if (directoryAccess == null) { + return new MemberCandidatesResponse("UNAVAILABLE", "UNAVAILABLE", false, null, "UNKNOWN", + current, Collections.emptyList(), MAX_CANDIDATE_RESULTS, false, false); + } + com.finance.system.adapter.feishu.FeishuDirectoryAccessService.CandidateSearch search = + includeSensitiveFields + ? directoryAccess.searchPublishedCandidates(groupId, needle, MAX_CANDIDATE_RESULTS + 1, true) + : directoryAccess.searchPublishedCandidates(groupId, needle, MAX_CANDIDATE_RESULTS + 1); + if (!search.isAdditionsAllowed()) { + return new MemberCandidatesResponse(search.getSnapshotState(), search.getAvailabilityState(), false, + search.getCurrentRevision(), search.getContextState(), current, + Collections.emptyList(), MAX_CANDIDATE_RESULTS, false, false); + } + + LinkedHashMap uniqueRows = + new LinkedHashMap<>(); + for (com.finance.system.adapter.feishu.FeishuDirectoryAccessService.DirectoryCandidate row : search.getCandidates()) { + if (row == null) continue; + String key = StringUtils.hasText(row.getGenerationId()) && StringUtils.hasText(row.getOpenId()) + ? row.getGenerationId() + "\u0000" + row.getOpenId() + : "local\u0000" + String.valueOf(row.getLocalUserId()); + uniqueRows.putIfAbsent(key, row); + } + List rows = + new ArrayList<>(uniqueRows.values()); + Set assignedGroupIds = rows.stream() + .map(com.finance.system.adapter.feishu.FeishuDirectoryAccessService.DirectoryCandidate::getAssignedGroupId) + .filter(Objects::nonNull).collect(Collectors.toSet()); + Map groupNames = safe(groups.findAllById(assignedGroupIds)).stream() + .filter(Objects::nonNull).filter(group -> group.getId() != null) + .collect(Collectors.toMap(SysUserGroup::getId, SysUserGroup::getGroupName, (left, right) -> left)); + boolean truncated = rows.size() > MAX_CANDIDATE_RESULTS; + List matches = new ArrayList<>(); + for (int i = 0; i < Math.min(rows.size(), MAX_CANDIDATE_RESULTS); i++) { + com.finance.system.adapter.feishu.FeishuDirectoryAccessService.DirectoryCandidate row = rows.get(i); + Long assignedGroupId = row.getAssignedGroupId(); + boolean providerIdentityValid = StringUtils.hasText(row.getGenerationId()) + && StringUtils.hasText(row.getOpenId()); + // Legacy in-process candidate objects have only a local ID. They + // remain display-compatible, but never gain a provider identity. + boolean identityValid = providerIdentityValid || row.getLocalUserId() != null + && !StringUtils.hasText(row.getGenerationId()) && !StringUtils.hasText(row.getOpenId()) + && !StringUtils.hasText(row.getUserId()); + boolean selectable = identityValid && !row.isIdentityConflict() && assignedGroupId == null + && (row.getLocalUserId() == null || isActiveStatus(row.getLocalStatus())); + DirectoryIdentityDto identity = includeSensitiveFields && providerIdentityValid && selectable + ? new DirectoryIdentityDto(row.getGenerationId(), row.getOpenId(), row.getUserId()) : null; + matches.add(new MemberCandidateDto(row.getLocalUserId(), row.getName(), row.getEmployeeNo(), + row.getDepartmentNames(), assignedGroupId, groupNames.get(assignedGroupId), + row.isEligible(), selectable, identity)); + } + return new MemberCandidatesResponse(search.getSnapshotState(), search.getAvailabilityState(), + search.isAdditionsAllowed(), search.getCurrentRevision(), search.getContextState(), current, + matches, MAX_CANDIDATE_RESULTS, truncated, false); + } + + private List localDepartmentNames(SysUser user) { + if (departments == null || user == null || user.getDepartmentId() == null) return Collections.emptyList(); + return departments.findById(user.getDepartmentId()).map(department -> + Collections.singletonList(department.getDeptName())).orElse(Collections.emptyList()); + } + public static String mask(String value) { if (!StringUtils.hasText(value)) return null; String v = value.trim(); if (v.length() <= 4) return "****"; return v.substring(0, 2) + "****" + v.substring(v.length() - 2); } + private boolean matchesCandidate(String needle, String... values) { + if (!StringUtils.hasText(needle)) return true; + for (String value : values) { + if (StringUtils.hasText(value) && value.toLowerCase(Locale.ROOT).contains(needle)) return true; + } + return false; + } + public static String normalize(String value) { return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : EMPLOYEE; } - private long countAdministratorAssignments(Long roleId) { return userRoles.countByIdRoleId(roleId) + groupRoles.countByIdRoleId(roleId); } + private long countAdministratorAssignments(Long roleId) { return groupRoles.countByIdRoleId(roleId); } private void ensurePrivilegedRoleDelegation(Long actorId, Long targetUserId, Collection roleIds) { boolean privileged = false; @@ -545,9 +920,82 @@ public class RoleService { throw new BusinessException("不能把当前操作者提升为管理员", 403); } } + private Set groupRoleIdSet(Long groupId) { + return safe(groupRoles.findByIdGroupId(groupId)).stream().filter(x -> x.getId() != null) + .map(x -> x.getId().getRoleId()).collect(Collectors.toCollection(LinkedHashSet::new)); + } + private Set currentMemberIdSet(Long groupId) { + return safe(members.findByIdGroupId(groupId)).stream() + .filter(Objects::nonNull).map(SysUserGroupMember::getId).filter(Objects::nonNull) + .map(SysUserGroupMember.SysUserGroupMemberId::getUserId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + private Set activeExplicitRoleIds(Long userId) { + Set result = new LinkedHashSet<>(); + for (SysUserGroupMember member : safe(members.findByIdUserId(userId))) { + if (member.getId() == null) continue; + SysUserGroup group = groups.findById(member.getId().getGroupId()).orElse(null); + if (group != null && isActiveStatus(group.getStatus())) { + for (Long roleId : groupRoleIdSet(group.getId())) { + if (roles.findById(roleId).map(role -> isActiveStatus(role.getStatus())).orElse(false)) { + result.add(roleId); + } + } + } + } + return result; + } + private boolean containsRoleCode(Collection roleIds, String roleCode) { + for (Long roleId : roleIds) { + SysRole role = roles.findById(roleId).orElse(null); + if (role != null && isActiveStatus(role.getStatus()) + && roleCode.equals(normalize(role.getRoleCode()))) return true; + } + return false; + } + private boolean hasActiveExplicitRole(Long userId, String roleCode) { + if (userId == null) return false; + SysUser user = users.findById(userId).orElse(null); + return user != null && isActiveStatus(user.getStatus()) + && containsRoleCode(activeExplicitRoleIds(userId), roleCode); + } + private boolean containsPrivilegedRole(Collection roleIds) { + for (Long roleId : roleIds) { + String code = normalize(requireRole(roleId).getRoleCode()); + if (ADMIN.equals(code) || SUPER_ADMIN.equals(code)) return true; + } + return false; + } + private boolean containsPrivilegedGroupRole(Long groupId) { + for (SysUserGroupRole assignment : safe(groupRoles.findByIdGroupId(groupId))) { + if (assignment.getId() != null + && containsPrivilegedRole(Collections.singleton(assignment.getId().getRoleId()))) return true; + } + return false; + } + private void ensureActiveSuperAdminRemains() { + SysRole superRole = roles.findByRoleCode(SUPER_ADMIN).orElse(null); + Long superRoleId = superRole != null && isActiveStatus(superRole.getStatus()) + ? superRole.getId() : null; + for (SysUser user : safe(users.findAll())) { + if (user == null || user.getId() == null || !isActiveStatus(user.getStatus())) continue; + if (superRoleId == null) continue; + for (SysUserGroupMember member : safe(members.findByIdUserId(user.getId()))) { + if (member.getId() == null) continue; + SysUserGroup group = groups.findById(member.getId().getGroupId()).orElse(null); + if (group == null || !isActiveStatus(group.getStatus())) continue; + for (SysUserGroupRole assignment : safe(groupRoles.findByIdGroupId(group.getId()))) { + if (assignment.getId() != null && superRoleId.equals(assignment.getId().getRoleId())) return; + } + } + } + throw new BusinessException("系统必须保留至少一个启用的超级管理员恢复账号", 409); + } + private void lockPrivilegeChanges() { + roles.findByRoleCodeForUpdate(SUPER_ADMIN); + } private boolean canDelegatePermission(Long actorId, SysPermission permission, String requestedAccess) { String code = permission.getPermissionCode(); - if (isSuperAdminOnlyPermission(code)) return false; if ("HIDDEN".equals(requestedAccess)) return true; String effective = "FIELD".equals(permission.getPermissionType()) ? fieldAccess(actorId, code) : permissionAccess(actorId, code); @@ -580,14 +1028,54 @@ public class RoleService { } } } - private boolean isSuperAdminOnlyPermission(String code) { - return SUPER_ADMIN_ONLY_PERMISSIONS.contains(code) - || (code.startsWith("system:") && code.endsWith(":manage")) - || code.startsWith("system:integration:"); + /** + * Delegation check for activation paths that already hold privilege locks. + * Only active explicit-group grants are inspected, so this cannot enter the + * directory publication lock or a REQUIRES_NEW directory observation. + */ + private void validateDelegatedRolesFromExplicitGroups(Long actorId, Collection roleIds) { + if (hasActiveExplicitRole(actorId, SUPER_ADMIN)) return; + Map actorAccess = explicitPermissionAccess(actorId); + for (Long roleId : roleIds) { + SysRole role = requireRole(roleId); + List assignments = safe(rolePermissions.findByIdRoleId(roleId)); + Map catalog = permissionMap(assignments); + for (SysRolePermission assignment : assignments) { + if (assignment.getId() == null || "HIDDEN".equals(assignment.getAccessLevel())) continue; + SysPermission permission = catalog.get(assignment.getId().getPermissionId()); + if (permission == null || !ACCESS_LEVELS.contains(assignment.getAccessLevel())) { + throw new BusinessException("角色包含无效权限,不能启用", 403); + } + if (EMPLOYEE.equals(normalize(role.getRoleCode())) + && SAFE_EMPLOYEE_PERMISSIONS.contains(permission.getPermissionCode())) continue; + if (accessRank(actorAccess.get(permission.getPermissionCode())) + < accessRank(assignment.getAccessLevel())) { + throw new BusinessException("不能启用超出操作者自身有效权限的角色", 403); + } + } + } + } + private Map explicitPermissionAccess(Long userId) { + Map result = new HashMap<>(); + Set roleIds = activeExplicitRoleIds(userId); + roleIds.removeIf(roleId -> roles.findById(roleId) + .map(role -> !isActiveStatus(role.getStatus())).orElse(true)); + if (roleIds.isEmpty()) return result; + List assignments = safe(rolePermissions.findByIdRoleIdIn(roleIds)); + Map catalog = permissionMap(assignments); + for (SysRolePermission assignment : assignments) { + if (assignment.getId() == null) continue; + SysPermission permission = catalog.get(assignment.getId().getPermissionId()); + String access = normalizedAccess(assignment.getAccessLevel()); + if (permission != null && access != null && !"HIDDEN".equals(access)) { + result.put(permission.getPermissionCode(), stronger(result.get(permission.getPermissionCode()), access)); + } + } + return result; } private String permissionAccess(Long userId, String code) { ResolvedPermissions resolved = currentPermissions(userId); - if (resolved.getRoleCodes().contains(ADMIN) || resolved.getRoleCodes().contains(SUPER_ADMIN)) return "EDIT"; + if (resolved.getRoleCodes().contains(SUPER_ADMIN)) return "EDIT"; String access = resolved.getPermissionAccess().get(code); return access == null && resolved.getPermissionCodes().contains(code) ? "READ" : access; } @@ -596,26 +1084,180 @@ public class RoleService { if ("READ".equals(access)) return 1; return 0; } - private String legacyPermissionAccess(String legacy, String code) { - if ("FINANCE".equals(legacy)) { - return ("reimbursement:view-all".equals(code) || "approval:view".equals(code)) ? "READ" : "EDIT"; + private boolean isDefaultGroup(SysUserGroup group) { + return group != null && DEFAULT_EMPLOYEE_GROUP.equalsIgnoreCase(group.getGroupCode()); + } + private boolean isDynamicDefaultMember(SysUser user) { + if (user == null) return false; + SysUserGroup defaultGroup = groups.findByGroupCode(DEFAULT_EMPLOYEE_GROUP).orElse(null); + return isDefaultGroup(defaultGroup) && isActiveStatus(defaultGroup.getStatus()) + && directoryAccess != null && directoryAccess.directoryAllowed(user) + && user.getDirectoryLastSeenRunId() != null + && StringUtils.hasText(user.getFeishuOpenId()); + } + private DynamicMembership dynamicMembership() { + List allUsers = safe(users.findAll()); + com.finance.system.adapter.feishu.FeishuDirectoryAccessService.DirectoryObservation observation = + directoryAccess == null ? null : directoryAccess.captureObservation(allUsers.stream() + .filter(Objects::nonNull).map(SysUser::getId).filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new))); + String snapshotState = directoryAccess == null ? "UNAVAILABLE" : directoryAccess.snapshotState(observation); + boolean resolved = "FRESH".equals(snapshotState); + if (!resolved) return new DynamicMembership(Collections.emptyList(), false, + StringUtils.hasText(snapshotState) ? snapshotState : "UNAVAILABLE"); + List userIds = new ArrayList<>(); + for (SysUser user : allUsers) { + if (user != null && user.getId() != null + && directoryAccess.directoryAllowed(user, observation)) { + userIds.add(user.getId()); + } + } + return new DynamicMembership(userIds, true, snapshotState); + } + private Map groupDetails(SysUserGroup group, DynamicMembership suppliedDynamic) { + boolean defaultGroup = isDefaultGroup(group); + DynamicMembership dynamic = defaultGroup + ? (suppliedDynamic == null ? dynamicMembership() : suppliedDynamic) : null; + Map item = groupMap(group); + item.put("membershipMode", defaultGroup ? "DYNAMIC" : "EXPLICIT"); + if (defaultGroup) { + // Keep the unresolved state as null. A nested numeric conditional + // here is unsafe because Java may unbox the null Integer while + // reconciling it with the explicit-group int branch. + item.put("memberCount", dynamic.resolved ? Integer.valueOf(dynamic.userIds.size()) : null); + } else { + item.put("memberCount", Integer.valueOf(safe(members.findByIdGroupId(group.getId())).size())); + } + item.put("membershipResolved", !defaultGroup || dynamic.resolved); + item.put("snapshotState", defaultGroup ? dynamic.snapshotState : null); + item.put("roleCount", defaultGroup ? 1 : safe(groupRoles.findByIdGroupId(group.getId())).size()); + return item; + } + private static final class DynamicMembership { + private final List userIds; + private final boolean resolved; + private final String snapshotState; + private DynamicMembership(List userIds, boolean resolved, String snapshotState) { + this.userIds = userIds; this.resolved = resolved; this.snapshotState = snapshotState; + } + } + private static final class CandidateRow { + private final SysUser user; + private final Long assignedGroupId; + private final boolean existingMember; + private final String departmentName; + private CandidateRow(SysUser user, Long assignedGroupId, boolean existingMember, String departmentName) { + this.user = user; this.assignedGroupId = assignedGroupId; + this.existingMember = existingMember; this.departmentName = departmentName; } - return ("dashboard".equals(code) || "applications".equals(code) - || "application:view-own".equals(code) || "reimbursement:view-own".equals(code)) ? "READ" : "EDIT"; } private SysRole requireRole(Long id) { return roles.findById(id).orElseThrow(() -> new ResourceNotFoundException("角色不存在")); } private SysUserGroup requireGroup(Long id) { return groups.findById(id).orElseThrow(() -> new ResourceNotFoundException("用户组不存在")); } + private SysUserGroup requireGroupForUpdate(Long id) { return groups.findByIdForUpdate(id).orElseThrow(() -> new ResourceNotFoundException("用户组不存在")); } private SysUser requireUser(Long id) { return users.findById(id).orElseThrow(() -> new ResourceNotFoundException("用户不存在")); } - private void validateRoleIds(Collection ids) { for (Long id : ids) { SysRole r = requireRole(id); if ("INACTIVE".equalsIgnoreCase(r.getStatus())) throw new BusinessException("不能绑定停用角色", 400); } } + private void validateRoleIds(Collection ids) { for (Long id : ids) { SysRole r = requireRole(id); if (!isActiveStatus(r.getStatus())) throw new BusinessException("只能绑定启用角色", 400); } } private Map roleMap(SysRole r) { Map x = new LinkedHashMap<>(); x.put("id", r.getId()); x.put("roleCode", r.getRoleCode()); x.put("roleName", r.getRoleName()); x.put("description", r.getDescription()); x.put("status", r.getStatus()); x.put("builtIn", r.getBuiltIn()); return x; } - private Map groupMap(SysUserGroup g) { Map x = new LinkedHashMap<>(); x.put("id", g.getId()); x.put("groupCode", g.getGroupCode()); x.put("groupName", g.getGroupName()); x.put("description", g.getDescription()); x.put("status", g.getStatus()); return x; } + private Map groupMap(SysUserGroup g) { Map x = new LinkedHashMap<>(); x.put("id", g.getId()); x.put("groupCode", g.getGroupCode()); x.put("groupName", g.getGroupName()); x.put("description", g.getDescription()); x.put("status", g.getStatus()); x.put("builtIn", Boolean.TRUE.equals(g.getBuiltIn())); return x; } private Map permissionMap(List assignments) { Set ids = assignments.stream().filter(x -> x.getId() != null).map(x -> x.getId().getPermissionId()).collect(Collectors.toSet()); return permissions.findAllById(ids).stream().collect(Collectors.toMap(SysPermission::getId, x -> x)); } - private String legacyRoleCode(String type) { String x = normalize(type); return "FINANCE".equals(x) ? "FINANCE" : (ADMIN.equals(x) ? ADMIN : (SUPER_ADMIN.equals(x) ? SUPER_ADMIN : EMPLOYEE)); } private String stronger(String a, String b) { return "EDIT".equals(a) || "EDIT".equals(b) ? "EDIT" : "READ"; } + + private Map requestedAccess(Map body, Map catalog) { + Map result = new LinkedHashMap<>(); + if (body.containsKey("permissionAccess")) { + if (!(body.get("permissionAccess") instanceof Map)) throw new BusinessException("permissionAccess 必须是对象", 400); + result.putAll(stringMap(body.get("permissionAccess"))); + } else { + if (body.containsKey("permissionCodes") && !(body.get("permissionCodes") instanceof Collection)) + throw new BusinessException("permissionCodes 必须是数组", 400); + if (body.containsKey("fieldPermissions") && !(body.get("fieldPermissions") instanceof Map)) + throw new BusinessException("fieldPermissions 必须是对象", 400); + Set codes = stringSet(body.get("permissionCodes")); + Map fields = stringMap(body.get("fieldPermissions")); + for (String code : codes) { + SysPermission permission = catalog.get(code); + if (permission == null) throw new BusinessException("权限不存在: " + code, 400); + if ("FIELD".equals(permission.getPermissionType())) + throw new BusinessException("字段权限必须通过 fieldPermissions 设置", 400); + String level = normalizedAccess(permission.getDefaultAccess()); + if (level == null) throw new BusinessException("权限默认访问级别无效: " + code, 500); + result.put(code, level); + } + for (Map.Entry field : fields.entrySet()) { + SysPermission permission = catalog.get(field.getKey()); + if (permission == null) throw new BusinessException("权限不存在: " + field.getKey(), 400); + if (!"FIELD".equals(permission.getPermissionType())) + throw new BusinessException("只有字段权限可以设置 fieldPermissions", 400); + result.put(field.getKey(), field.getValue()); + } + } + for (Map.Entry entry : result.entrySet()) { + SysPermission permission = catalog.get(entry.getKey()); + if (permission == null) throw new BusinessException("权限不存在: " + entry.getKey(), 400); + if (!PERMISSION_TYPES.contains(permission.getPermissionType())) + throw new BusinessException("权限类型无效: " + entry.getKey(), 400); + if (!ACCESS_LEVELS.contains(entry.getValue())) throw new BusinessException("无效的访问级别: " + entry.getKey(), 400); + } + return result; + } + + private void addReadableAncestors(Map requested, Map catalog) { + for (String code : new ArrayList<>(requested.keySet())) { + if ("HIDDEN".equals(requested.get(code))) continue; + SysPermission child = catalog.get(code); + Set visited = new HashSet<>(); + while (child != null && StringUtils.hasText(child.getParentCode())) { + String parentCode = child.getParentCode(); + if (!visited.add(parentCode)) throw new BusinessException("权限目录存在循环: " + code, 500); + SysPermission parent = catalog.get(parentCode); + if (parent == null) throw new BusinessException("权限祖先不存在: " + parentCode, 500); + String existing = requested.get(parentCode); + if (!"EDIT".equals(existing)) requested.put(parentCode, "READ"); + child = parent; + } + } + } + + private String normalizedAccess(String value) { + if (!StringUtils.hasText(value)) return null; + String normalized = value.trim().toUpperCase(Locale.ROOT); + return ACCESS_LEVELS.contains(normalized) ? normalized : null; + } private String requiredCode(Map body, String key) { String value = requiredText(body, key); if (!value.matches("[A-Za-z0-9:_-]{2,80}")) throw new BusinessException("编码格式不正确", 400); return value.toUpperCase(Locale.ROOT); } private String requiredText(Map body, String key) { String x = text(body.get(key)); if (!StringUtils.hasText(x)) throw new BusinessException(key + "不能为空", 400); return x.trim(); } private String text(Object x) { return x == null ? null : String.valueOf(x); } private String status(Object x) { String value = StringUtils.hasText(text(x)) ? text(x).trim().toUpperCase(Locale.ROOT) : "ACTIVE"; if (!("ACTIVE".equals(value) || "INACTIVE".equals(value))) throw new BusinessException("状态必须是 ACTIVE 或 INACTIVE", 400); return value; } + private static boolean isActiveStatus(String value) { return "ACTIVE".equalsIgnoreCase(value); } + private Set strictMemberIds(Collection values, String field) { + if (values == null) throw new BusinessException(field + " 必须是数组", 400); + if (values.size() > MAX_MEMBER_IDS_PER_BIND) throw new BusinessException(field + " 数量不能超过5000", 400); + Set result = new LinkedHashSet<>(); + for (Object value : values) { + if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long)) + throw new BusinessException(field + " 必须仅包含正整数", 400); + long parsed = ((Number) value).longValue(); + if (parsed <= 0 || !result.add(parsed)) throw new BusinessException(field + " 包含无效或重复成员", 400); + } + return result; + } + private List strictDirectoryIdentities(Collection values) { + if (values == null) throw new BusinessException("directoryIdentities 必须是数组", 400); + if (values.size() > MAX_DIRECTORY_IDENTITIES_PER_BIND) + throw new BusinessException("directoryIdentities 数量不能超过200", 400); + List result = new ArrayList<>(); + Set unique = new HashSet<>(); + for (DirectoryIdentityDto identity : values) { + if (identity == null || !boundedIdentity(identity.getRevision(), 36) + || !boundedIdentity(identity.getOpenId(), 100) + || StringUtils.hasText(identity.getUserId())&&!boundedIdentity(identity.getUserId(),100)) + throw new BusinessException("目录身份格式不正确", 400); + if (!unique.add(identity)) throw new BusinessException("目录身份不能重复", 400); + result.add(identity); + } + return result; + } + private boolean boundedIdentity(String value, int max) { + return StringUtils.hasText(value) && value.equals(value.trim()) && value.length() <= max; + } private Set longSet(Collection values) { Set result = new LinkedHashSet<>(); if (values == null) return result; for (Object value : values) { try { result.add(Long.valueOf(String.valueOf(value))); } catch (Exception e) { throw new BusinessException("ID 列表包含无效值", 400); } } return result; } private Set stringSet(Object values) { Set result = new LinkedHashSet<>(); if (values instanceof Collection) for (Object x : (Collection) values) if (StringUtils.hasText(text(x))) result.add(text(x).trim()); return result; } private Map stringMap(Object values) { Map result = new LinkedHashMap<>(); if (values instanceof Map) for (Map.Entry e : ((Map) values).entrySet()) result.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()).toUpperCase(Locale.ROOT)); return result; } diff --git a/src/main/java/com/finance/system/service/ScheduledTaskPoller.java b/src/main/java/com/finance/system/service/ScheduledTaskPoller.java new file mode 100644 index 0000000..f9939f4 --- /dev/null +++ b/src/main/java/com/finance/system/service/ScheduledTaskPoller.java @@ -0,0 +1,23 @@ +package com.finance.system.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class ScheduledTaskPoller { + private final ScheduledTaskService tasks; + + @Scheduled(fixedDelayString = "${scheduled-tasks.poll-delay-ms:30000}", + initialDelayString = "${scheduled-tasks.initial-delay-ms:5000}") + public void poll() { + try { + tasks.claimDue(); + } catch (RuntimeException failure) { + log.warn("Scheduled task poll failed", failure); + } + } +} diff --git a/src/main/java/com/finance/system/service/ScheduledTaskService.java b/src/main/java/com/finance/system/service/ScheduledTaskService.java new file mode 100644 index 0000000..9746464 --- /dev/null +++ b/src/main/java/com/finance/system/service/ScheduledTaskService.java @@ -0,0 +1,223 @@ +package com.finance.system.service; + +import com.finance.system.adapter.feishu.FeishuDirectoryRunStore; +import com.finance.system.adapter.feishu.FeishuDirectoryService; +import com.finance.system.adapter.feishu.FeishuDirectorySyncDispatcher; +import com.finance.system.dto.ScheduledTaskRunDto; +import com.finance.system.exception.BusinessException; +import lombok.Data; +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 java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +@Service +public class ScheduledTaskService { + public static final String FEISHU = "FEISHU_DIRECTORY_SYNC"; + private static final Set INTERVALS = new HashSet<>(Arrays.asList(1, 2, 3, 6, 12, 24)); + private static final String RUN_COLUMNS = "run_id,trigger_type,state,queued_at,started_at,finished_at,attempt_count,complete,applied," + + "departments,users_seen,eligible,excluded,created,updated,ineligible,out_of_scope,error_code,error_message"; + + private final JdbcTemplate jdbc; + private final FeishuDirectoryRunStore runs; + private final FeishuDirectorySyncDispatcher dispatcher; + private final TransactionTemplate tx; + + public ScheduledTaskService(JdbcTemplate jdbc, PlatformTransactionManager manager, + FeishuDirectoryRunStore runs, FeishuDirectorySyncDispatcher dispatcher) { + this.jdbc = jdbc; + this.runs = runs; + this.dispatcher = dispatcher; + this.tx = new TransactionTemplate(manager); + this.tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.tx.setTimeout(10); + } + + public List> list() { + return Collections.singletonList(detail(FEISHU)); + } + + public Map detail(String code) { + requireCode(code); + Map row = jdbc.queryForMap( + "SELECT task_code,display_name,enabled,interval_hours,time_zone,next_due_at,last_claimed_at,version,updated_at " + + "FROM sys_scheduled_task WHERE task_code=?", code); + Map result = new LinkedHashMap<>(); + result.put("code", row.get("task_code")); + result.put("name", row.get("display_name")); + result.put("enabled", row.get("enabled")); + result.put("intervalHours", row.get("interval_hours")); + result.put("timeZone", row.get("time_zone")); + result.put("nextDueAt", instant(row.get("next_due_at"))); + result.put("lastClaimedAt", instant(row.get("last_claimed_at"))); + result.put("version", row.get("version")); + result.put("status", active() ? "RUNNING" : "IDLE"); + return result; + } + + public Map update(String code, ScheduleRequest request) { + requireCode(code); + if (request == null || request.version == null || request.enabled == null + || request.intervalHours == null || !INTERVALS.contains(request.intervalHours)) { + throw new BusinessException("Invalid schedule configuration", 400); + } + tx.execute(status -> { + List> rows = jdbc.queryForList( + "SELECT enabled,version FROM sys_scheduled_task WHERE task_code=? FOR UPDATE", code); + if (rows.size() != 1 || ((Number) rows.get(0).get("version")).longValue() != request.version) { + throw new BusinessException("Schedule configuration changed; refresh and retry", 409); + } + boolean wasEnabled = bool(rows.get(0).get("enabled")); + long delay = !wasEnabled && request.enabled ? 60L : request.intervalHours * 3600L; + Timestamp now = databaseNow(); + Timestamp next = request.enabled ? Timestamp.from(now.toInstant().plusSeconds(delay)) : null; + jdbc.update("UPDATE sys_scheduled_task SET enabled=?,interval_hours=?,next_due_at=?,version=version+1,updated_at=? WHERE task_code=?", + request.enabled, request.intervalHours, next, now, code); + return null; + }); + return detail(code); + } + + public ScheduledTaskRunDto execute(String code) { + requireCode(code); + FeishuDirectoryService.Run accepted = runs.enqueue("MANUAL"); + ScheduledTaskRunDto run = tx.execute(status -> loadPublicRun(accepted.getRunId())); + dispatcher.wake(); + return run; + } + + /** Cluster-safe due claim. Advancing from DB now coalesces all downtime into one run. */ + public boolean claimDue() { + Boolean queued = tx.execute(status -> { + List> rows = jdbc.queryForList( + "SELECT enabled,interval_hours,next_due_at FROM sys_scheduled_task WHERE task_code=? FOR UPDATE", FEISHU); + if (rows.isEmpty() || !bool(rows.get(0).get("enabled"))) return false; + + Timestamp now = databaseNow(); + Timestamp due = (Timestamp) rows.get(0).get("next_due_at"); + if (due != null && due.after(now)) return false; + + jdbc.queryForMap("SELECT id FROM feishu_directory_state WHERE id=1 FOR UPDATE"); + int hours = ((Number) rows.get(0).get("interval_hours")).intValue(); + Timestamp next = Timestamp.from(now.toInstant().plusSeconds(hours * 3600L)); + jdbc.update("UPDATE sys_scheduled_task SET next_due_at=?,last_claimed_at=?,version=version+1,updated_at=? WHERE task_code=?", + next, now, now, FEISHU); + + Integer active = jdbc.queryForObject( + "SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class); + if (active != null && active > 0) return false; + + jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger_type,state,queued_at,started_at,complete,applied) " + + "VALUES (?,'SCHEDULED','QUEUED',?,NULL,FALSE,FALSE)", + UUID.randomUUID().toString(), now); + return true; + }); + if (Boolean.TRUE.equals(queued)) dispatcher.wake(); + return Boolean.TRUE.equals(queued); + } + + public Map runs(String code, int page, int size) { + requireCode(code); + if (page < 0 || size < 1 || size > 100 || page > Integer.MAX_VALUE / size) { + throw new BusinessException("Invalid pagination", 400); + } + int offset = page * size; + Integer total = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run", Integer.class); + List items = new ArrayList<>(); + List> rows = jdbc.queryForList( + "SELECT " + RUN_COLUMNS + + " FROM feishu_directory_sync_run ORDER BY queued_at DESC,run_id DESC LIMIT ? OFFSET ?", size, offset); + for (Map row : rows) items.add(publicRun(row)); + + Map result = new LinkedHashMap<>(); + result.put("items", items); + result.put("page", page); + result.put("size", size); + result.put("total", total); + return result; + } + + private ScheduledTaskRunDto loadPublicRun(String runId) { + return publicRun(jdbc.queryForMap( + "SELECT " + RUN_COLUMNS + " FROM feishu_directory_sync_run WHERE run_id=?", runId)); + } + + private ScheduledTaskRunDto publicRun(Map row) { + ScheduledTaskRunDto result = new ScheduledTaskRunDto(); + result.setRunId(String.valueOf(row.get("run_id"))); + result.setTrigger(String.valueOf(row.get("trigger_type"))); + String state = String.valueOf(row.get("state")); + result.setState("QUEUED".equals(state) ? "RUNNING" : state); + result.setQueuedAt(instant(row.get("queued_at"))); + result.setStartedAt(instant(row.get("started_at"))); + result.setFinishedAt(instant(row.get("finished_at"))); + result.setAttempts(number(row.get("attempt_count"))); + result.setComplete(bool(row.get("complete"))); + result.setApplied(bool(row.get("applied"))); + ScheduledTaskRunDto.Counts counts = new ScheduledTaskRunDto.Counts(); + counts.setDepartments(number(row.get("departments"))); + counts.setUsersSeen(number(row.get("users_seen"))); + counts.setEligible(number(row.get("eligible"))); + counts.setExcluded(number(row.get("excluded"))); + counts.setCreated(number(row.get("created"))); + counts.setUpdated(number(row.get("updated"))); + counts.setIneligible(number(row.get("ineligible"))); + counts.setOutOfScope(number(row.get("out_of_scope"))); + result.setCounts(counts); + result.setErrorCode(row.get("error_code") == null ? null : String.valueOf(row.get("error_code"))); + result.setErrorMessage(sanitize(row.get("error_message"))); + return result; + } + + private boolean active() { + Integer count = jdbc.queryForObject( + "SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class); + return count != null && count > 0; + } + + private Timestamp databaseNow() { + return jdbc.queryForObject("SELECT CURRENT_TIMESTAMP", Timestamp.class); + } + + private static boolean bool(Object value) { + return Boolean.TRUE.equals(value) || value instanceof Number && ((Number) value).intValue() != 0; + } + + private static int number(Object value) { + return value == null ? 0 : ((Number) value).intValue(); + } + + private static String instant(Object value) { + return value instanceof Timestamp ? ((Timestamp) value).toInstant().toString() : null; + } + + private static String sanitize(Object value) { + if (value == null) return null; + String sanitized = String.valueOf(value).replaceAll("[\\r\\n\\t]", " "); + return sanitized.length() > 500 ? sanitized.substring(0, 500) : sanitized; + } + + private static void requireCode(String code) { + if (!FEISHU.equals(code)) throw new BusinessException("Scheduled task not found", 404); + } + + @Data + public static class ScheduleRequest { + private Boolean enabled; + private Integer intervalHours; + private Long version; + } +} diff --git a/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java b/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java index 47ba21d..d766bfc 100644 --- a/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java @@ -39,10 +39,9 @@ public class DashboardServiceImpl implements DashboardService { @Override public DashboardStats getDashboardStats(Long userId) { if (userId == null) throw new UnauthorizedException("未登录"); - SysUser user = sysUserRepository.findById(userId).orElse(null); List applications; - boolean viewAll = canViewAll(userId, user); + boolean viewAll = canViewAll(userId); if (viewAll) { // 财务人员查看所有申请 applications = reimApplicationRepository.findAll(); @@ -95,7 +94,7 @@ public class DashboardServiceImpl implements DashboardService { public List getRecentApplications(Long userId, int limit) { if (userId == null) throw new UnauthorizedException("未登录"); List applications; - if (canViewAll(userId, sysUserRepository.findById(userId).orElse(null))) { + if (canViewAll(userId)) { int safeLimit = Math.max(1, Math.min(limit, 100)); applications = reimApplicationRepository.findAll().stream() .sorted((left, right) -> { @@ -111,15 +110,22 @@ public class DashboardServiceImpl implements DashboardService { return applications.stream().map(this::buildSummary).collect(Collectors.toList()); } - private boolean canViewAll(Long userId, SysUser user) { + private boolean canViewAll(Long userId) { if (roleService != null) { - return roleService.hasPermission(userId, "reimbursement:view-all") + return roleService.hasPermission(userId, "page.finance-receipt") + || roleService.hasPermission(userId, "page.source-documents") + || roleService.hasPermission(userId, "page.payments") + || roleService.hasPermission(userId, "finance.receipt.confirm") + || roleService.hasPermission(userId, "finance.approval.decide") + || roleService.hasPermission(userId, "finance.payment.register") + // Legacy codes remain during the RBAC migration window. + || roleService.hasPermission(userId, "reimbursement:view-all") || roleService.hasPermission(userId, "receipt:manage") || roleService.hasPermission(userId, "payment:register") || roleService.hasPermission(userId, "approval:view"); } - // Narrow compatibility fallback for isolated legacy unit construction. - return user != null && "FINANCE".equalsIgnoreCase(user.getUserType()); + // Missing authorization infrastructure must never widen data scope. + return false; } private ReimApplicationSummary buildSummary(ReimApplication app) { diff --git a/src/main/java/com/finance/system/service/impl/MySqlPaymentIdempotencyLock.java b/src/main/java/com/finance/system/service/impl/MySqlPaymentIdempotencyLock.java new file mode 100644 index 0000000..de97a17 --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/MySqlPaymentIdempotencyLock.java @@ -0,0 +1,57 @@ +package com.finance.system.service.impl; + +import com.finance.system.service.PaymentIdempotencyLock; +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +/** Holds an InnoDB row lock until the caller's payment transaction completes. */ +@Component +@RequiredArgsConstructor +public class MySqlPaymentIdempotencyLock implements PaymentIdempotencyLock { + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + + @Override + public void lock(String normalizedIdempotencyKey) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("付款幂等锁必须在数据库事务内获取"); + } + String product = databaseProduct(); + if ("MySQL".equalsIgnoreCase(product)) { + jdbcTemplate.update("INSERT INTO payment_idempotency_lock(lock_key,created_at,updated_at) " + + "VALUES (?,CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6)) " + + "ON DUPLICATE KEY UPDATE updated_at=updated_at", + normalizedIdempotencyKey); + } else if ("H2".equalsIgnoreCase(product)) { + jdbcTemplate.update("MERGE INTO payment_idempotency_lock(lock_key,created_at,updated_at) " + + "KEY(lock_key) VALUES (?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", + normalizedIdempotencyKey); + } else { + throw new IllegalStateException("不支持的数据库,拒绝跳过付款幂等锁: " + product); + } + String locked = jdbcTemplate.queryForObject( + "SELECT lock_key FROM payment_idempotency_lock WHERE lock_key=? FOR UPDATE", + String.class, normalizedIdempotencyKey); + if (!normalizedIdempotencyKey.equals(locked)) { + throw new IllegalStateException("付款幂等锁获取失败"); + } + } + + private String databaseProduct() { + Connection connection = DataSourceUtils.getConnection(dataSource); + try { + return connection.getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + throw new IllegalStateException("无法识别数据库类型,拒绝跳过付款幂等锁", e); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } +} diff --git a/src/main/java/com/finance/system/service/impl/PostgresPaymentIdempotencyLock.java b/src/main/java/com/finance/system/service/impl/PostgresPaymentIdempotencyLock.java deleted file mode 100644 index f1c2701..0000000 --- a/src/main/java/com/finance/system/service/impl/PostgresPaymentIdempotencyLock.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.finance.system.service.impl; - -import com.finance.system.service.PaymentIdempotencyLock; -import lombok.RequiredArgsConstructor; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementCallback; -import org.springframework.jdbc.datasource.DataSourceUtils; -import org.springframework.stereotype.Component; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** PostgreSQL transaction-level advisory lock with a no-op H2 fallback. */ -@Component -@RequiredArgsConstructor -public class PostgresPaymentIdempotencyLock implements PaymentIdempotencyLock { - private final JdbcTemplate jdbcTemplate; - private final DataSource dataSource; - private volatile Boolean postgres; - - @Override - public void lock(String normalizedIdempotencyKey) { - if (!isPostgres()) return; - jdbcTemplate.execute("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", - (PreparedStatementCallback) statement -> { - statement.setString(1, normalizedIdempotencyKey); - statement.execute(); - return null; - }); - } - - private boolean isPostgres() { - Boolean cached = postgres; - if (cached != null) return cached; - Connection connection = DataSourceUtils.getConnection(dataSource); - try { - boolean detected = "PostgreSQL".equalsIgnoreCase( - connection.getMetaData().getDatabaseProductName()); - postgres = detected; - return detected; - } catch (SQLException e) { - throw new IllegalStateException("无法识别数据库类型,拒绝跳过幂等锁", e); - } finally { - DataSourceUtils.releaseConnection(connection, dataSource); - } - } -} diff --git a/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java index 5d69add..fc394ea 100644 --- a/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java @@ -32,6 +32,7 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class ReimApplicationServiceImpl implements ReimApplicationService { + private static final long FEISHU_CREATING_LEASE_SECONDS = 120L; private final ReimApplicationRepository reimApplicationRepository; private final SysUserRepository sysUserRepository; @@ -47,6 +48,10 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { private final KingdeeConfig kingdeeConfig; private RoleService roleService; private FeishuApprovalService feishuApprovalService; + private ReimbursementRoutePreviewService routePreviewService; + private ReimbursementSubmissionCoordinator submissionCoordinator; + private IntFeishuApprovalRepository feishuApprovalRepository; + private FeishuInstanceTimelineNodeRepository timelineNodeRepository; @Autowired(required = false) public void setRoleService(RoleService roleService) { @@ -58,9 +63,79 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { this.feishuApprovalService = feishuApprovalService; } + @Autowired(required = false) + public void setRoutePreviewService(ReimbursementRoutePreviewService routePreviewService) { + this.routePreviewService = routePreviewService; + } + + @Autowired(required = false) + public void setSubmissionCoordinator(ReimbursementSubmissionCoordinator submissionCoordinator) { + this.submissionCoordinator = submissionCoordinator; + } + + @Autowired(required = false) + public void setFeishuApprovalRepository(IntFeishuApprovalRepository repository) { + this.feishuApprovalRepository = repository; + } + + @Autowired(required = false) + public void setTimelineNodeRepository(FeishuInstanceTimelineNodeRepository repository) { + this.timelineNodeRepository = repository; + } + @Override + @Transactional + public RoutePreviewDto previewRoute(Long id, Long userId) { + requireEditPermission(userId, "reimbursement.application.edit"); + // This application-row lock serializes concurrent token issuance and the + // Phase-A create intent for the same reimbursement. + ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ensureOwner(app, userId); + if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { + throw new BusinessException("只能预览可编辑草稿的审批路线", 409); + } + validatePersistedApplication(app); + if (routePreviewService == null) throw new BusinessException("审批路线预览服务不可用", 503); + IntFeishuApproval intent = feishuApprovalRepository == null ? null + : feishuApprovalRepository.findByApplicationIdForUpdate(app.getId()).orElse(null); + if (intent != null && "CREATING".equals(intent.getStatus())) { + LocalDateTime cutoff = LocalDateTime.now().minusSeconds(FEISHU_CREATING_LEASE_SECONDS); + if (intent.getCreateStartedAt() == null || intent.getCreateStartedAt().isAfter(cutoff)) + throw new BusinessException("飞书审批正在创建,暂不能重新预览", 409); + intent.setStatus("CREATE_OUTCOME_UNKNOWN"); + intent.setSyncedAt(LocalDateTime.now()); + feishuApprovalRepository.save(intent); + } + if (intent != null && ("CREATE_OUTCOME_UNKNOWN".equals(intent.getStatus()) + || "CREATED".equals(intent.getStatus()))) + return routePreviewService.previewRecovery(app, userId, intent); + return routePreviewService.preview(app, userId); + } + + @Override + public List getRouteTimeline(Long id, Long userId) { + requirePermission(userId, "page.applications", "page.application-edit", "page.finance-receipt"); + ReimApplication app = reimApplicationRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ensureCanRead(app, userId); + if (feishuApprovalRepository == null || timelineNodeRepository == null) return Collections.emptyList(); + IntFeishuApproval mapping = feishuApprovalRepository.findByApplicationId(id).orElse(null); + if (mapping == null || !org.springframework.util.StringUtils.hasText(mapping.getFeishuInstanceCode())) + return Collections.emptyList(); + return timelineNodeRepository.findByFeishuApprovalIdAndInstanceCodeOrderByNodeOrderAscIdAsc( + mapping.getId(), mapping.getFeishuInstanceCode()).stream().map(node -> RouteTimelineNodeDto.builder() + .order(node.getNodeOrder()).nodeName(node.getNodeName()).nodeType(node.getNodeType()) + .approvalMode(node.getApprovalMode()).planned(Boolean.TRUE.equals(node.getPlanned())) + .status(node.getStatus()).approverLabel(node.getApproverLabel()).comment(node.getComment()) + .actionTime(node.getActionTime()).build()).collect(Collectors.toList()); + } + + @Override + @Transactional(readOnly = true) public WorkbenchDto getWorkbench(Long userId) { - requirePermission(userId, "reimbursement:view-own", "application:view-own"); + requirePermission(userId, "page.dashboard", "page.applications", "page.application-create", + "page.application-edit", "page.finance-receipt", "page.payments"); SysUser user = sysUserRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); @@ -89,7 +164,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override public Page getMyApplications(Long userId, String status, Pageable pageable) { - requirePermission(userId, "reimbursement:view-own", "application:view-own"); + requirePermission(userId, "page.applications"); Page applications; if (status != null && !status.isEmpty() && !"ALL".equalsIgnoreCase(status)) { if (ApplicationStatus.DRAFT.name().equalsIgnoreCase(status)) { @@ -107,8 +182,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override public ReimApplicationDetail getApplicationDetail(Long id, Long userId) { - requirePermission(userId, "reimbursement:view-own", "application:view-own", - "reimbursement:view-all", "approval:view"); + requirePermission(userId, "page.applications", "page.application-edit", "page.finance-receipt"); ReimApplication app = reimApplicationRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); ensureCanRead(app, userId); @@ -117,8 +191,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override public ReimApplicationDetail getByApplicationNo(String applicationNo, Long userId) { - requirePermission(userId, "reimbursement:view-own", "application:view-own", - "reimbursement:view-all", "approval:view"); + requirePermission(userId, "page.applications", "page.application-edit", "page.finance-receipt"); ReimApplication app = reimApplicationRepository.findByApplicationNo(applicationNo); if (app == null) { throw new ResourceNotFoundException("报销申请不存在: " + applicationNo); @@ -130,7 +203,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override @Transactional public ReimApplicationDetail createApplication(CreateApplicationRequest request, Long userId) { - requirePermission(userId, "reimbursement:create", "application:create"); + requireEditPermission(userId, "reimbursement.application.create"); SysUser user = sysUserRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); validateFieldPermissions(request, userId, null, true); @@ -167,11 +240,12 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override @Transactional public ReimApplicationDetail updateApplication(Long id, CreateApplicationRequest request, Long userId) { - ReimApplication app = reimApplicationRepository.findById(id) + ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - requirePermission(userId, "reimbursement:create", "application:create"); + requireEditPermission(userId, "reimbursement.application.edit"); ensureOwner(app, userId); + ensureNoCreationInProgress(app.getId()); if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { if (!ApprovalStatus.REJECTED.name().equals(app.getApprovalStatus()) && !ApprovalStatus.CANCELLED.name().equals(app.getApprovalStatus())) { @@ -205,71 +279,14 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { } @Override - @Transactional public ReimApplicationDetail submitApplication(Long id, Long userId) { - // Lock the application for the whole local-plus-Feishu transition so - // concurrent submit requests cannot both pass the DRAFT check and - // create two remote instances. - ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - - requirePermission(userId, "reimbursement:create", "application:create"); - ensureOwner(app, userId); - if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus()) - && !ApprovalStatus.CANCELLED.name().equals(app.getApprovalStatus())) { - throw new BusinessException("只能提交草稿或退回状态的申请"); - } - validatePersistedApplication(app); - - boolean useFeishuApproval = feishuApprovalService != null - && feishuApprovalService.isApprovalEnabledAndConfigured(); - SysApprovalNode firstNode = null; - Long firstApproverId = null; - if (!useFeishuApproval) { - List nodes = sysApprovalNodeRepository.findAllByOrderBySortOrder(); - for (SysApprovalNode candidate : nodes) { - if (!ApprovalRoutingRules.isApprovalNode(candidate)) { - continue; - } - Long candidateApproverId = resolveApprover(candidate); - if (candidateApproverId != null) { - firstNode = candidate; - firstApproverId = candidateApproverId; - break; - } - } - if (firstNode == null || firstApproverId == null) { - throw new BusinessException("当前审批节点未配置有效审批人,无法提交"); - } - } - - app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); - app.setApprovalStatus(ApprovalStatus.PENDING.name()); - app.setSubmitTime(LocalDateTime.now()); - - if (useFeishuApproval) { - app.setCurrentApprovalNode("飞书审批"); - app.setCurrentApproverId(null); - } else { - // 设置第一个审批节点为"应付会计审核" - app.setCurrentApprovalNode(firstNode.getNodeName()); - app.setCurrentApproverId(firstApproverId); - } - - // 占用预算 - app.setBudgetStatus(BudgetStatus.OCCUPIED.name()); - - app = reimApplicationRepository.save(app); - - // The enclosing transaction rolls the local submission back when the - // external creation fails, so a caller never gets a submitted - // application without a persisted Feishu sync record. The Feishu - // service also checks the application mapping before creating a new - // remote instance, making retries idempotent. - if (useFeishuApproval) { - feishuApprovalService.createApprovalInstance(app); - } + throw new BusinessException("提交前必须获取审批路线预览", 400); + } + @Override + public ReimApplicationDetail submitApplication(Long id, Long userId, String previewToken) { + if (submissionCoordinator == null) throw new BusinessException("审批提交服务不可用", 503); + ReimApplication app = submissionCoordinator.submit(id, userId, previewToken); log.info("提交报销申请: applicationNo={}", app.getApplicationNo()); return buildDetail(app); } @@ -278,7 +295,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Transactional public ReimApplicationDetail receiveApplication(Long id, Long operatorId) { Long currentUserId = AuditUtil.getCurrentUserId(); - boolean permitted = roleService != null ? roleService.hasPermission(operatorId, "receipt:manage") + boolean permitted = roleService != null ? roleService.hasEditPermission(operatorId, "finance.receipt.confirm") : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); if (operatorId == null || !operatorId.equals(currentUserId) || !permitted) { throw new com.finance.system.exception.UnauthorizedException("仅财务人员可以确认收单"); @@ -318,11 +335,12 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override @Transactional public void deleteApplication(Long id, Long userId) { - ReimApplication app = reimApplicationRepository.findById(id) + ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - requirePermission(userId, "reimbursement:create", "application:create"); + requireEditPermission(userId, "reimbursement.application.edit"); ensureOwner(app, userId); + ensureNoCreationInProgress(app.getId()); if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { throw new BusinessException("只能删除草稿状态的申请"); } @@ -403,11 +421,18 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { } } + private void ensureNoCreationInProgress(Long applicationId) { + if (feishuApprovalRepository == null) return; + IntFeishuApproval mapping = feishuApprovalRepository.findByApplicationId(applicationId).orElse(null); + if (mapping != null && ("CREATING".equals(mapping.getStatus()) || "CREATED".equals(mapping.getStatus()) + || "CREATE_OUTCOME_UNKNOWN".equals(mapping.getStatus()))) + throw new BusinessException("飞书审批正在创建,暂不能修改或删除", 409); + } + private void ensureCanRead(ReimApplication app, Long currentId) { if (currentId == null) throw new com.finance.system.exception.UnauthorizedException("未登录"); if (currentId.equals(app.getApplicantId())) return; - if (roleService != null && (roleService.hasPermission(currentId, "reimbursement:view-all") - || roleService.hasPermission(currentId, "approval:view"))) return; + if (roleService != null && roleService.hasPermission(currentId, "page.finance-receipt")) return; if (roleService == null && (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole())) return; throw new org.springframework.security.access.AccessDeniedException("无权访问该申请"); } @@ -421,6 +446,13 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { throw new org.springframework.security.access.AccessDeniedException("权限不足,无法访问"); } + private void requireEditPermission(Long userId, String permissionCode) { + if (userId == null) throw new com.finance.system.exception.UnauthorizedException("未登录"); + if (roleService == null) return; // retained for narrow legacy unit tests + if (!roleService.hasEditPermission(userId, permissionCode)) + throw new org.springframework.security.access.AccessDeniedException("权限不足,无法写入"); + } + private void validateFieldPermissions(CreateApplicationRequest request, Long userId, ReimApplication existing, boolean creating) { if (roleService == null) return; @@ -544,7 +576,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { List users = roleService == null ? sysUserRepository.findByUserType("FINANCE") : sysUserRepository.findAll(); for (SysUser user : users) { - if ((roleService == null || roleService.hasPermission(user.getId(), "approval:view")) + if ((roleService == null || roleService.hasEditPermission(user.getId(), "finance.approval.decide")) && ApprovalRoutingRules.matchesRole(user, role)) return user.getId(); } return null; diff --git a/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java index b59e92e..797fbe4 100644 --- a/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java @@ -196,7 +196,7 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { private void ensureCurrentApprover(ReimApplication app, Long approverId) { Long actorId = AuditUtil.getCurrentUserId(); - boolean permitted = roleService != null ? roleService.hasPermission(approverId, "approval:view") + boolean permitted = roleService != null ? roleService.hasEditPermission(approverId, "finance.approval.decide") : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); if (approverId == null || (actorId != null && !approverId.equals(actorId)) || !permitted) { throw new com.finance.system.exception.UnauthorizedException("无审批权限"); @@ -231,7 +231,7 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { List users = roleService == null ? sysUserRepository.findByUserType("FINANCE") : sysUserRepository.findAll(); for (SysUser user : users) { - if ((roleService == null || roleService.hasPermission(user.getId(), "approval:view")) + if ((roleService == null || roleService.hasEditPermission(user.getId(), "finance.approval.decide")) && ApprovalRoutingRules.matchesRole(user, node.getApproverRole())) return user.getId(); } return null; diff --git a/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java index 1a4b1fc..6de4bbc 100644 --- a/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java @@ -3,6 +3,7 @@ package com.finance.system.service.impl; import com.finance.system.dto.*; import com.finance.system.entity.*; import com.finance.system.enums.PaymentStatus; +import com.finance.system.exception.BadRequestException; import com.finance.system.exception.BusinessException; import com.finance.system.exception.ResourceNotFoundException; import com.finance.system.repository.*; @@ -116,17 +117,17 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { } private PaymentResultDto executePaymentInternal(Long applicationId, BigDecimal amount, Long operatorId, - String paymentMethod, String referenceNo, String remark, - String idempotencyKey, boolean requireFullPayment, boolean partialOnly) { + String paymentMethod, String referenceNo, String remark, + String idempotencyKey, boolean requireFullPayment, boolean partialOnly) { requirePaymentPermission(operatorId); if (operatorId == null || !operatorId.equals(AuditUtil.getCurrentUserId())) { throw new com.finance.system.exception.UnauthorizedException("无权使用其他用户身份付款"); } + String normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey); ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - String normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey); if (normalizedIdempotencyKey != null) { - // Acquire the transaction-scoped PostgreSQL advisory lock before + // Acquire the transaction-scoped database lock before // reading the key. This serializes claims across application rows. paymentIdempotencyLock.lock(normalizedIdempotencyKey); ReimPayment existing = reimPaymentRepository.findByIdempotencyKey(normalizedIdempotencyKey); @@ -242,7 +243,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { } private void requirePaymentPermission(Long operatorId) { - boolean permitted = roleService != null ? roleService.hasPermission(operatorId, "payment:register") + boolean permitted = roleService != null ? roleService.hasEditPermission(operatorId, "finance.payment.register") : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); if (!permitted) throw new com.finance.system.exception.UnauthorizedException("仅财务人员可以登记付款"); } @@ -268,8 +269,11 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { } private String normalizeIdempotencyKey(String idempotencyKey) { - if (idempotencyKey == null || idempotencyKey.trim().isEmpty()) return null; - return idempotencyKey.trim(); + if (idempotencyKey == null) return null; + String normalized = idempotencyKey.trim(); + if (normalized.isEmpty()) throw new BadRequestException("幂等键不能为空"); + if (normalized.length() > 100) throw new BadRequestException("幂等键长度不能超过100个字符"); + return normalized; } private PaymentTaskDto buildPaymentTask(ReimApplication app) { diff --git a/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java b/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java new file mode 100644 index 0000000..1996c1c --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java @@ -0,0 +1,293 @@ +package com.finance.system.service.impl; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.finance.system.adapter.feishu.FeishuApprovalService; +import com.finance.system.dto.RoutePreviewDto; +import com.finance.system.entity.*; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.*; +import com.finance.system.service.ReimbursementFingerprintService; +import com.finance.system.service.RoleService; +import com.finance.system.util.Sha256; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.security.SecureRandom; +import java.time.*; +import java.util.*; + +@Service +@RequiredArgsConstructor +public class ReimbursementRoutePreviewService { + public static final String INVALID_PREVIEW = "审批路线预览已失效,请重新预览"; + private static final Duration TOKEN_TTL = Duration.ofMinutes(10); + private static final SecureRandom RANDOM = new SecureRandom(); + private static final int MAX_ROUTE_NODES = 100; + private static final int MAX_APPROVERS_PER_NODE = 50; + + private final FeishuApprovalService feishu; + private final FeishuApprovalDefinitionSnapshotRepository snapshots; + private final FeishuApprovalDefinitionNodeRepository definitionNodes; + private final FeishuApprovalDefinitionApproverRepository definitionApprovers; + private final ReimRoutePreviewTokenRepository tokens; + private final SysApprovalNodeRepository localNodes; + private final SysUserRepository users; + private final RoleService roles; + private final ReimbursementFingerprintService fingerprints; + private final ObjectMapper objectMapper; + + @Value("${feishu.approval.snapshot-max-age-seconds:86400}") + private long snapshotMaxAgeSeconds; + + @Transactional + public RoutePreviewDto preview(ReimApplication application, Long userId) { + Route route = currentRoute(false); + return issue(application, userId, route, fingerprints.fingerprint(application)); + } + + /** Unknown remote outcome must display and authorize the immutable original route, never today's definition. */ + @Transactional + public RoutePreviewDto previewRecovery(ReimApplication application, Long userId, IntFeishuApproval intent) { + if (intent == null || !("CREATE_OUTCOME_UNKNOWN".equals(intent.getStatus()) + || "CREATED".equals(intent.getStatus())) + || !"FEISHU".equals(intent.getRouteSource()) || !StringUtils.hasText(intent.getRoutePlan()) + || !StringUtils.hasText(intent.getFeishuApprovalCode())) throw invalid(); + List nodes = nodesFromPlan(intent.getRoutePlan()); + Route route = new Route("FEISHU", nodes, intent.getRouteFingerprint(), intent.getSnapshotFingerprint(), + null, true, false, "上次创建结果未知;本次将使用原审批定义、原路线和原请求标识恢复提交", + null, null, null, null, intent.getFeishuApprovalCode()); + return issue(application, userId, route, intent.getApplicationFingerprint()); + } + + private RoutePreviewDto issue(ReimApplication application, Long userId, Route route, String applicationFingerprint) { + String tokenValue = randomToken(); + LocalDateTime now = LocalDateTime.now(); + LocalDateTime expiresAt = now.plus(TOKEN_TTL); + tokens.deleteByExpiresAtBeforeOrConsumedAtIsNotNull(now); + tokens.deleteByApplicationIdAndUserId(application.getId(), userId); + tokens.save(ReimRoutePreviewToken.builder().tokenHash(Sha256.hex(tokenValue)) + .applicationId(application.getId()).userId(userId).routeSource(route.source) + .approvalCode(route.approvalCode).applicationFingerprint(applicationFingerprint) + .routeFingerprint(route.fingerprint).snapshotFingerprint(route.snapshotFingerprint) + .routePlan(writePlan(route.nodes)).firstApproverId(route.firstApproverId) + .firstNodeId(route.firstNodeId).firstApproverRole(route.firstApproverRole) + .firstNodeName(route.firstNodeName).createdAt(now).expiresAt(expiresAt).build()); + return RoutePreviewDto.builder().applicationId(application.getId()).source(route.source) + .nodes(route.nodes).routeFingerprint(route.fingerprint) + .snapshotFingerprint(route.snapshotFingerprint).previewToken(tokenValue) + .expiresAt(expiresAt).snapshotFetchedAt(route.snapshotFetchedAt) + .staleSnapshot(route.stale).exact(route.exact).warning(route.warning).build(); + } + + /** Called only while the reimbursement is pessimistically locked. */ + @Transactional + public ReimRoutePreviewToken validateForSubmit(ReimApplication application, Long userId, String rawToken) { + if (!StringUtils.hasText(rawToken) || rawToken.length() > 512) throw invalid(); + ReimRoutePreviewToken token = tokens.findByTokenHashForUpdate(Sha256.hex(rawToken)) + .orElseThrow(this::invalid); + if (!Objects.equals(token.getApplicationId(), application.getId()) + || !Objects.equals(token.getUserId(), userId) || token.getConsumedAt() != null + || token.getExpiresAt() == null || !token.getExpiresAt().isAfter(LocalDateTime.now())) throw invalid(); + Route current = currentRoute(true); + if (!Objects.equals(token.getApplicationFingerprint(), fingerprints.fingerprint(application)) + || !Objects.equals(token.getRouteSource(), current.source) + || !Objects.equals(token.getApprovalCode(), current.approvalCode) + || !Objects.equals(token.getRouteFingerprint(), current.fingerprint) + || !Objects.equals(token.getSnapshotFingerprint(), current.snapshotFingerprint)) throw invalid(); + nodesFromToken(token); // reject corrupted/oversized persisted plans + return token; + } + + /** Resume validation deliberately ignores mutable directory labels; Phase A's content hash proves no user edit. */ + @Transactional + public ReimRoutePreviewToken validateForUnknownResume(ReimApplication application, Long userId, String rawToken) { + if (!StringUtils.hasText(rawToken) || rawToken.length() > 512) throw invalid(); + ReimRoutePreviewToken token = tokens.findByTokenHashForUpdate(Sha256.hex(rawToken)).orElseThrow(this::invalid); + if (!Objects.equals(token.getApplicationId(), application.getId()) || !Objects.equals(token.getUserId(), userId) + || token.getConsumedAt() != null || token.getExpiresAt() == null + || !token.getExpiresAt().isAfter(LocalDateTime.now()) || !"FEISHU".equals(token.getRouteSource())) throw invalid(); + return token; + } + + public String applicationFingerprint(ReimApplication application) { return fingerprints.fingerprint(application); } + + public List nodesFromToken(ReimRoutePreviewToken token) { + return nodesFromPlan(token.getRoutePlan()); + } + + public List nodesFromPlan(String routePlan) { + try { + List result = objectMapper.readValue(routePlan, + new TypeReference>() { }); + if (result == null || result.isEmpty() || result.size() > MAX_ROUTE_NODES) throw new IllegalArgumentException(); + return result; + } catch (Exception e) { + throw invalid(); + } + } + + /** Rechecks every local preview invariant after the application and token have been reacquired for finalization. */ + public void validateLockedLocalForFinalization(ReimApplication application, ReimRoutePreviewToken token) { + if (feishu.isApprovalEnabledAndConfigured()) + throw new BusinessException("审批路由已切换为飞书,请重新预览后提交", 409); + if (token == null || !"LOCAL".equals(token.getRouteSource()) + || !Objects.equals(token.getApplicationId(), application.getId()) + || !Objects.equals(token.getUserId(), application.getApplicantId()) + || token.getConsumedAt() != null || token.getExpiresAt() == null + || !token.getExpiresAt().isAfter(LocalDateTime.now()) + || !Objects.equals(token.getApplicationFingerprint(), fingerprints.fingerprint(application))) throw invalid(); + Route current = localRoute(); + if (!Objects.equals(token.getRouteFingerprint(), current.fingerprint) + || !Objects.equals(token.getApprovalCode(), current.approvalCode)) throw invalid(); + nodesFromToken(token); + } + + private Route currentRoute(boolean lockSnapshot) { + return feishu.isApprovalEnabledAndConfigured() ? feishuRoute(lockSnapshot) : localRoute(); + } + + private Route feishuRoute(boolean lockSnapshot) { + Optional current = lockSnapshot + ? snapshots.findByIdForRouteValidation(FeishuApprovalDefinitionSnapshot.CURRENT_ID) + : snapshots.findById(FeishuApprovalDefinitionSnapshot.CURRENT_ID); + FeishuApprovalDefinitionSnapshot snapshot = current + .orElseThrow(() -> new BusinessException("飞书审批路线尚未同步,请联系管理员", 409)); + String approvalCode = feishu.getConfiguredApprovalCode(); + if (!Objects.equals(snapshot.getApprovalCode(), approvalCode)) + throw new BusinessException("飞书审批配置已变更,请先同步审批路线", 409); + List persisted = definitionNodes + .findBySnapshotIdOrderByNodeOrderAsc(snapshot.getId()); + if (persisted.isEmpty() || persisted.size() > MAX_ROUTE_NODES) + throw new BusinessException("飞书审批路线不可用,请联系管理员", 409); + List result = new ArrayList<>(); + for (FeishuApprovalDefinitionNode node : persisted) { + List storedApprovers = definitionApprovers + .findByNodeIdOrderByApproverOrderAsc(node.getId()); + if (storedApprovers.size() > MAX_APPROVERS_PER_NODE) + throw new BusinessException("飞书审批路线不可用,请联系管理员", 409); + List labels = new ArrayList<>(); + boolean dynamic = Boolean.TRUE.equals(node.getDynamic()); + for (FeishuApprovalDefinitionApprover approver : storedApprovers) { + String label = bounded(approver.getApproverLabel(), 300); + if (Boolean.TRUE.equals(approver.getDynamic()) && !label.contains("提交时")) + label += "(提交时由飞书解析)"; + labels.add(bounded(label, 300)); + dynamic |= Boolean.TRUE.equals(approver.getDynamic()); + } + if (labels.isEmpty()) { labels.add("提交时由飞书解析"); dynamic = true; } + result.add(RoutePreviewDto.RouteNodeDto.builder().order(node.getNodeOrder()) + .nodeKey(bounded(node.getNodeKey(), 300)).nodeName(bounded(node.getNodeName(), 300)) + .nodeType(bounded(node.getNodeType(), 80)).approvalMode(bounded(node.getApprovalMode(), 80)) + .approverLabels(labels).dynamic(dynamic).build()); + } + boolean stale = snapshot.getFetchedAt() == null || snapshot.getFetchedAt() + .isBefore(LocalDateTime.now().minusSeconds(Math.max(1, snapshotMaxAgeSeconds))); + String warning = stale + ? "当前展示的是较早同步的飞书审批定义;实际审批人和条件由飞书在提交时解析" + : "该路线为估算结果;实际审批人和条件由飞书在提交时解析"; + return new Route("FEISHU", result, + routeFingerprint("FEISHU", true, approvalCode, snapshot.getFingerprint(), result), + snapshot.getFingerprint(), snapshot.getFetchedAt(), stale, false, warning, null, null, + null, null, approvalCode); + } + + private Route localRoute() { + List result = new ArrayList<>(); + List bindings = new ArrayList<>(); + Long firstApproverId = null, firstNodeId = null; String firstNodeName = null, firstRole = null; int order = 1; + List configuredNodes = new ArrayList<>(localNodes.findAllByOrderBySortOrder()); + configuredNodes.sort(Comparator.comparing(SysApprovalNode::getSortOrder, Comparator.nullsLast(Integer::compareTo)) + .thenComparing(SysApprovalNode::getId, Comparator.nullsLast(Long::compareTo))); + for (SysApprovalNode node : configuredNodes) { + if (!ApprovalRoutingRules.isApprovalNode(node)) continue; + if (result.size() >= MAX_ROUTE_NODES) throw new BusinessException("当前审批路线节点过多,无法预览"); + SysUser approver = resolveApprover(node); + if (approver == null) throw new BusinessException("当前审批节点未配置有效审批人,无法预览"); + if (firstApproverId == null) { firstApproverId = approver.getId(); firstNodeId = node.getId(); + firstNodeName = node.getNodeName(); firstRole = node.getApproverRole(); } + bindings.add(localBinding(node, approver)); + result.add(RoutePreviewDto.RouteNodeDto.builder().order(order++) + .nodeKey(node.getNodeCode()).nodeName(node.getNodeName()).nodeType(node.getApproverType()) + .approvalMode("SEQUENTIAL").approverLabels(Collections.singletonList(approver.getRealName())) + .dynamic(false).build()); + } + if (result.isEmpty()) throw new BusinessException("当前审批路线未配置,无法预览"); + String configuredCode = feishu.getConfiguredApprovalCode(); + return new Route("LOCAL", result, + Sha256.hex(routeFingerprint("LOCAL", false, configuredCode, null, result) + + "|" + String.join("|", bindings)), + null, null, false, true, null, firstApproverId, firstNodeName, firstNodeId, firstRole, configuredCode); + } + + private SysUser resolveApprover(SysApprovalNode node) { + if (node.getApproverId() != null) { + SysUser user = users.findById(node.getApproverId()).orElse(null); + return ApprovalRoutingRules.matchesRole(user, node.getApproverRole()) + && roles.hasEditPermission(user.getId(), "finance.approval.decide") ? user : null; + } + List candidates = new ArrayList<>(users.findAll()); + candidates.sort(Comparator.comparing(SysUser::getId, Comparator.nullsLast(Long::compareTo))); + for (SysUser user : candidates) + if (roles.hasEditPermission(user.getId(), "finance.approval.decide") + && ApprovalRoutingRules.matchesRole(user, node.getApproverRole())) return user; + return null; + } + + private String localBinding(SysApprovalNode node, SysUser approver) { + StringBuilder out = new StringBuilder(); + append(out, node.getId()); append(out, node.getNodeCode()); append(out, node.getNodeName()); + append(out, node.getApproverType()); append(out, node.getApproverId()); append(out, node.getApproverRole()); + append(out, node.getSortOrder()); append(out, node.getTimeoutHours()); append(out, node.getStatus()); + append(out, approver.getId()); + return out.toString(); + } + + private String routeFingerprint(String source, boolean enabled, String approvalCode, + String snapshot, List nodes) { + StringBuilder value = new StringBuilder(); append(value, source); append(value, enabled); + append(value, approvalCode); append(value, snapshot); + for (RoutePreviewDto.RouteNodeDto node : nodes) { + append(value, node.getOrder()); append(value, node.getNodeKey()); append(value, node.getNodeName()); + append(value, node.getNodeType()); append(value, node.getApprovalMode()); append(value, node.isDynamic()); + for (String label : node.getApproverLabels()) append(value, label); + } + return Sha256.hex(value.toString()); + } + + private String writePlan(List nodes) { + try { return objectMapper.writeValueAsString(nodes); } + catch (Exception e) { throw new BusinessException("审批路线预览生成失败", 500); } + } + private String randomToken() { byte[] b = new byte[32]; RANDOM.nextBytes(b); return Base64.getUrlEncoder().withoutPadding().encodeToString(b); } + private void append(StringBuilder out, Object value) { String s = value == null ? "" : String.valueOf(value); out.append(s.length()).append(':').append(s).append('|'); } + private String bounded(String value, int max) { return value == null ? null : value.substring(0, Math.min(max, value.length())); } + private BusinessException invalid() { return new BusinessException(INVALID_PREVIEW, 409); } + + private static class Route { + final String source; final List nodes; final String fingerprint; + final String snapshotFingerprint; final LocalDateTime snapshotFetchedAt; final boolean stale; + final boolean exact; final String warning; final Long firstApproverId; final String firstNodeName; + final Long firstNodeId; final String firstApproverRole; + final String approvalCode; + Route(String source, List nodes, String fingerprint, + String snapshotFingerprint, LocalDateTime snapshotFetchedAt, boolean stale, + boolean exact, String warning, Long firstApproverId, String firstNodeName) { + this(source,nodes,fingerprint,snapshotFingerprint,snapshotFetchedAt,stale,exact,warning, + firstApproverId,firstNodeName,null,null,null); + } + Route(String source, List nodes, String fingerprint, + String snapshotFingerprint, LocalDateTime snapshotFetchedAt, boolean stale, + boolean exact, String warning, Long firstApproverId, String firstNodeName, + Long firstNodeId, String firstApproverRole, String approvalCode) { + this.source=source; this.nodes=nodes; this.fingerprint=fingerprint; this.snapshotFingerprint=snapshotFingerprint; + this.snapshotFetchedAt=snapshotFetchedAt; this.stale=stale; this.exact=exact; this.warning=warning; + this.firstApproverId=firstApproverId; this.firstNodeName=firstNodeName; + this.firstNodeId=firstNodeId; this.firstApproverRole=firstApproverRole; + this.approvalCode=approvalCode; + } + } +} diff --git a/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionCoordinator.java b/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionCoordinator.java new file mode 100644 index 0000000..eedd15a --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionCoordinator.java @@ -0,0 +1,39 @@ +package com.finance.system.service.impl; + +import com.finance.system.adapter.feishu.FeishuApprovalService; +import com.finance.system.entity.ReimApplication; +import com.finance.system.exception.FeishuCreateOutcomeUnknownException; +import com.finance.system.exception.BusinessException; +import com.finance.system.util.Sha256; +import com.finance.system.service.impl.ReimbursementSubmissionStateService.PreparedSubmission; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class ReimbursementSubmissionCoordinator { + private final ReimbursementSubmissionStateService state; + private final FeishuApprovalService feishu; + + /** Orchestrates three short transactions around an explicitly non-transactional network call. */ + public ReimApplication submit(Long applicationId, Long userId, String previewToken) { + PreparedSubmission prepared = state.prepare(applicationId, userId, previewToken); + if ("LOCAL".equals(prepared.getSource())) return state.finalizeSubmission(prepared); + if (!prepared.isRemoteAlreadyCreated()) { + String instance; + try { + if (prepared.getCreatePayload() == null || !Sha256.hex(prepared.getCreatePayload()).equals(prepared.getCreatePayloadHash())) + throw new BusinessException("飞书审批创建载荷校验失败", 500); + instance = feishu.createApprovalInstanceRemote(prepared.getCreatePayload(), prepared.getRequestUuid()); + } catch (FeishuCreateOutcomeUnknownException e) { + state.markCreateOutcomeUnknown(prepared); + throw e; + } catch (RuntimeException e) { + state.markCreateFailed(prepared); + throw e; + } + state.recordRemoteCreated(prepared, instance); + } + return state.finalizeSubmission(prepared); + } +} diff --git a/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java b/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java new file mode 100644 index 0000000..af062c5 --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java @@ -0,0 +1,322 @@ +package com.finance.system.service.impl; + +import com.finance.system.adapter.feishu.FeishuApprovalService; +import com.finance.system.dto.RoutePreviewDto; +import com.finance.system.entity.*; +import com.finance.system.enums.*; +import com.finance.system.exception.*; +import com.finance.system.repository.*; +import com.finance.system.service.RoleService; +import com.finance.system.service.ReimbursementFingerprintService; +import com.finance.system.util.Sha256; +import lombok.*; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.*; + +@Service +@RequiredArgsConstructor +public class ReimbursementSubmissionStateService { + private static final long CREATING_RETRY_SECONDS = 120; + private final ReimApplicationRepository applications; + private final ReimExpenseItemRepository items; + private final SysBankAccountRepository banks; + private final IntFeishuApprovalRepository approvals; + private final ReimRoutePreviewTokenRepository tokens; + private final FeishuInstanceTimelineNodeRepository timeline; + private final ReimbursementRoutePreviewService routes; + private final RoleService roles; + private final FeishuApprovalService feishu; + private final ReimbursementFingerprintService fingerprints; + private final SysUserRepository users; + private final SysApprovalNodeRepository localNodes; + private final IntFeishuApprovalAttemptRepository attempts; + + @Transactional + public PreparedSubmission prepare(Long applicationId, Long userId, String rawToken) { + ReimApplication app = applications.findByIdForUpdate(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + requirePermission(userId); + if (!Objects.equals(userId, app.getApplicantId())) + throw new org.springframework.security.access.AccessDeniedException("只能操作本人申请"); + if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) + throw new BusinessException("只能提交草稿或退回状态的申请"); + validatePersisted(app); + LocalDateTime now = LocalDateTime.now(); + IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(applicationId).orElse(null); + boolean resumable = mapping != null && ("CREATED".equals(mapping.getStatus()) + || "CREATE_OUTCOME_UNKNOWN".equals(mapping.getStatus())); + if (mapping != null && "CREATING".equals(mapping.getStatus())) { + boolean stale = mapping.getCreateStartedAt() != null + && !mapping.getCreateStartedAt().isAfter(now.minusSeconds(CREATING_RETRY_SECONDS)); + if (!stale) throw new BusinessException("飞书审批正在创建,请稍后重试", 409); + mapping.setStatus("CREATE_OUTCOME_UNKNOWN"); + resumable = true; + } + ReimRoutePreviewToken token = resumable + ? routes.validateForUnknownResume(app, userId, rawToken) + : routes.validateForSubmit(app, userId, rawToken); + String tokenHash = token.getTokenHash(); + if (resumable) { + if (!Objects.equals(mapping.getSubmissionContentHash(), fingerprints.submissionContentFingerprint(app))) + throw new BusinessException("创建结果未知期间申请内容已变化,禁止重试", 409); + if (!Objects.equals(token.getRouteSource(), mapping.getRouteSource()) + || !Objects.equals(token.getRouteFingerprint(), mapping.getRouteFingerprint()) + || !Objects.equals(token.getSnapshotFingerprint(), mapping.getSnapshotFingerprint()) + || !Objects.equals(token.getApprovalCode(), mapping.getFeishuApprovalCode()) + || !Objects.equals(token.getRoutePlan(), mapping.getRoutePlan())) throw invalid(); + boolean alreadyCreated = "CREATED".equals(mapping.getStatus()); + if (!alreadyCreated) mapping.setStatus("CREATING"); + mapping.setPreviewTokenHash(tokenHash); + mapping.setCreateStartedAt(now); + approvals.save(mapping); + return PreparedSubmission.feishu(applicationId, tokenHash, mapping.getRequestUuid(), + mapping.getFeishuApprovalCode(), mapping.getFeishuInstanceCode(), + alreadyCreated, mapping.getCreatePayload(), mapping.getCreatePayloadHash()); + } + if ("LOCAL".equals(token.getRouteSource())) return PreparedSubmission.local(applicationId, tokenHash); + if (!"FEISHU".equals(token.getRouteSource())) throw invalid(); + + if (mapping == null) { + mapping = new IntFeishuApproval(); + mapping.setApplicationId(applicationId); + mapping.setCreatedAt(now); + mapping.setRequestUuid(stableRequestUuid(app, null)); + } else if (!"CREATE_FAILED".equals(mapping.getStatus()) + && !ApprovalStatus.REJECTED.name().equals(mapping.getStatus()) + && !ApprovalStatus.CANCELLED.name().equals(mapping.getStatus())) { + throw new BusinessException("该申请已有飞书审批记录", 409); + } + + if (StringUtils.hasText(mapping.getFeishuInstanceCode())) { + archiveCurrentAttempt(mapping, now); + mapping.setRequestUuid(stableRequestUuid(app, mapping.getFeishuInstanceCode())); + mapping.setFeishuInstanceCode(null); + } + if ("CREATE_FAILED".equals(mapping.getStatus())) mapping.setRequestUuid(UUID.randomUUID().toString()); + if (!StringUtils.hasText(mapping.getRequestUuid())) mapping.setRequestUuid(stableRequestUuid(app, null)); + mapping.setStatus("CREATING"); + if (!StringUtils.hasText(token.getApprovalCode())) throw invalid(); + mapping.setFeishuApprovalCode(token.getApprovalCode()); + mapping.setRouteSource(token.getRouteSource()); + mapping.setRoutePlan(token.getRoutePlan()); + mapping.setApplicationFingerprint(token.getApplicationFingerprint()); + mapping.setRouteFingerprint(token.getRouteFingerprint()); + mapping.setSnapshotFingerprint(token.getSnapshotFingerprint()); + mapping.setPreviewTokenHash(tokenHash); + mapping.setSubmissionContentHash(fingerprints.submissionContentFingerprint(app)); + String payload = feishu.buildCreatePayload(applicationId, mapping.getRequestUuid(), mapping.getFeishuApprovalCode()); + mapping.setCreatePayload(payload); + mapping.setCreatePayloadHash(Sha256.hex(payload)); + mapping.setDeferredStatus(null); mapping.setDeferredEventAt(null); mapping.setEventUpdatedAt(null); + mapping.setCreateStartedAt(now); + mapping.setSyncedAt(now); + approvals.save(mapping); + return PreparedSubmission.feishu(applicationId, tokenHash, mapping.getRequestUuid(), + mapping.getFeishuApprovalCode(), null, false, payload, mapping.getCreatePayloadHash()); + } + + @Transactional + public void recordRemoteCreated(PreparedSubmission prepared, String instanceCode) { + applications.findByIdForUpdate(prepared.applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(prepared.applicationId) + .orElseThrow(() -> new BusinessException("飞书创建意图不存在,请重试", 409)); + if (!Objects.equals(mapping.getRequestUuid(), prepared.requestUuid)) + throw new BusinessException("飞书创建意图已变更,请重试", 409); + if ("CREATED".equals(mapping.getStatus()) && Objects.equals(mapping.getFeishuInstanceCode(), instanceCode)) return; + if (!"CREATING".equals(mapping.getStatus())) throw new BusinessException("飞书创建状态不可更新", 409); + mapping.setFeishuInstanceCode(limit(instanceCode, 200)); + mapping.setStatus("CREATED"); + mapping.setSyncedAt(LocalDateTime.now()); + approvals.save(mapping); + } + + @Transactional + public ReimApplication finalizeSubmission(PreparedSubmission prepared) { + ReimApplication app = applications.findByIdForUpdate(prepared.applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + IntFeishuApproval mapping = null; + if ("FEISHU".equals(prepared.source)) { + mapping = approvals.findByApplicationIdForUpdate(app.getId()) + .orElseThrow(() -> new BusinessException("飞书创建意图不存在,请重试", 409)); + if (!"CREATED".equals(mapping.getStatus()) || !StringUtils.hasText(mapping.getFeishuInstanceCode()) + || !Objects.equals(mapping.getRequestUuid(), prepared.requestUuid)) + throw new BusinessException("飞书实例尚未完成创建,请重试", 409); + } + ReimRoutePreviewToken token = tokens.findByTokenHashForUpdate(prepared.tokenHash) + .orElseThrow(() -> new BusinessException(ReimbursementRoutePreviewService.INVALID_PREVIEW, 409)); + if (mapping != null) { + if (!Objects.equals(token.getRouteSource(), mapping.getRouteSource()) + || !Objects.equals(token.getRouteFingerprint(), mapping.getRouteFingerprint()) + || !Objects.equals(token.getSnapshotFingerprint(), mapping.getSnapshotFingerprint()) + || !Objects.equals(token.getApprovalCode(), mapping.getFeishuApprovalCode())) throw invalid(); + seedTimeline(mapping); + app.setCurrentApprovalNode("飞书审批"); app.setCurrentApproverId(null); + } else { + if (!"LOCAL".equals(token.getRouteSource()) || token.getFirstApproverId() == null) + throw new BusinessException(ReimbursementRoutePreviewService.INVALID_PREVIEW, 409); + routes.validateLockedLocalForFinalization(app, token); + validateLocalFirstApprover(token); + app.setCurrentApprovalNode(token.getFirstNodeName()); + app.setCurrentApproverId(token.getFirstApproverId()); + } + app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); + app.setApprovalStatus(ApprovalStatus.PENDING.name()); + app.setSubmitTime(LocalDateTime.now()); + app.setBudgetStatus(BudgetStatus.OCCUPIED.name()); + if (mapping != null) { + String deferred = mapping.getDeferredStatus(); + mapping.setStatus(ApprovalStatus.PENDING.name()); + mapping.setSyncedAt(LocalDateTime.now()); + if (StringUtils.hasText(deferred)) applyApprovalStatus(app, deferred); + mapping.setStatus(StringUtils.hasText(deferred) ? deferred : ApprovalStatus.PENDING.name()); + if (mapping.getDeferredEventAt() != null) mapping.setEventUpdatedAt(mapping.getDeferredEventAt()); + mapping.setDeferredStatus(null); mapping.setDeferredEventAt(null); + approvals.save(mapping); + } + applications.save(app); + tokens.deleteByApplicationId(app.getId()); + return app; + } + + @Transactional + public void markCreateFailed(PreparedSubmission prepared) { + applications.findByIdForUpdate(prepared.applicationId).ifPresent(ignored -> {}); + approvals.findByApplicationIdForUpdate(prepared.applicationId).ifPresent(mapping -> { + if ("CREATING".equals(mapping.getStatus()) && Objects.equals(mapping.getRequestUuid(), prepared.requestUuid)) { + mapping.setStatus("CREATE_FAILED"); mapping.setSyncedAt(LocalDateTime.now()); approvals.save(mapping); + } + }); + } + + @Transactional + public void markCreateOutcomeUnknown(PreparedSubmission prepared) { + applications.findByIdForUpdate(prepared.applicationId).ifPresent(ignored -> {}); + approvals.findByApplicationIdForUpdate(prepared.applicationId).ifPresent(mapping -> { + if ("CREATING".equals(mapping.getStatus()) && Objects.equals(mapping.getRequestUuid(), prepared.requestUuid)) { + mapping.setStatus("CREATE_OUTCOME_UNKNOWN"); mapping.setSyncedAt(LocalDateTime.now()); approvals.save(mapping); + } + }); + } + + private void seedTimeline(IntFeishuApproval mapping) { + LocalDateTime now = LocalDateTime.now(); + for (RoutePreviewDto.RouteNodeDto node : routes.nodesFromPlan(mapping.getRoutePlan())) { + String key = "NODE:" + node.getOrder() + ":" + (node.getNodeKey() == null ? "" : node.getNodeKey()); + if (timeline.findByFeishuApprovalIdAndInstanceCodeAndTimelineKey( + mapping.getId(), mapping.getFeishuInstanceCode(), key).isPresent()) continue; + FeishuInstanceTimelineNode actual = node.getNodeKey() == null ? null : timeline + .findFirstByFeishuApprovalIdAndInstanceCodeAndNodeKeyOrderByIdAsc( + mapping.getId(), mapping.getFeishuInstanceCode(), node.getNodeKey()).orElse(null); + if (actual != null && !Boolean.TRUE.equals(actual.getPlanned())) continue; + timeline.save(FeishuInstanceTimelineNode.builder().feishuApprovalId(mapping.getId()) + .instanceCode(mapping.getFeishuInstanceCode()).timelineKey(limit(key, 400)) + .nodeOrder(node.getOrder()).nodeKey(limit(node.getNodeKey(), 300)) + .nodeName(limit(node.getNodeName(), 300)).nodeType(limit(node.getNodeType(), 80)) + .approvalMode(limit(node.getApprovalMode(), 80)).planned(true).status("PLANNED") + .createdAt(now).updatedAt(now).build()); + } + } + + private void archiveCurrentAttempt(IntFeishuApproval mapping, LocalDateTime now) { + String instance = mapping.getFeishuInstanceCode(); + if (!StringUtils.hasText(instance) || attempts.findByInstanceCode(instance).isPresent()) return; + attempts.save(IntFeishuApprovalAttempt.builder().feishuApprovalId(mapping.getId()) + .applicationId(mapping.getApplicationId()).instanceCode(instance).requestUuid(mapping.getRequestUuid()) + .status(mapping.getStatus()).eventUpdatedAt(mapping.getEventUpdatedAt()).createdAt(now).updatedAt(now).build()); + } + + private void validateLocalFirstApprover(ReimRoutePreviewToken token) { + SysApprovalNode node = token.getFirstNodeId() == null ? null : localNodes.findById(token.getFirstNodeId()).orElse(null); + SysUser user = users.findById(token.getFirstApproverId()).orElse(null); + SysUser currentlyResolved = node == null ? null : resolveLocalApprover(node); + if (node == null || !ApprovalRoutingRules.isApprovalNode(node) + || !Objects.equals(node.getApproverRole(), token.getFirstApproverRole()) + || !ApprovalRoutingRules.matchesRole(user, token.getFirstApproverRole()) + || !roles.hasEditPermission(user.getId(), "finance.approval.decide") || currentlyResolved == null + || !Objects.equals(currentlyResolved.getId(), token.getFirstApproverId())) + throw new BusinessException("预览中的首位审批人已失效,请重新预览", 409); + } + + private SysUser resolveLocalApprover(SysApprovalNode node) { + if (node.getApproverId() != null) { + SysUser user = users.findById(node.getApproverId()).orElse(null); + return user != null && ApprovalRoutingRules.matchesRole(user, node.getApproverRole()) + && roles.hasEditPermission(user.getId(), "finance.approval.decide") ? user : null; + } + List candidates = new ArrayList<>(users.findAll()); + candidates.sort(Comparator.comparing(SysUser::getId, Comparator.nullsLast(Long::compareTo))); + for (SysUser candidate : candidates) + if (ApprovalRoutingRules.matchesRole(candidate, node.getApproverRole()) + && roles.hasEditPermission(candidate.getId(), "finance.approval.decide")) return candidate; + return null; + } + + private void applyApprovalStatus(ReimApplication app, String status) { + app.setApprovalStatus(status); app.setCurrentApproverId(null); + if (ApprovalStatus.PENDING.name().equals(status)) { + app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode("飞书审批"); app.setApproveTime(null); + } else if (ApprovalStatus.APPROVED.name().equals(status)) { + app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode(null); app.setApproveTime(LocalDateTime.now()); + } else if (ApprovalStatus.REJECTED.name().equals(status) || ApprovalStatus.CANCELLED.name().equals(status)) { + app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setCurrentApprovalNode(null); app.setApproveTime(null); + } + } + + private void validatePersisted(ReimApplication app) { + List persisted = items.findByApplicationId(app.getId()); + if (app.getTotalAmount() == null || app.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0 || persisted.isEmpty()) + throw new BusinessException("申请金额或费用明细无效"); + BigDecimal sum = BigDecimal.ZERO; + for (ReimExpenseItem item : persisted) { + if (item.getAmount() == null || item.getAmount().compareTo(BigDecimal.ZERO) <= 0) throw new BusinessException("费用明细无效"); + sum = sum.add(item.getAmount()); + } + if (sum.compareTo(app.getTotalAmount()) != 0) throw new BusinessException("费用明细合计必须等于总金额"); + if (app.getPayeeBankId() == null || !banks.findById(app.getPayeeBankId()) + .map(b -> Objects.equals(app.getApplicantId(), b.getUserId())).orElse(false)) + throw new BusinessException("收款银行账户不属于本人"); + } + + private void requirePermission(Long userId) { + if (userId == null) throw new UnauthorizedException("未登录"); + if (!roles.hasEditPermission(userId, "reimbursement.application.submit")) + throw new org.springframework.security.access.AccessDeniedException("权限不足,无法访问"); + } + private String stableRequestUuid(ReimApplication app, String previousInstance) { + String seed = "finance-system:feishu:approval:" + app.getId(); + if (StringUtils.hasText(previousInstance)) seed += ":retry:" + previousInstance; + return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString(); + } + private String limit(String value, int max) { return value == null ? null : value.substring(0, Math.min(max, value.length())); } + private BusinessException invalid() { return new BusinessException(ReimbursementRoutePreviewService.INVALID_PREVIEW, 409); } + + @Getter + public static class PreparedSubmission { + private final Long applicationId; private final String source; private final String tokenHash; + private final String requestUuid; private final String approvalCode; private final String instanceCode; + private final boolean remoteAlreadyCreated; private final String createPayload; private final String createPayloadHash; + public PreparedSubmission(Long applicationId,String source,String tokenHash,String requestUuid,String approvalCode, + String instanceCode,boolean remoteAlreadyCreated,String createPayload) { + this(applicationId,source,tokenHash,requestUuid,approvalCode,instanceCode,remoteAlreadyCreated,createPayload, + createPayload == null ? null : Sha256.hex(createPayload)); + } + public PreparedSubmission(Long applicationId,String source,String tokenHash,String requestUuid,String approvalCode, + String instanceCode,boolean remoteAlreadyCreated,String createPayload,String createPayloadHash) { + this.applicationId=applicationId;this.source=source;this.tokenHash=tokenHash;this.requestUuid=requestUuid; + this.approvalCode=approvalCode;this.instanceCode=instanceCode;this.remoteAlreadyCreated=remoteAlreadyCreated; + this.createPayload=createPayload;this.createPayloadHash=createPayloadHash; + } + static PreparedSubmission local(Long app, String token) { return new PreparedSubmission(app,"LOCAL",token,null,null,null,false,null,null); } + static PreparedSubmission feishu(Long app,String token,String uuid,String code,String instance,boolean created,String payload,String payloadHash) { + return new PreparedSubmission(app,"FEISHU",token,uuid,code,instance,created,payload,payloadHash); + } + } +} diff --git a/src/main/java/com/finance/system/util/AuditUtil.java b/src/main/java/com/finance/system/util/AuditUtil.java index e96be13..61e78f5 100644 --- a/src/main/java/com/finance/system/util/AuditUtil.java +++ b/src/main/java/com/finance/system/util/AuditUtil.java @@ -25,13 +25,10 @@ public class AuditUtil { } public static boolean isFinanceRole() { - UserPrincipal user = getCurrentUser(); - return user != null && "FINANCE".equalsIgnoreCase(user.getUserType()); + return false; } public static boolean isAdminRole() { - UserPrincipal user = getCurrentUser(); - return user != null && ("ADMIN".equalsIgnoreCase(user.getUserType()) - || "SUPER_ADMIN".equalsIgnoreCase(user.getUserType())); + return false; } } diff --git a/src/main/java/com/finance/system/util/Sha256.java b/src/main/java/com/finance/system/util/Sha256.java new file mode 100644 index 0000000..a0e7d4a --- /dev/null +++ b/src/main/java/com/finance/system/util/Sha256.java @@ -0,0 +1,20 @@ +package com.finance.system.util; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; + +public final class Sha256 { + private Sha256() { } + + public static String hex(String value) { + try { + byte[] bytes = MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(64); + for (byte b : bytes) result.append(String.format("%02x", b & 0xff)); + return result.toString(); + } catch (Exception e) { + throw new IllegalStateException("SHA-256 unavailable", e); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 8c0b42d..069eaf2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -4,10 +4,10 @@ spring: application: name: finance-system datasource: - url: "${DB_URL:jdbc:postgresql://localhost:5432/finance_system}" - username: "${DB_USERNAME:postgres}" - password: "${DB_PASSWORD:}" - driver-class-name: org.postgresql.Driver + url: "${DB_URL:jdbc:mysql://localhost:3306/finance_system?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}" + username: "${DB_USERNAME}" + password: "${DB_PASSWORD}" + driver-class-name: com.mysql.cj.jdbc.Driver hikari: maximum-pool-size: 20 minimum-idle: 5 @@ -20,12 +20,11 @@ spring: properties: hibernate: format_sql: true - dialect: org.hibernate.dialect.PostgreSQLDialect + dialect: org.hibernate.dialect.MySQL57Dialect open-in-view: false - flyway: - enabled: true - baseline-on-migrate: true - locations: classpath:db/migration +database: + # Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone. + time-zone: "${DB_TIME_ZONE:Asia/Shanghai}" jwt: secret: "${JWT_SECRET:}" expiration: ${JWT_EXPIRATION:86400000} @@ -40,7 +39,6 @@ feishu: directory: bootstrap-sync-on-startup: ${FEISHU_DIRECTORY_BOOTSTRAP_SYNC_ON_STARTUP:false} credential-revision: "${FEISHU_DIRECTORY_CREDENTIAL_REVISION:1}" - max-status-age-seconds: ${FEISHU_DIRECTORY_MAX_STATUS_AGE_SECONDS:86400} max-elapsed-seconds: ${FEISHU_DIRECTORY_MAX_ELAPSED_SECONDS:120} department-id-type: ${FEISHU_DIRECTORY_DEPARTMENT_ID_TYPE:open_department_id} directory-concurrency: ${FEISHU_DIRECTORY_CONCURRENCY:4} @@ -59,12 +57,14 @@ app: kingdee: enabled: ${KINGDEE_ENABLED:false} base-url: ${KINGDEE_BASE_URL:} + allowed-hosts: ${KINGDEE_ALLOWED_HOSTS:app.kingdee.com} client-id: ${KINGDEE_CLIENT_ID:} client-secret: ${KINGDEE_CLIENT_SECRET:} db-id: ${KINGDEE_DB_ID:} logging: level: com.finance.system: DEBUG + com.finance.system.adapter.feishu.FeishuDirectoryService: DEBUG org.springframework.security: INFO org.hibernate.SQL: WARN springdoc: diff --git a/src/main/resources/db/migration/V10__feishu_directory_normalized.sql b/src/main/resources/db/migration/V10__feishu_directory_normalized.sql deleted file mode 100644 index defc272..0000000 --- a/src/main/resources/db/migration/V10__feishu_directory_normalized.sql +++ /dev/null @@ -1,62 +0,0 @@ -CREATE TABLE IF NOT EXISTS feishu_directory_sync_run ( - run_id VARCHAR(36) PRIMARY KEY, - trigger VARCHAR(20) NOT NULL, - state VARCHAR(20) NOT NULL, - started_at TIMESTAMP NOT NULL, - finished_at TIMESTAMP, - complete BOOLEAN NOT NULL DEFAULT FALSE, - applied BOOLEAN NOT NULL DEFAULT FALSE, - departments INTEGER NOT NULL DEFAULT 0, - users_seen INTEGER NOT NULL DEFAULT 0, - eligible INTEGER NOT NULL DEFAULT 0, - excluded INTEGER NOT NULL DEFAULT 0, - created INTEGER NOT NULL DEFAULT 0, - updated INTEGER NOT NULL DEFAULT 0, - ineligible INTEGER NOT NULL DEFAULT 0, - out_of_scope INTEGER NOT NULL DEFAULT 0, - error_code VARCHAR(100), - error_message VARCHAR(1000), - context VARCHAR(64) -); - -CREATE TABLE IF NOT EXISTS feishu_directory_department ( - open_department_id VARCHAR(64) PRIMARY KEY, - name VARCHAR(200) NOT NULL, - parent_open_department_id VARCHAR(64), - sort_order BIGINT NOT NULL DEFAULT 0, - status VARCHAR(30) NOT NULL, - member_count INTEGER NOT NULL DEFAULT 0, - snapshot_run_id VARCHAR(36) NOT NULL, - context VARCHAR(64), - observed_at TIMESTAMP NOT NULL -); - -CREATE TABLE IF NOT EXISTS feishu_directory_user ( - open_id VARCHAR(100) PRIMARY KEY, - user_id VARCHAR(100) NOT NULL UNIQUE, - name VARCHAR(100) NOT NULL, - employee_no VARCHAR(50), - eligible BOOLEAN NOT NULL DEFAULT FALSE, - snapshot_run_id VARCHAR(36) NOT NULL, - context VARCHAR(64), - observed_at TIMESTAMP NOT NULL -); - -CREATE TABLE IF NOT EXISTS feishu_directory_user_department ( - open_id VARCHAR(100) NOT NULL, - open_department_id VARCHAR(64) NOT NULL, - PRIMARY KEY (open_id, open_department_id), - CONSTRAINT fk_feishu_directory_ud_user FOREIGN KEY (open_id) - REFERENCES feishu_directory_user(open_id) ON DELETE CASCADE, - CONSTRAINT fk_feishu_directory_ud_department FOREIGN KEY (open_department_id) - REFERENCES feishu_directory_department(open_department_id) ON DELETE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_feishu_directory_department_snapshot - ON feishu_directory_department(snapshot_run_id); -CREATE INDEX IF NOT EXISTS idx_feishu_directory_department_parent - ON feishu_directory_department(parent_open_department_id); -CREATE INDEX IF NOT EXISTS idx_feishu_directory_user_snapshot - ON feishu_directory_user(snapshot_run_id); -CREATE INDEX IF NOT EXISTS idx_feishu_directory_ud_department - ON feishu_directory_user_department(open_department_id); diff --git a/src/main/resources/db/migration/V11__feishu_directory_user_details.sql b/src/main/resources/db/migration/V11__feishu_directory_user_details.sql deleted file mode 100644 index c439b37..0000000 --- a/src/main/resources/db/migration/V11__feishu_directory_user_details.sql +++ /dev/null @@ -1,17 +0,0 @@ -ALTER TABLE feishu_directory_user - ADD COLUMN IF NOT EXISTS email VARCHAR(320); - -ALTER TABLE feishu_directory_user - ADD COLUMN IF NOT EXISTS mobile VARCHAR(50); - -ALTER TABLE feishu_directory_user - ADD COLUMN IF NOT EXISTS job_title VARCHAR(200); - -ALTER TABLE feishu_directory_user - ADD COLUMN IF NOT EXISTS employee_type INTEGER; - -ALTER TABLE feishu_directory_user - ADD COLUMN IF NOT EXISTS avatar_url VARCHAR(500); - -ALTER TABLE feishu_directory_user - ADD COLUMN IF NOT EXISTS employment_status VARCHAR(32); diff --git a/src/main/resources/db/migration/V1__init_schema.sql b/src/main/resources/db/migration/V1__init_schema.sql deleted file mode 100644 index f8fd897..0000000 --- a/src/main/resources/db/migration/V1__init_schema.sql +++ /dev/null @@ -1,62 +0,0 @@ --- PostgreSQL baseline for fresh installations. Existing installations are baselined by Flyway. -CREATE TABLE IF NOT EXISTS sys_department ( - id BIGSERIAL PRIMARY KEY, dept_code VARCHAR(50) NOT NULL UNIQUE, dept_name VARCHAR(200) NOT NULL, - parent_id BIGINT, sort_order INTEGER, status VARCHAR(20), created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS sys_user ( - id BIGSERIAL PRIMARY KEY, feishu_open_id VARCHAR(100) UNIQUE, feishu_user_id VARCHAR(100) UNIQUE, - employee_no VARCHAR(50) NOT NULL UNIQUE, real_name VARCHAR(100) NOT NULL, avatar_url VARCHAR(500), - email VARCHAR(200), mobile VARCHAR(20), department_id BIGINT, position VARCHAR(200), user_type VARCHAR(30), - password_hash VARCHAR(100), status VARCHAR(20), last_login_at TIMESTAMP, created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS sys_expense_type ( - id BIGSERIAL PRIMARY KEY, type_code VARCHAR(50) NOT NULL UNIQUE, type_name VARCHAR(200) NOT NULL, - category VARCHAR(50) NOT NULL, parent_id BIGINT, sort_order INTEGER, status VARCHAR(20), - kingdee_form_id VARCHAR(100), created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS sys_bank_account ( - id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, bank_name VARCHAR(200) NOT NULL, branch_name VARCHAR(200), - account_no VARCHAR(100) NOT NULL, account_no_mask VARCHAR(50), account_name VARCHAR(200) NOT NULL, - is_default BOOLEAN, status VARCHAR(20), created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS sys_approval_node ( - id BIGSERIAL PRIMARY KEY, node_code VARCHAR(50) NOT NULL UNIQUE, node_name VARCHAR(200) NOT NULL, - approver_type VARCHAR(50) NOT NULL, approver_id BIGINT, approver_role VARCHAR(50), sort_order INTEGER NOT NULL, - timeout_hours INTEGER, status VARCHAR(20), created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_application ( - id BIGSERIAL PRIMARY KEY, application_no VARCHAR(50) NOT NULL UNIQUE, title VARCHAR(500) NOT NULL, - applicant_id BIGINT NOT NULL, department_id BIGINT NOT NULL, expense_type_id BIGINT NOT NULL, category VARCHAR(100), - total_amount NUMERIC(18,2) NOT NULL, description TEXT, application_status VARCHAR(30) NOT NULL, - approval_status VARCHAR(30), current_approval_node VARCHAR(100), current_approver_id BIGINT, - receipt_status VARCHAR(30), payment_status VARCHAR(30), budget_status VARCHAR(30), source_doc_no VARCHAR(100), - source_doc_type VARCHAR(100), source_system VARCHAR(50), source_doc_date DATE, source_status VARCHAR(30), - payee_name VARCHAR(200), payee_bank_id BIGINT, return_reason TEXT, submit_time TIMESTAMP, approve_time TIMESTAMP, - version INTEGER, deleted BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_expense_item ( - id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL, seq_no INTEGER NOT NULL, expense_date DATE NOT NULL, - category VARCHAR(100) NOT NULL, description VARCHAR(500), amount NUMERIC(18,2) NOT NULL, currency VARCHAR(10), - invoice_count INTEGER, created_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_approval_record ( - id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL, node_name VARCHAR(200) NOT NULL, approver_id BIGINT NOT NULL, - action VARCHAR(30) NOT NULL, comment TEXT, signature VARCHAR(500), action_time TIMESTAMP, created_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_payment ( - id BIGSERIAL PRIMARY KEY, payment_no VARCHAR(50) NOT NULL UNIQUE, application_id BIGINT NOT NULL, payee_id BIGINT NOT NULL, - payee_bank_id BIGINT, total_amount NUMERIC(18,2) NOT NULL, payment_amount NUMERIC(18,2) NOT NULL, - paid_amount NUMERIC(18,2), remaining_amount NUMERIC(18,2), payment_method VARCHAR(50), bank_account_no VARCHAR(100), - bank_account_name VARCHAR(200), reference_no VARCHAR(100), operator_id BIGINT NOT NULL, payment_status VARCHAR(30), - payment_time TIMESTAMP, idempotency_key VARCHAR(100) UNIQUE, remark TEXT, version INTEGER, - deleted BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMP, updated_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_invoice ( - id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL, expense_item_id BIGINT, invoice_no VARCHAR(100) NOT NULL, - invoice_code VARCHAR(100), invoice_type VARCHAR(50), issue_date DATE, amount NUMERIC(18,2), tax_amount NUMERIC(18,2), - seller_name VARCHAR(500), seller_tax_no VARCHAR(100), file_url VARCHAR(500), ocr_result TEXT, verify_status VARCHAR(30), created_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_attachment ( - id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL, file_name VARCHAR(500) NOT NULL, file_type VARCHAR(100), - file_url VARCHAR(500) NOT NULL, file_size BIGINT, content_type VARCHAR(100), uploader_id BIGINT NOT NULL, created_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS reim_payment_installment ( - id BIGSERIAL PRIMARY KEY, payment_id BIGINT NOT NULL, seq_no INTEGER NOT NULL, amount NUMERIC(18,2) NOT NULL, - payment_method VARCHAR(50), reference_no VARCHAR(100), status VARCHAR(30), operated_by BIGINT, operated_at TIMESTAMP, - remark VARCHAR(500), created_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS int_feishu_approval ( - id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL, feishu_instance_code VARCHAR(200), - feishu_approval_code VARCHAR(200), status VARCHAR(30), callback_data TEXT, synced_at TIMESTAMP, created_at TIMESTAMP); -CREATE TABLE IF NOT EXISTS sys_budget ( - id BIGSERIAL PRIMARY KEY, dept_id BIGINT NOT NULL, expense_type_id BIGINT NOT NULL, fiscal_year INTEGER NOT NULL, - fiscal_month INTEGER, total_amount NUMERIC(18,2) NOT NULL, used_amount NUMERIC(18,2) NOT NULL, - frozen_amount NUMERIC(18,2) NOT NULL, status VARCHAR(20), created_at TIMESTAMP, updated_at TIMESTAMP); diff --git a/src/main/resources/db/migration/V2__add_local_password_hash.sql b/src/main/resources/db/migration/V2__add_local_password_hash.sql deleted file mode 100644 index f1548b6..0000000 --- a/src/main/resources/db/migration/V2__add_local_password_hash.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE sys_user ADD COLUMN IF NOT EXISTS password_hash VARCHAR(100); diff --git a/src/main/resources/db/migration/V3__add_oauth_state.sql b/src/main/resources/db/migration/V3__add_oauth_state.sql deleted file mode 100644 index 4c7b3dd..0000000 --- a/src/main/resources/db/migration/V3__add_oauth_state.sql +++ /dev/null @@ -1,3 +0,0 @@ -CREATE TABLE IF NOT EXISTS sys_oauth_state ( - state VARCHAR(128) PRIMARY KEY, expires_at BIGINT NOT NULL); -CREATE INDEX IF NOT EXISTS idx_sys_oauth_state_expires_at ON sys_oauth_state (expires_at); diff --git a/src/main/resources/db/migration/V4__add_webhook_event_inbox.sql b/src/main/resources/db/migration/V4__add_webhook_event_inbox.sql deleted file mode 100644 index 63b7402..0000000 --- a/src/main/resources/db/migration/V4__add_webhook_event_inbox.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE IF NOT EXISTS sys_webhook_event ( - event_id VARCHAR(200) PRIMARY KEY, - status VARCHAR(20) NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP); - -CREATE INDEX IF NOT EXISTS idx_sys_webhook_event_status_created_at - ON sys_webhook_event (status, created_at); diff --git a/src/main/resources/db/migration/V5__add_rbac_and_integration_config.sql b/src/main/resources/db/migration/V5__add_rbac_and_integration_config.sql deleted file mode 100644 index 49925e0..0000000 --- a/src/main/resources/db/migration/V5__add_rbac_and_integration_config.sql +++ /dev/null @@ -1,105 +0,0 @@ --- Database-backed RBAC. The old user_type column remains the compatibility fallback. -CREATE TABLE IF NOT EXISTS sys_role ( - id BIGSERIAL PRIMARY KEY, role_code VARCHAR(80) NOT NULL UNIQUE, role_name VARCHAR(200) NOT NULL, - description VARCHAR(500), status VARCHAR(20) NOT NULL, built_in BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMP, updated_at TIMESTAMP); - -CREATE TABLE IF NOT EXISTS sys_permission ( - id BIGSERIAL PRIMARY KEY, permission_code VARCHAR(120) NOT NULL UNIQUE, permission_name VARCHAR(200) NOT NULL, - permission_type VARCHAR(20) NOT NULL, parent_code VARCHAR(120), resource VARCHAR(200), - default_access VARCHAR(20), created_at TIMESTAMP, updated_at TIMESTAMP); - -CREATE TABLE IF NOT EXISTS sys_role_permission ( - role_id BIGINT NOT NULL REFERENCES sys_role(id), permission_id BIGINT NOT NULL REFERENCES sys_permission(id), access_level VARCHAR(20) NOT NULL, - PRIMARY KEY (role_id, permission_id)); - -CREATE TABLE IF NOT EXISTS sys_user_role ( - user_id BIGINT NOT NULL REFERENCES sys_user(id), role_id BIGINT NOT NULL REFERENCES sys_role(id), PRIMARY KEY (user_id, role_id)); - -CREATE TABLE IF NOT EXISTS sys_user_group ( - id BIGSERIAL PRIMARY KEY, group_code VARCHAR(80) NOT NULL UNIQUE, group_name VARCHAR(200) NOT NULL, - description VARCHAR(500), status VARCHAR(20) NOT NULL, created_at TIMESTAMP, updated_at TIMESTAMP); - -CREATE TABLE IF NOT EXISTS sys_user_group_member ( - group_id BIGINT NOT NULL REFERENCES sys_user_group(id), user_id BIGINT NOT NULL REFERENCES sys_user(id), PRIMARY KEY (group_id, user_id)); - -CREATE TABLE IF NOT EXISTS sys_user_group_role ( - group_id BIGINT NOT NULL REFERENCES sys_user_group(id), role_id BIGINT NOT NULL REFERENCES sys_role(id), PRIMARY KEY (group_id, role_id)); - -CREATE TABLE IF NOT EXISTS sys_integration_config ( - id BIGSERIAL PRIMARY KEY, provider VARCHAR(20) NOT NULL, config_key VARCHAR(80) NOT NULL, - config_value VARCHAR(2000), secret BOOLEAN NOT NULL DEFAULT FALSE, enabled BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMP, updated_at TIMESTAMP, UNIQUE (provider, config_key)); - -INSERT INTO sys_role (role_code, role_name, description, status, built_in, created_at, updated_at) -VALUES ('EMPLOYEE', '普通用户', '普通员工', 'ACTIVE', TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) -ON CONFLICT (role_code) DO NOTHING; -INSERT INTO sys_role (role_code, role_name, description, status, built_in, created_at, updated_at) -VALUES ('FINANCE', '财务', '财务人员', 'ACTIVE', TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) -ON CONFLICT (role_code) DO NOTHING; -INSERT INTO sys_role (role_code, role_name, description, status, built_in, created_at, updated_at) -VALUES ('ADMIN', '系统管理员', '系统管理员', 'ACTIVE', TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) -ON CONFLICT (role_code) DO NOTHING; --- MENU / BUTTON / FIELD catalog. Codes are also the server-side authorization vocabulary. -INSERT INTO sys_permission (permission_code, permission_name, permission_type, parent_code, resource, default_access) -VALUES - ('dashboard', '工作台', 'MENU', NULL, '/dashboard', 'READ'), - ('applications', '报销申请', 'MENU', NULL, '/applications', 'READ'), - ('application:create', '创建报销申请', 'BUTTON', 'applications', 'application', 'EDIT'), - ('application:view-own', '查看本人报销', 'BUTTON', 'applications', 'application', 'READ'), - ('application:amount', '报销金额', 'FIELD', 'applications', 'application.amount', 'EDIT'), - ('application:payeeName', '收款人', 'FIELD', 'applications', 'application.payeeName', 'EDIT'), - ('application:bankAccount', '收款账户', 'FIELD', 'applications', 'application.bankAccount', 'EDIT'), - ('reimbursement:create', '发起报销', 'BUTTON', 'applications', 'reimbursement', 'EDIT'), - ('reimbursement:view-own', '查看本人报销进度', 'BUTTON', 'applications', 'reimbursement', 'READ'), - ('reimbursement:view-all', '查看全部报销', 'BUTTON', 'applications', 'reimbursement', 'READ'), - ('receipt:manage', '收单管理', 'BUTTON', NULL, 'receipt', 'EDIT'), - ('payment:register', '登记付款', 'BUTTON', NULL, 'payment', 'EDIT'), - ('approval:view', '查看审批', 'BUTTON', NULL, 'approval', 'READ'), - ('master-data:manage', '基础数据管理', 'BUTTON', NULL, 'master-data', 'EDIT'), - ('system:user:view', '查看用户', 'BUTTON', NULL, 'system.user', 'READ'), - ('system:user:manage', '管理用户', 'BUTTON', NULL, 'system.user', 'EDIT'), - ('system:role:view', '查看角色', 'BUTTON', NULL, 'system.role', 'READ'), - ('system:role:manage', '管理角色', 'BUTTON', NULL, 'system.role', 'EDIT'), - ('system:group:view', '查看用户组', 'BUTTON', NULL, 'system.group', 'READ'), - ('system:group:manage', '管理用户组', 'BUTTON', NULL, 'system.group', 'EDIT'), - ('system:feishu:bind', '绑定飞书', 'BUTTON', NULL, 'system.feishu', 'EDIT'), - ('system:feishu:sync', '同步飞书', 'BUTTON', NULL, 'system.feishu', 'EDIT'), - ('system:integration:view', '查看集成配置', 'BUTTON', NULL, 'system.integration', 'READ'), - ('system:integration:manage', '管理集成配置', 'BUTTON', NULL, 'system.integration', 'EDIT'), - ('system:integration:test', '测试集成配置', 'BUTTON', NULL, 'system.integration', 'EDIT') -ON CONFLICT (permission_code) DO NOTHING; - --- Existing roles use the same built-in mapping as the historical userType checks. -INSERT INTO sys_role_permission (role_id, permission_id, access_level) -SELECT r.id, p.id, 'READ' FROM sys_role r CROSS JOIN sys_permission p -WHERE r.role_code = 'EMPLOYEE' AND p.permission_code IN - ('dashboard', 'applications', 'application:view-own', 'reimbursement:view-own') -ON CONFLICT (role_id, permission_id) DO NOTHING; -INSERT INTO sys_role_permission (role_id, permission_id, access_level) -SELECT r.id, p.id, 'EDIT' FROM sys_role r CROSS JOIN sys_permission p -WHERE r.role_code = 'EMPLOYEE' AND p.permission_code IN ('application:create', 'reimbursement:create', 'application:amount', 'application:payeeName', 'application:bankAccount') -ON CONFLICT (role_id, permission_id) DO NOTHING; -INSERT INTO sys_role_permission (role_id, permission_id, access_level) -SELECT r.id, p.id, 'READ' FROM sys_role r CROSS JOIN sys_permission p -WHERE r.role_code = 'FINANCE' AND p.permission_code IN - ('dashboard', 'applications', 'application:view-own', 'reimbursement:view-own', 'reimbursement:view-all', 'approval:view') -ON CONFLICT (role_id, permission_id) DO NOTHING; -INSERT INTO sys_role_permission (role_id, permission_id, access_level) -SELECT r.id, p.id, 'EDIT' FROM sys_role r CROSS JOIN sys_permission p -WHERE r.role_code = 'FINANCE' AND p.permission_code IN - ('application:create', 'reimbursement:create', 'receipt:manage', 'payment:register', 'master-data:manage', 'application:amount', 'application:payeeName', 'application:bankAccount') -ON CONFLICT (role_id, permission_id) DO NOTHING; -INSERT INTO sys_role_permission (role_id, permission_id, access_level) -SELECT r.id, p.id, 'EDIT' FROM sys_role r CROSS JOIN sys_permission p -WHERE r.role_code = 'ADMIN' -ON CONFLICT (role_id, permission_id) DO NOTHING; -INSERT INTO sys_user_role (user_id, role_id) -SELECT u.id, r.id FROM sys_user u JOIN sys_role r ON r.role_code = - CASE WHEN UPPER(COALESCE(u.user_type, 'EMPLOYEE')) = 'FINANCE' THEN 'FINANCE' ELSE 'EMPLOYEE' END -WHERE UPPER(COALESCE(u.user_type, 'EMPLOYEE')) NOT IN ('ADMIN', 'SUPER_ADMIN') -ON CONFLICT (user_id, role_id) DO NOTHING; -INSERT INTO sys_user_role (user_id, role_id) -SELECT u.id, r.id FROM sys_user u JOIN sys_role r ON r.role_code = 'ADMIN' -WHERE UPPER(COALESCE(u.user_type, 'EMPLOYEE')) IN ('ADMIN', 'SUPER_ADMIN') -ON CONFLICT (user_id, role_id) DO NOTHING; diff --git a/src/main/resources/db/migration/V6__add_super_admin_role.sql b/src/main/resources/db/migration/V6__add_super_admin_role.sql deleted file mode 100644 index a9b4338..0000000 --- a/src/main/resources/db/migration/V6__add_super_admin_role.sql +++ /dev/null @@ -1,25 +0,0 @@ --- Add the protected super-admin role without changing the checksum of V5. -INSERT INTO sys_role (role_code, role_name, description, status, built_in, created_at, updated_at) -VALUES ('SUPER_ADMIN', '超级管理员', '超级管理员 - 全部系统权限', 'ACTIVE', TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) -ON CONFLICT (role_code) DO NOTHING; - -INSERT INTO sys_role_permission (role_id, permission_id, access_level) -SELECT r.id, p.id, 'EDIT' -FROM sys_role r CROSS JOIN sys_permission p -WHERE r.role_code = 'SUPER_ADMIN' -ON CONFLICT (role_id, permission_id) DO NOTHING; - --- V5 historically mapped SUPER_ADMIN user_type values to ADMIN. Replace that --- compatibility assignment with the protected role after it exists. -DELETE FROM sys_user_role ur -USING sys_user u, sys_role r -WHERE ur.user_id = u.id - AND ur.role_id = r.id - AND r.role_code = 'ADMIN' - AND UPPER(COALESCE(u.user_type, 'EMPLOYEE')) = 'SUPER_ADMIN'; - -INSERT INTO sys_user_role (user_id, role_id) -SELECT u.id, r.id -FROM sys_user u JOIN sys_role r ON r.role_code = 'SUPER_ADMIN' -WHERE UPPER(COALESCE(u.user_type, 'EMPLOYEE')) = 'SUPER_ADMIN' -ON CONFLICT (user_id, role_id) DO NOTHING; diff --git a/src/main/resources/db/migration/V7__unique_feishu_application_mapping.sql b/src/main/resources/db/migration/V7__unique_feishu_application_mapping.sql deleted file mode 100644 index 33758b6..0000000 --- a/src/main/resources/db/migration/V7__unique_feishu_application_mapping.sql +++ /dev/null @@ -1,10 +0,0 @@ --- A reimbursement application has at most one local Feishu synchronization --- record. Keep the newest row if older deployments created duplicates before --- the application-level idempotency key was added. -DELETE FROM int_feishu_approval older -USING int_feishu_approval newer -WHERE older.application_id = newer.application_id - AND older.id < newer.id; - -CREATE UNIQUE INDEX IF NOT EXISTS ux_int_feishu_approval_application_id - ON int_feishu_approval (application_id); diff --git a/src/main/resources/db/migration/V8__feishu_directory.sql b/src/main/resources/db/migration/V8__feishu_directory.sql deleted file mode 100644 index f41eb56..0000000 --- a/src/main/resources/db/migration/V8__feishu_directory.sql +++ /dev/null @@ -1,12 +0,0 @@ -ALTER TABLE sys_user ADD COLUMN directory_status VARCHAR(20) NOT NULL DEFAULT 'UNKNOWN'; -ALTER TABLE sys_user ADD COLUMN directory_context VARCHAR(64); -ALTER TABLE sys_user ADD COLUMN directory_verified_at TIMESTAMP; -ALTER TABLE sys_user ADD COLUMN directory_last_seen_run_id VARCHAR(36); -CREATE INDEX idx_user_directory_context ON sys_user(directory_context); -CREATE TABLE feishu_directory_state ( - id INTEGER PRIMARY KEY CHECK (id = 1), - owner VARCHAR(36), lease_until TIMESTAMP, context VARCHAR(64), - last_run TEXT, last_successful_run_id VARCHAR(36), last_successful_at TIMESTAMP, - successful_context VARCHAR(64) -); -INSERT INTO feishu_directory_state(id) VALUES (1); diff --git a/src/main/resources/db/migration/V9__feishu_directory_snapshot.sql b/src/main/resources/db/migration/V9__feishu_directory_snapshot.sql deleted file mode 100644 index 4bcb3e5..0000000 --- a/src/main/resources/db/migration/V9__feishu_directory_snapshot.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE feishu_directory_state - ADD COLUMN IF NOT EXISTS last_snapshot TEXT; diff --git a/src/main/resources/db/seed/seed_dev_admin.sql b/src/main/resources/db/seed/seed_dev_admin.sql deleted file mode 100644 index ed7755d..0000000 --- a/src/main/resources/db/seed/seed_dev_admin.sql +++ /dev/null @@ -1,68 +0,0 @@ --- ============================================================================ --- 开发测试环境:预配置飞书超级管理员 --- ============================================================================ --- 使用说明: --- 1. 先在飞书开放平台上创建自建应用,获取 App ID 和 App Secret --- 2. 将 FEISHU_APP_ID / FEISHU_APP_SECRET 填入环境变量或 application.yml --- 3. 将下面占位符替换为实际的飞书 open_id/user_id 后再执行此脚本 --- 4. 执行方式:psql -h localhost -U postgres -d finance_system -f seed_dev_admin.sql --- OAuth 登录本身不依赖通讯录同步;通讯录仅用于资料与业务管理。 --- ============================================================================ --- 对于 local 模式(H2 内存库),不需要执行此脚本: --- 系统会在首次飞书登录时创建 ACTIVE 状态的普通 EMPLOYEE 用户;OAuth 登录不依赖通讯录同步。 --- ============================================================================ - --- 替换下面占位符为你的实际飞书信息后再执行 --- 如何获取 open_id?首次登录失败后查看后端日志: --- "飞书获取access_token失败" 上方应有飞书回调的请求日志,或 --- 在飞书开发者后台 → 应用详情 → 查看用户信息 - -BEGIN; -SELECT id FROM feishu_directory_state WHERE id = 1 FOR UPDATE; - -WITH upsert AS ( - UPDATE sys_user - SET - feishu_user_id = COALESCE(NULLIF(BTRIM(feishu_user_id), ''), NULLIF(BTRIM(NULLIF('你的飞书user_id', '你的飞书user_id')), '')), -- 可选,未填写时为 NULL - real_name = '管理员', -- 替换为你的名字 - user_type = 'SUPER_ADMIN', - status = 'ACTIVE', - directory_status = 'UNKNOWN', - directory_context = NULL, - directory_verified_at = NULL, - directory_last_seen_run_id = NULL, - updated_at = CURRENT_TIMESTAMP - WHERE feishu_open_id = '你的飞书open_id' -- 替换为实际值,必填 - RETURNING id -) -INSERT INTO sys_user ( - employee_no, - real_name, - feishu_open_id, - feishu_user_id, - user_type, - status, - directory_status, - directory_context, - directory_verified_at, - directory_last_seen_run_id, - created_at, - updated_at -) -SELECT - 'ADMIN-' || SUBSTR(MD5(RANDOM()::TEXT), 1, 8), - '管理员', -- 替换为你的名字 - '你的飞书open_id', -- 替换为实际值,必填 - NULLIF(BTRIM(NULLIF('你的飞书user_id', '你的飞书user_id')), ''), -- 替换为实际值,可选 - 'SUPER_ADMIN', - 'ACTIVE', - 'UNKNOWN', - NULL, - NULL, - NULL, - CURRENT_TIMESTAMP, - CURRENT_TIMESTAMP -WHERE NOT EXISTS (SELECT 1 FROM upsert) - AND NOT EXISTS (SELECT 1 FROM sys_user WHERE feishu_open_id = '你的飞书open_id'); - -COMMIT; diff --git a/src/test/java/com/finance/system/ReimbursementMvpIntegrationTest.java b/src/test/java/com/finance/system/ReimbursementMvpIntegrationTest.java deleted file mode 100644 index 0d150d8..0000000 --- a/src/test/java/com/finance/system/ReimbursementMvpIntegrationTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.finance.system; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.entity.SysBankAccount; -import com.finance.system.entity.SysExpenseType; -import com.finance.system.repository.SysBankAccountRepository; -import com.finance.system.repository.SysExpenseTypeRepository; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.web.servlet.MockMvc; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@SpringBootTest(properties = "jwt.secret=test-only-jwt-secret-012345678901234567890123456789") -@AutoConfigureMockMvc -@ActiveProfiles("local") -class ReimbursementMvpIntegrationTest { - private static final String LOCAL_PASSWORD = "local-password"; - - @Autowired private MockMvc mvc; - @Autowired private ObjectMapper mapper; - @Autowired private SysExpenseTypeRepository expenseTypes; - @Autowired private SysBankAccountRepository banks; - - private String token(String employeeNo) throws Exception { - String json = mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON) - .content("{\"employeeNo\":\"" + employeeNo + "\",\"password\":\"" - + LOCAL_PASSWORD + "\"}")) - .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - return mapper.readTree(json).path("data").path("token").asText(); - } - - @BeforeEach - void loginWorks() throws Exception { - assertTrue(token("E1001").length() > 20); - } - - @Test - void createRejectsAmountMismatchAndEnforcesOwnership() throws Exception { - String employeeToken = token("E1001"); - String otherToken = token("E1002"); - SysExpenseType type = expenseTypes.findAll().get(0); - SysBankAccount bank = banks.findByUserId(1L).get(0); - String body = application(type.getId(), bank.getId(), "11.00", "10.00"); - mvc.perform(post("/api/v1/reimbursements").header("Authorization", "Bearer " + employeeToken) - .contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isConflict()); - - String valid = application(type.getId(), bank.getId(), "10.00", "10.00"); - String response = mvc.perform(post("/api/v1/reimbursements").header("Authorization", "Bearer " + employeeToken) - .contentType(MediaType.APPLICATION_JSON).content(valid)).andExpect(status().isCreated()) - .andReturn().getResponse().getContentAsString(); - long id = mapper.readTree(response).path("data").path("id").asLong(); - mvc.perform(get("/api/v1/reimbursements/" + id).header("Authorization", "Bearer " + otherToken)) - .andExpect(status().isForbidden()); - } - - @Test - void submitApprovalAndPaymentAreProtectedAndIdempotent() throws Exception { - String employeeToken = token("E1001"); - SysExpenseType type = expenseTypes.findAll().get(0); - SysBankAccount bank = banks.findByUserId(1L).get(0); - String response = mvc.perform(post("/api/v1/reimbursements").header("Authorization", "Bearer " + employeeToken) - .contentType(MediaType.APPLICATION_JSON).content(application(type.getId(), bank.getId(), "10.00", "10.00"))) - .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(); - long id = mapper.readTree(response).path("data").path("id").asLong(); - mvc.perform(post("/api/v1/reimbursements/" + id + "/submit").header("Authorization", "Bearer " + employeeToken)) - .andExpect(status().isOk()); - - String finance = token("F2001"); - mvc.perform(post("/api/v1/accounts-payable/approve").header("Authorization", "Bearer " + finance) - .contentType(MediaType.APPLICATION_JSON).content("{\"applicationId\":" + id + "}")) - .andExpect(status().isOk()); - String manager = token("M3001"); - mvc.perform(post("/api/v1/accounts-payable/approve").header("Authorization", "Bearer " + manager) - .contentType(MediaType.APPLICATION_JSON).content("{\"applicationId\":" + id + "}")) - .andExpect(status().isOk()); - - // Payment is not allowed until finance has explicitly received the application. - String payment = "{\"applicationId\":" + id + ",\"paymentAmount\":10,\"paymentMethod\":\"MANUAL\",\"referenceNo\":\"REF-1\"}"; - mvc.perform(post("/api/v1/cashier/pay").header("Authorization", "Bearer " + finance) - .header("Idempotency-Key", "test-payment-before-receive").contentType(MediaType.APPLICATION_JSON) - .content(payment)).andExpect(status().isConflict()); - - mvc.perform(post("/api/v1/reimbursements/" + id + "/receive") - .header("Authorization", "Bearer " + finance)) - .andExpect(status().isOk()) - .andExpect(result -> assertEquals("RECEIVED", mapper.readTree(result.getResponse().getContentAsString()) - .path("data").path("receiptStatus").asText())); - // Receiving is idempotent and must not alter approval or amount. - mvc.perform(post("/api/v1/reimbursements/" + id + "/receive") - .header("Authorization", "Bearer " + finance)) - .andExpect(status().isOk()); - - String first = mvc.perform(post("/api/v1/cashier/pay").header("Authorization", "Bearer " + finance) - .header("Idempotency-Key", "test-payment-1").contentType(MediaType.APPLICATION_JSON).content(payment)) - .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - String second = mvc.perform(post("/api/v1/cashier/pay").header("Authorization", "Bearer " + finance) - .header("Idempotency-Key", "test-payment-1").contentType(MediaType.APPLICATION_JSON).content(payment)) - .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - assertEquals(mapper.readTree(first).path("data").path("paymentNo").asText(), - mapper.readTree(second).path("data").path("paymentNo").asText()); - mvc.perform(post("/api/v1/cashier/pay").header("Authorization", "Bearer " + finance) - .header("Idempotency-Key", "test-payment-2").contentType(MediaType.APPLICATION_JSON) - .content(payment)).andExpect(status().isConflict()); - } - - @Test - void userAdministrationRequiresAdminAndRejectsUnknownRoles() throws Exception { - String employee = token("E1001"); - String admin = token("A9001"); - - mvc.perform(get("/api/auth/users").header("Authorization", "Bearer " + employee)) - .andExpect(status().isForbidden()); - mvc.perform(put("/api/auth/users/1/role").header("Authorization", "Bearer " + employee) - .contentType(MediaType.APPLICATION_JSON).content("{\"userType\":\"ADMIN\"}")) - .andExpect(status().isForbidden()); - mvc.perform(put("/api/auth/users/1/status").header("Authorization", "Bearer " + employee) - .contentType(MediaType.APPLICATION_JSON).content("{\"status\":\"INACTIVE\"}")) - .andExpect(status().isForbidden()); - mvc.perform(get("/api/auth/users").header("Authorization", "Bearer " + admin)) - .andExpect(status().isOk()); - mvc.perform(put("/api/auth/users/1/role").header("Authorization", "Bearer " + admin) - .contentType(MediaType.APPLICATION_JSON).content("{\"userType\":\"SUPER_ADMIN\"}")) - .andExpect(status().isBadRequest()); - } - - private String application(Long typeId, Long bankId, String total, String itemAmount) { - return "{\"title\":\"本地差旅\",\"expenseTypeId\":" + typeId + ",\"category\":\"差旅\"," - + "\"totalAmount\":" + total + ",\"payeeName\":\"本地员工\",\"payeeBankId\":" + bankId - + ",\"items\":[{\"expenseDate\":\"2026-09-01\",\"category\":\"交通\",\"amount\":" + itemAmount + "}]}"; - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalServiceTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalServiceTest.java deleted file mode 100644 index cbeb5b4..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalServiceTest.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.finance.system.entity.IntFeishuApproval; -import com.finance.system.entity.ReimApplication; -import com.finance.system.entity.SysUser; -import com.finance.system.enums.ApplicationStatus; -import com.finance.system.enums.ApprovalStatus; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.*; -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.nio.charset.StandardCharsets; -import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - -class FeishuApprovalServiceTest { - - @Test - void approvalDelegationRequiresCredentialsAndApprovalDefinition() { - FeishuConfig config = new FeishuConfig(); - FeishuApprovalService service = new FeishuApprovalService(config, mock(FeishuAuthService.class), - mock(SysUserRepository.class), mock(SysDepartmentRepository.class), - mock(SysExpenseTypeRepository.class), mock(ReimExpenseItemRepository.class), - mock(IntFeishuApprovalRepository.class), mock(ReimApplicationRepository.class), - mock(RestTemplate.class)); - - assertFalse(service.isApprovalEnabledAndConfigured()); - config.setAppId("app-id"); - config.setAppSecret("app-secret"); - assertFalse(service.isApprovalEnabledAndConfigured()); - config.getApproval().setApprovalCode("approval-code"); - assertTrue(service.isApprovalEnabledAndConfigured()); - } - - @Test - void createsInstanceAndReturnsExistingMappingOnRetry() { - FeishuConfig config = new FeishuConfig(); - config.setAppId("app-id"); - config.setAppSecret("app-secret"); - config.getApproval().setApprovalCode("approval-code"); - - FeishuAuthService auth = mock(FeishuAuthService.class); - SysUserRepository users = mock(SysUserRepository.class); - SysDepartmentRepository departments = mock(SysDepartmentRepository.class); - SysExpenseTypeRepository expenseTypes = mock(SysExpenseTypeRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - IntFeishuApprovalRepository syncRecords = mock(IntFeishuApprovalRepository.class); - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - RestTemplate rest = mock(RestTemplate.class); - FeishuApprovalService service = new FeishuApprovalService(config, auth, users, departments, - expenseTypes, items, syncRecords, applications, rest); - - ReimApplication application = ReimApplication.builder().id(7L).applicationNo("REIM-7") - .title("travel").totalAmount(new java.math.BigDecimal("10.00")).applicantId(1L).build(); - FeishuApprovalResponse response = new FeishuApprovalResponse(); - FeishuApprovalResponse.Data data = new FeishuApprovalResponse.Data(); - data.setInstanceCode("instance-7"); - response.setData(data); - - when(syncRecords.findByApplicationId(7L)) - .thenReturn(Optional.empty()) - .thenReturn(Optional.of(new IntFeishuApproval(1L, 7L, "instance-7", "approval-code", - "PENDING", null, null, null))); - when(auth.getTenantAccessToken()).thenReturn("tenant-token"); - when(items.findByApplicationId(7L)).thenReturn(Collections.emptyList()); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L) - .realName("Applicant").feishuUserId("ou_applicant").build())); - when(rest.exchange(anyString(), eq(HttpMethod.POST), any(), eq(FeishuApprovalResponse.class))) - .thenReturn(ResponseEntity.ok(response)); - - assertEquals("instance-7", service.createApprovalInstance(application)); - verify(syncRecords).save(any(IntFeishuApproval.class)); - org.mockito.ArgumentCaptor requestCaptor = org.mockito.ArgumentCaptor.forClass(HttpEntity.class); - verify(rest).exchange(anyString(), eq(HttpMethod.POST), requestCaptor.capture(), eq(FeishuApprovalResponse.class)); - Map requestBody = (Map) requestCaptor.getValue().getBody(); - assertEquals(UUID.nameUUIDFromBytes("finance-system:feishu:approval:7" - .getBytes(StandardCharsets.UTF_8)).toString(), requestBody.get("uuid")); - assertNotNull(requestCaptor.getValue().getHeaders().getFirst("X-Request-ID")); - assertEquals("instance-7", service.createApprovalInstance(application)); - verify(rest, times(1)).exchange(anyString(), eq(HttpMethod.POST), any(), eq(FeishuApprovalResponse.class)); - } - - @Test - void missingApplicantFeishuIdentityFailsBeforeTokenOrRemoteRequest() { - FeishuConfig config = new FeishuConfig(); - config.setAppId("app-id"); - config.setAppSecret("app-secret"); - config.getApproval().setApprovalCode("approval-code"); - FeishuAuthService auth = mock(FeishuAuthService.class); - SysUserRepository users = mock(SysUserRepository.class); - RestTemplate rest = mock(RestTemplate.class); - IntFeishuApprovalRepository syncRecords = mock(IntFeishuApprovalRepository.class); - FeishuApprovalService service = new FeishuApprovalService(config, auth, users, - mock(SysDepartmentRepository.class), mock(SysExpenseTypeRepository.class), - mock(ReimExpenseItemRepository.class), syncRecords, mock(ReimApplicationRepository.class), rest); - ReimApplication application = ReimApplication.builder().id(9L).applicantId(1L).build(); - when(syncRecords.findByApplicationId(9L)).thenReturn(Optional.empty()); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L) - .realName("Applicant").build())); - - BusinessException error = assertThrows(BusinessException.class, - () -> service.createApprovalInstance(application)); - - assertEquals(400, error.getStatusCode()); - assertTrue(error.getMessage().contains("未绑定飞书")); - verifyNoInteractions(auth, rest); - } - - @Test - void remoteBusinessErrorIsNotReplacedByGenericMessage() { - FeishuConfig config = new FeishuConfig(); - config.setAppId("app-id"); - config.setAppSecret("app-secret"); - config.getApproval().setApprovalCode("approval-code"); - FeishuAuthService auth = mock(FeishuAuthService.class); - SysUserRepository users = mock(SysUserRepository.class); - IntFeishuApprovalRepository syncRecords = mock(IntFeishuApprovalRepository.class); - RestTemplate rest = mock(RestTemplate.class); - FeishuApprovalService service = new FeishuApprovalService(config, auth, users, - mock(SysDepartmentRepository.class), mock(SysExpenseTypeRepository.class), - mock(ReimExpenseItemRepository.class), syncRecords, mock(ReimApplicationRepository.class), rest); - ReimApplication application = ReimApplication.builder().id(10L).applicantId(1L).build(); - FeishuApprovalResponse response = new FeishuApprovalResponse(); - response.setCode(12345); - response.setMsg("invalid approval definition"); - when(syncRecords.findByApplicationId(10L)).thenReturn(Optional.empty()); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L) - .realName("Applicant").feishuOpenId("ou_applicant").build())); - when(auth.getTenantAccessToken()).thenReturn("token"); - when(rest.exchange(anyString(), eq(HttpMethod.POST), any(), eq(FeishuApprovalResponse.class))) - .thenReturn(ResponseEntity.ok(response)); - - BusinessException error = assertThrows(BusinessException.class, - () -> service.createApprovalInstance(application)); - - assertTrue(error.getMessage().contains("invalid approval definition")); - } - - @Test - void standardV2ApprovalEventUpdatesApplicationAndLateEventCannotReopenIt() { - Fixture fixture = fixture(ApprovalStatus.PENDING.name()); - Map event = new HashMap<>(); - event.put("event_type", "approval_instance"); - event.put("instance_code", "instance-8"); - event.put("status", "APPROVED"); - - fixture.service.handleApprovalEvent(event); - - assertEquals(ApprovalStatus.APPROVED.name(), fixture.record.getStatus()); - assertEquals(ApprovalStatus.APPROVED.name(), fixture.application.getApprovalStatus()); - assertEquals(ApplicationStatus.SUBMITTED.name(), fixture.application.getApplicationStatus()); - assertNotNull(fixture.application.getApproveTime()); - assertNull(fixture.application.getCurrentApproverId()); - - fixture.service.syncApprovalResult("instance-8", "PENDING", null); - verify(fixture.applications, times(1)).save(fixture.application); - assertEquals(ApprovalStatus.APPROVED.name(), fixture.record.getStatus()); - } - - @Test - void unknownStatusIsIgnoredWithoutChangingLocalState() { - Fixture fixture = fixture(ApprovalStatus.PENDING.name()); - - fixture.service.syncApprovalResult("instance-8", "TERMINATED", "ignored"); - - assertEquals(ApprovalStatus.PENDING.name(), fixture.record.getStatus()); - assertEquals(ApprovalStatus.PENDING.name(), fixture.application.getApprovalStatus()); - verify(fixture.syncRecords, never()).save(any(IntFeishuApproval.class)); - verify(fixture.applications, never()).save(any(ReimApplication.class)); - } - - private Fixture fixture(String status) { - FeishuConfig config = new FeishuConfig(); - FeishuAuthService auth = mock(FeishuAuthService.class); - SysUserRepository users = mock(SysUserRepository.class); - SysDepartmentRepository departments = mock(SysDepartmentRepository.class); - SysExpenseTypeRepository expenseTypes = mock(SysExpenseTypeRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - IntFeishuApprovalRepository syncRecords = mock(IntFeishuApprovalRepository.class); - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - RestTemplate rest = mock(RestTemplate.class); - FeishuApprovalService service = new FeishuApprovalService(config, auth, users, departments, - expenseTypes, items, syncRecords, applications, rest); - - IntFeishuApproval record = new IntFeishuApproval(); - record.setApplicationId(8L); - record.setFeishuInstanceCode("instance-8"); - record.setStatus(status); - ReimApplication application = ReimApplication.builder().id(8L) - .applicationStatus(ApplicationStatus.SUBMITTED.name()) - .approvalStatus(ApprovalStatus.PENDING.name()).build(); - when(syncRecords.findByFeishuInstanceCodeForUpdate("instance-8")).thenReturn(Optional.of(record)); - when(applications.findById(8L)).thenReturn(Optional.of(application)); - return new Fixture(service, syncRecords, applications, record, application); - } - - private static class Fixture { - private final FeishuApprovalService service; - private final IntFeishuApprovalRepository syncRecords; - private final ReimApplicationRepository applications; - private final IntFeishuApproval record; - private final ReimApplication application; - - private Fixture(FeishuApprovalService service, IntFeishuApprovalRepository syncRecords, - ReimApplicationRepository applications, IntFeishuApproval record, - ReimApplication application) { - this.service = service; - this.syncRecords = syncRecords; - this.applications = applications; - this.record = record; - this.application = application; - } - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuAuthServiceTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuAuthServiceTest.java deleted file mode 100644 index 0f80f75..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuAuthServiceTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.finance.system.entity.SysUser; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.SysOauthStateRepository; -import com.finance.system.repository.SysUserRepository; -import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; - -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.never; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; - -class FeishuAuthServiceTest { - - @Test - void unknownFeishuUserIsProvisionedAsAnOrdinaryActiveEmployee() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - SysUser provisioned = SysUser.builder().id(7L).feishuOpenId("open-unknown") - .feishuUserId("user-unknown").employeeNo("FS-test") - .realName("Test user").userType("EMPLOYEE").status("ACTIVE") - .directoryStatus("UNKNOWN").build(); - when(users.findByFeishuOpenId("open-unknown")).thenReturn(null, null); - when(users.findByFeishuUserId("user-unknown")).thenReturn(null); - when(users.save(org.mockito.ArgumentMatchers.any(SysUser.class))).thenReturn(provisioned); - FeishuLoginPersistenceService finalizer = mock(FeishuLoginPersistenceService.class); - when(finalizer.completeOAuth(eq(7L), org.mockito.ArgumentMatchers.any(FeishuUserInfo.class))) - .thenReturn(provisioned); - - FeishuAuthService service = service(users, states); - ReflectionTestUtils.setField(service, "loginPersistence", finalizer); - FeishuUserInfo info = userInfo("open-unknown", "user-unknown"); - - assertEquals(provisioned, service.findOrCreateUser(info)); - verifyNoInteractions(states); - verify(users, org.mockito.Mockito.times(2)).findByFeishuOpenId("open-unknown"); - verify(users).findByFeishuUserId("user-unknown"); - verify(users).save(org.mockito.ArgumentMatchers.argThat(user -> - "EMPLOYEE".equals(user.getUserType()) && "ACTIVE".equals(user.getStatus()) - && user.getEmployeeNo().startsWith("FS-") && "UNKNOWN".equals(user.getDirectoryStatus()))); - verify(finalizer).completeOAuth(7L, info); - } - - @Test - void missingOpenIdIsRejectedBeforeAnyLookup() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - FeishuUserInfo info = userInfo(null, "user-1"); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service(users, states).findOrCreateUser(info)); - - assertEquals(403, exception.getStatusCode()); - verifyNoInteractions(users, states); - } - - @Test - void missingOrExpiredStateIsRejected() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - when(states.findByStateAndExpiresAtGreaterThan(eq("expired"), anyLong())) - .thenReturn(Optional.empty()); - when(states.findByStateAndExpiresAtGreaterThan(eq("missing"), anyLong())) - .thenReturn(Optional.empty()); - FeishuAuthService service = service(users, states); - - assertThrows(BusinessException.class, - () -> service.validateCallbackState("expired")); - assertThrows(BusinessException.class, - () -> service.validateCallbackState("missing")); - } - - @Test - void stateCookieMustMatchBeforeConsumption() { - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - FeishuAuthService service = service(mock(SysUserRepository.class), states); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service.validateCallbackState("state-a", "state-b", true)); - - assertEquals(400, exception.getStatusCode()); - verifyNoInteractions(states); - } - - @Test - void successfulStateExchangeCanOnlyConsumeOnce() { - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - when(states.consumeIfValid(eq("state-a"), anyLong())).thenReturn(1, 0); - FeishuAuthService service = service(mock(SysUserRepository.class), states); - - service.validateCallbackState("state-a", "state-a", true); - assertThrows(BusinessException.class, - () -> service.validateCallbackState("state-a", "state-a", true)); - } - - @Test - void malformedAccessTokenResponseIsRejected() { - RestTemplate rest = mock(RestTemplate.class); - when(rest.postForEntity(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), - eq(FeishuTokenResponse.class))).thenReturn( - org.springframework.http.ResponseEntity.ok(new FeishuTokenResponse(0, "ok", null))); - FeishuAuthService service = service(mock(SysUserRepository.class), mock(SysOauthStateRepository.class), rest); - - assertThrows(BusinessException.class, () -> service.getAccessToken("code")); - } - - @Test - void duplicateUserIdOwnershipIsRejectedBeforeUnknownProvisioning() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - SysUser owner = SysUser.builder().id(9L).feishuOpenId("open-owner").feishuUserId("user-local").build(); - when(users.findByFeishuOpenId("open-local")).thenReturn(null); - when(users.findByFeishuUserId("user-local")).thenReturn(owner); - - FeishuAuthService service = service(users, states); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service.findOrCreateUser(userInfo("open-local", "user-local"))); - - assertEquals(403, exception.getStatusCode()); - verifyNoSave(users); - verify(users, never()).flush(); - } - - @Test - void invalidRemoteProfileIsRejectedBeforeUnknownProvisioning() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - when(users.findByFeishuOpenId("open-invalid")).thenReturn(null); - FeishuUserInfo info = userInfo("open-invalid", "user-invalid"); - info.setName(new String(new char[101]).replace('\0', 'x')); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service(users, states).findOrCreateUser(info)); - - assertEquals(403, exception.getStatusCode()); - verify(users, never()).findByFeishuUserId(anyString()); - verifyNoSave(users); - } - - @Test - void unknownOAuthProvisioningDoesNotDependOnLocalBootstrapOrDirectorySync() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - SysUser user = SysUser.builder().id(8L).feishuOpenId("open-local").feishuUserId("user-local") - .status("ACTIVE").userType("EMPLOYEE").directoryStatus("UNKNOWN").build(); - when(users.findByFeishuOpenId("open-local")).thenReturn(null, null); - when(users.findByFeishuUserId("user-local")).thenReturn(null); - when(users.save(org.mockito.ArgumentMatchers.any(SysUser.class))).thenReturn(user); - FeishuLoginPersistenceService finalizer = mock(FeishuLoginPersistenceService.class); - when(finalizer.completeOAuth(eq(8L), org.mockito.ArgumentMatchers.any(FeishuUserInfo.class))).thenReturn(user); - - FeishuAuthService service = service(users, states); - ReflectionTestUtils.setField(service, "loginPersistence", finalizer); - - assertEquals(user, service.findOrCreateUser(userInfo("open-local", "user-local"))); - verify(finalizer).completeOAuth(eq(8L), org.mockito.ArgumentMatchers.any(FeishuUserInfo.class)); - } - - @Test - void existingBoundAccountIsNotRejectedByDirectoryStatus() { - SysUserRepository users = mock(SysUserRepository.class); - SysOauthStateRepository states = mock(SysOauthStateRepository.class); - SysUser user = SysUser.builder().id(8L).feishuOpenId("open-other").feishuUserId("user-other") - .status("ACTIVE").userType("EMPLOYEE").directoryStatus("OUT_OF_SCOPE").build(); - when(users.findByFeishuOpenId("open-other")).thenReturn(user); - FeishuLoginPersistenceService finalizer = mock(FeishuLoginPersistenceService.class); - when(finalizer.completeOAuth(eq(8L), org.mockito.ArgumentMatchers.any(FeishuUserInfo.class))).thenReturn(user); - - FeishuAuthService service = service(users, states); - ReflectionTestUtils.setField(service, "loginPersistence", finalizer); - - assertEquals(user, service.findOrCreateUser(userInfo("open-other", "user-other"))); - verify(finalizer).completeOAuth(eq(8L), org.mockito.ArgumentMatchers.any(FeishuUserInfo.class)); - verifyNoInteractions(states); - } - - private FeishuAuthService service(SysUserRepository users, SysOauthStateRepository states) { - return service(users, states, mock(RestTemplate.class)); - } - - private FeishuAuthService service(SysUserRepository users, SysOauthStateRepository states, RestTemplate restTemplate) { - FeishuConfig config = new FeishuConfig(); - config.setAppId("test-app"); - config.setAppSecret("test-secret"); - config.setRedirectUri("http://localhost/callback"); - return new FeishuAuthService(config, users, states, restTemplate); - } - - private FeishuUserInfo userInfo(String openId, String userId) { - FeishuUserInfo info = new FeishuUserInfo(); - info.setOpenId(openId); - info.setUserId(userId); - info.setName("Test user"); - return info; - } - - private void verifyNoSave(SysUserRepository users) { - org.mockito.Mockito.verify(users, org.mockito.Mockito.never()).save(org.mockito.ArgumentMatchers.any(SysUser.class)); - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryAuthGateTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryAuthGateTest.java deleted file mode 100644 index 8725c65..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryAuthGateTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.finance.system.controller.*; -import com.finance.system.config.JwtConfig; -import com.finance.system.entity.SysUser; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.*; -import com.finance.system.security.*; -import org.junit.jupiter.api.*; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.mock.web.*; -import java.sql.Timestamp; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import java.time.Instant; -import java.util.*; -import static org.mockito.Mockito.*; -import static org.mockito.ArgumentMatchers.*; -import static org.junit.jupiter.api.Assertions.*; - -class FeishuDirectoryAuthGateTest { - @AfterEach void clear() { SecurityContextHolder.clearContext(); } - @Test void allThreeOAuthRoutesUseIdentityOnlyLoginWithoutDirectoryGate() { - SysUserRepository users = mock(SysUserRepository.class); - SysUser user = SysUser.builder().id(1L).feishuOpenId("ou_a").feishuUserId("u_a") - .realName("original").employeeNo("E1").userType("EMPLOYEE") - .status("ACTIVE").directoryStatus("INELIGIBLE").build(); - when(users.findByFeishuOpenId("ou_a")).thenReturn(user); - when(users.findByFeishuUserId("u_a")).thenReturn(user); - FeishuAuthService auth = spy(new FeishuAuthService(new FeishuConfig(), users, mock(SysOauthStateRepository.class), new org.springframework.web.client.RestTemplate())); - FeishuDirectoryAccessService access = mock(FeishuDirectoryAccessService.class); - FeishuLoginPersistenceService finalizer = mock(FeishuLoginPersistenceService.class); - when(finalizer.completeOAuth(eq(1L), any(FeishuUserInfo.class))).thenReturn(user); - ReflectionTestUtils.setField(auth, "loginPersistence", finalizer); - doNothing().when(auth).validateCallbackState("state", "state", true); - FeishuTokenResponse token = mock(FeishuTokenResponse.class, RETURNS_DEEP_STUBS); when(token.getData().getAccessToken()).thenReturn("access"); - doReturn(token).when(auth).getAccessToken("code"); - FeishuUserInfo info = new FeishuUserInfo(); info.setOpenId("ou_a"); info.setUserId("u_a"); info.setName("changed"); - doReturn(info).when(auth).getUserInfo("access"); - JwtConfig jwt = new JwtConfig(); - ReflectionTestUtils.setField(jwt, "secret", "test-only-jwt-secret-012345678901234567890123456789"); - ReflectionTestUtils.setField(jwt, "expiration", 86400000L); - ReflectionTestUtils.setField(jwt, "timeZone", "UTC"); - SysDepartmentRepository departments = mock(SysDepartmentRepository.class); - Map body = new HashMap<>(); body.put("code", "code"); body.put("state", "state"); - FeishuCallbackController callback = new FeishuCallbackController(auth, jwt, users, departments); - assertEquals(200, callback.feishuLogin(body, "state").getStatusCodeValue()); - assertEquals(200, callback.feishuLoginGet("code", "state", "state").getStatusCodeValue()); - AuthController controller = new AuthController(users, departments, jwt, auth, new MockEnvironment(), null); - assertEquals(200, controller.feishuLogin(body, "state").getStatusCodeValue()); - verifyNoInteractions(access); verify(users, never()).save(any()); - assertEquals("u_a", user.getFeishuUserId()); assertEquals("original", user.getRealName()); - } - @Test void conflictingImmutableBindingsRejectedBeforeLiveCheck() { - SysUserRepository users = mock(SysUserRepository.class); - when(users.findByFeishuOpenId("ou_a")).thenReturn(SysUser.builder().id(1L).feishuOpenId("ou_a").feishuUserId("u_a").build()); - when(users.findByFeishuUserId("u_a")).thenReturn(SysUser.builder().id(2L).feishuUserId("u_a").build()); - FeishuAuthService auth = new FeishuAuthService(new FeishuConfig(), users, null, null); - FeishuUserInfo info = new FeishuUserInfo(); info.setOpenId("ou_a"); info.setUserId("u_a"); - assertThrows(BusinessException.class, () -> auth.findOrCreateUser(info)); verify(users, never()).save(any()); - } - @Test void tenantTokenCompatibilityMethodForwards() { - FeishuAuthService auth = new FeishuAuthService(new FeishuConfig(), null, null, null); - FeishuTenantTokenService tokens = mock(FeishuTenantTokenService.class); when(tokens.getTenantAccessToken()).thenReturn("tenant"); - ReflectionTestUtils.setField(auth, "tenantTokens", tokens); assertEquals("tenant", auth.getTenantAccessToken()); - } - @Test void jwtAndRefreshRemainUsableWhenDirectorySnapshotIsStale() throws Exception { - FeishuTenantTokenService tokens = mock(FeishuTenantTokenService.class); - FeishuDirectoryClient client = mock(FeishuDirectoryClient.class); - when(tokens.capture()).thenReturn(new FeishuTenantTokenService.Context("app", "secret", "ctx")); - org.springframework.jdbc.core.JdbcTemplate stateJdbc = mock(org.springframework.jdbc.core.JdbcTemplate.class); - when(stateJdbc.queryForMap("SELECT last_successful_run_id,last_successful_at,successful_context FROM feishu_directory_state WHERE id=1")) - .thenReturn(new HashMap() {{ put("last_successful_run_id", "run"); put("last_successful_at", Timestamp.from(Instant.now().minusSeconds(1))); put("successful_context", "ctx"); }}); - FeishuDirectoryAccessService access = new FeishuDirectoryAccessService(tokens, client, new FeishuDirectorySettings(), new MockEnvironment(), stateJdbc, - mock(org.springframework.transaction.PlatformTransactionManager.class)); - SysUser user = SysUser.builder().id(1L).status("ACTIVE").userType("EMPLOYEE").feishuOpenId("ou_a") - .feishuUserId("u_a") - .directoryStatus("ELIGIBLE").directoryContext("ctx").directoryLastSeenRunId("run").directoryVerifiedAt(Instant.now().minusSeconds(1)).build(); - SysUserRepository users = mock(SysUserRepository.class); when(users.findById(1L)).thenReturn(Optional.of(user)); - JwtConfig jwt = new JwtConfig(); - ReflectionTestUtils.setField(jwt, "secret", "test-only-jwt-secret-012345678901234567890123456789"); - ReflectionTestUtils.setField(jwt, "expiration", 86400000L); - ReflectionTestUtils.setField(jwt, "timeZone", "UTC"); - String token = jwt.generateTokenWithTtl(1L, "E1", "Original", "EMPLOYEE").getToken(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(jwt, users); - MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer " + token); - filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - AuthController controller = new AuthController(users, null, jwt, null, new MockEnvironment(), null); - user.setDirectoryVerifiedAt(Instant.now().minusSeconds(86401)); - assertEquals(200, controller.refreshToken().getStatusCodeValue()); - filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - user.setDirectoryVerifiedAt(Instant.now()); user.setDirectoryContext("old"); - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(UserPrincipal.builder().id(1L).build(), null, Collections.emptyList())); - assertEquals(200, controller.refreshToken().getStatusCodeValue()); - filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - verifyNoInteractions(client); - } - @Test void localOnlyBypassDoesNotApplyToBoundEmployees() { - MockEnvironment env = new MockEnvironment(); env.setActiveProfiles("local"); - FeishuDirectoryAccessService access = new FeishuDirectoryAccessService(mock(FeishuTenantTokenService.class), mock(FeishuDirectoryClient.class), - new FeishuDirectorySettings(), env, null, mock(org.springframework.transaction.PlatformTransactionManager.class)); - SysUser user = SysUser.builder().status("ACTIVE").build(); assertTrue(access.allowed(user)); - user.setFeishuOpenId("ou_a"); assertFalse(access.allowed(user)); - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryClientTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryClientTest.java deleted file mode 100644 index 5f3a379..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryClientTest.java +++ /dev/null @@ -1,421 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.*; -import org.springframework.http.MediaType; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.test.web.client.ResponseCreator; -import org.springframework.web.client.RestTemplate; -import java.util.Collections; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; -import static org.springframework.test.web.client.response.MockRestResponseCreators.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.hamcrest.Matchers.containsString; - -class FeishuDirectoryClientTest { - final FeishuTenantTokenService tokens = mock(FeishuTenantTokenService.class); - final FeishuDirectorySettings settings = new FeishuDirectorySettings(); - final FeishuTenantTokenService.Context context = new FeishuTenantTokenService.Context("app", "secret", "ctx"); - final RestTemplate http = new RestTemplate(); - final MockRestServiceServer server = MockRestServiceServer.bindTo(http).ignoreExpectOrder(true).build(); - final FeishuDirectoryClient client = new FeishuDirectoryClient(tokens, settings, http); - @BeforeEach void setup() { when(tokens.token(context)).thenReturn("tenant"); } - @AfterEach void close() { client.close(); } - private static ResponseCreator rateLimit(org.springframework.http.HttpStatus status, String body, String reset) { - return request -> { - ClientHttpResponse response = withStatus(status).body(body).createResponse(request); - response.getHeaders().add("x-ogw-ratelimit-reset", reset); - return response; - }; - } - @Test void wallClockDeadlineIncludesTokenRequest() { - settings.setMaxElapsedSeconds(1); - when(tokens.token(context)).thenAnswer(invocation -> { Thread.sleep(5000); return "late"; }); - assertTimeout(java.time.Duration.ofSeconds(3), () -> assertThrows(RuntimeException.class, () -> client.fetch(context))); - } - static JsonNode employee(String open, String id) throws Exception { - return new ObjectMapper().readTree("{\"open_id\":\"" + open + "\",\"user_id\":\"" + id + "\",\"name\":\"Employee\",\"employee_no\":\"E-100\",\"email\":\"employee@example.com\",\"mobile\":\"13800000000\",\"job_title\":\"Accountant\",\"employee_type\":1,\"avatar_url\":\"https://example.com/avatar.png\",\"status\":{\"is_activated\":true,\"is_resigned\":false,\"is_frozen\":false,\"is_exited\":false,\"is_unjoin\":false}}"); - } - static String userPage(String open, String id) { - try { - return "{\"code\":0,\"data\":{\"items\":[" + employee(open, id) + "],\"has_more\":false}}"; - } catch (Exception e) { - throw new AssertionError("test user fixture could not be built", e); - } - } - void page(String path, String items, String more) { - server.expect(requestTo(containsString(path))).andExpect(header("Authorization", "Bearer tenant")) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":" + items + ",\"has_more\":" + more + "}}", MediaType.APPLICATION_JSON)); - } - @Test void traversesEveryDepartmentAndPageAndDeduplicates() throws Exception { - String employee = employee("ou_a", "u_a").toString(); - page("departments/0/children", "[{\"open_department_id\":\"d1\",\"name\":\"Finance\",\"order\":7,\"status\":{\"is_deleted\":false}}]", "true,\"page_token\":\"next\""); - page("page_token=next", "[{\"open_department_id\":\"d1\",\"status\":{\"is_deleted\":false}}]", "false"); - page("departments/d1/children", "[]", "false"); - page("department_id=0", "[" + employee + "]", "true,\"page_token\":\"members\""); - page("page_token=members", "[" + employee + "]", "false"); - page("department_id=d1", "[" + employee + "]", "false"); - FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); - assertEquals(2, snapshot.departments.size()); assertEquals(1, snapshot.users.size()); server.verify(); - assertEquals("Finance", snapshot.departmentDetails.get("d1").getName()); - assertEquals("0", snapshot.departmentDetails.get("d1").getParentOpenDepartmentId()); - assertEquals(7L, snapshot.departmentDetails.get("d1").getOrder()); - assertEquals(java.util.Arrays.asList("0", "d1"), snapshot.userSummaries.get("ou_a").getDepartmentIds()); - } - @Test void parsesNumericStringDepartmentOrder() throws Exception { - page("departments/0/children", "[{\"open_department_id\":\"d1\",\"order\":\"17\",\"status\":{\"is_deleted\":false}}]", "false"); - page("departments/d1/children", "[]", "false"); - page("department_id=0", "[]", "false"); - page("department_id=d1", "[]", "false"); - - FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); - assertEquals(17L, snapshot.departmentDetails.get("d1").getOrder()); - server.verify(); - } - @Test void officialQueriesUseOpenDepartmentIdsAndBoundedPageSize() { - server.expect(request -> { - assertTrue(request.getURI().getPath().endsWith("/departments/0/children")); - assertEquals("department_id_type=open_department_id&user_id_type=open_id&page_size=50&fetch_child=false", - request.getURI().getRawQuery()); - }).andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":[],\"has_more\":false}}", MediaType.APPLICATION_JSON)); - server.expect(request -> { - assertTrue(request.getURI().getPath().endsWith("/users/find_by_department")); - assertEquals("department_id_type=open_department_id&user_id_type=open_id&page_size=50&department_id=0", - request.getURI().getRawQuery()); - }).andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":[],\"has_more\":false}}", MediaType.APPLICATION_JSON)); - assertEquals(Collections.singleton("0"), client.fetch(context).departments); - server.verify(); - } - @Test void customDepartmentIdIsNeverTraversedByDefault() { - page("departments/0/children", "[{\"department_id\":\"custom\",\"status\":{\"is_deleted\":false}}]", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_IDENTITY_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void deletedDepartmentIsSkipped() { - page("departments/0/children", "[{\"status\":{\"is_deleted\":true}}]", "false"); - page("department_id=0", "[]", "false"); - FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); - assertEquals(Collections.singleton("0"), snapshot.departments); - server.verify(); - } - @Test void rejectsReturnedPageLargerThanDocumentedPageSize() { - StringBuilder deleted = new StringBuilder("["); - for (int i = 0; i < 51; i++) { - if (i > 0) deleted.append(','); - deleted.append("{\"status\":{\"is_deleted\":true}}"); - } - deleted.append(']'); - page("departments/0/children", deleted.toString(), "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_ITEMS_INVALID_PAGE_TOO_LARGE", ex.getDiagnosticCode()); - server.verify(); - } - @Test void missingDepartmentStatusFailsClosed() { - page("departments/0/children", "[{\"open_department_id\":\"d1\"}]", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_STATUS_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void missingIdentityFailsClosedWithIdentityDiagnostic() { - page("departments/0/children", "[{\"status\":{\"is_deleted\":false}}]", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_IDENTITY_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void invalidPagePayloadFailsClosedWithPageDiagnostic() { - page("departments/0/children", "{}", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_ITEMS_INVALID_TYPE_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void oversizedResponseCodeCannotWrapToSuccess() { - server.expect(requestTo(containsString("departments/0/children"))) - .andRespond(withSuccess("{\"code\":4294967296,\"data\":{\"items\":[],\"has_more\":false}}", - MediaType.APPLICATION_JSON)); - - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_PAGE_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void malformedUserPageIdentifiesUsersByDepartmentEndpoint() { - page("departments/0/children", "[]", "false"); - page("department_id=0", "{\"items\":[]}", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_USER_ITEMS_INVALID_TYPE_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void missingTerminalUserItemsMeansEmptyDepartment() { - page("departments/0/children", "[]", "false"); - server.expect(requestTo(containsString("find_by_department"))) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"has_more\":false}}", MediaType.APPLICATION_JSON)); - FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); - assertEquals(Collections.emptyMap(), snapshot.users); - server.verify(); - } - @Test void missingNonTerminalUserItemsFailsClosed() { - page("departments/0/children", "[]", "false"); - server.expect(requestTo(containsString("find_by_department"))) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"has_more\":true}}", MediaType.APPLICATION_JSON)); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_USER_ITEMS_INVALID_MISSING", ex.getDiagnosticCode()); - server.verify(); - } - @Test void paginationMustBeInsideOfficialBodyDataEnvelope() { - server.expect(requestTo(containsString("departments/0/children"))) - .andRespond(withSuccess("{\"code\":0,\"items\":[],\"has_more\":false}", MediaType.APPLICATION_JSON)); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_PAGE_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void repeatedPageTokenFails() { - page("departments/0/children", "[]", "true,\"page_token\":\"again\""); - page("page_token=again", "[]", "true,\"page_token\":\"again\""); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_PAGE_TOKEN_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void malformedUserPageTokenIdentifiesUsersByDepartmentEndpoint() { - page("departments/0/children", "[]", "false"); - page("department_id=0", "[]", "true"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_USER_PAGE_TOKEN_INVALID", ex.getDiagnosticCode()); - server.verify(); - } - @Test void malformedPageItemIdentifiesDepartmentEndpoint() { - page("departments/0/children", "[null]", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_DEPARTMENT_ITEM_INVALID", ex.getDiagnosticCode()); - assertFalse(ex.getMessage().contains("null")); - server.verify(); - } - @Test void malformedPageItemIdentifiesUsersByDepartmentEndpoint() { - page("departments/0/children", "[]", "false"); - page("department_id=0", "[1]", "false"); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("DIRECTORY_USER_ITEM_INVALID", ex.getDiagnosticCode()); - assertFalse(ex.getMessage().contains("1")); - server.verify(); - } - @Test void opaquePageTokenIsStrictlyEncodedExactlyOnceOnTheWire() { - String opaque = "abc+/==%2B"; - page("departments/0/children", "[]", "true,\"page_token\":\"" + opaque + "\""); - server.expect(request -> { - String rawQuery = request.getURI().getRawQuery(); - assertTrue(rawQuery.contains("page_token=abc%2B%2F%3D%3D%252B"), rawQuery); - String wireToken = rawQuery.substring(rawQuery.indexOf("page_token=") + "page_token=".length()); - assertEquals(opaque, java.net.URLDecoder.decode(wireToken, "UTF-8")); - }).andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":[],\"has_more\":false}}", MediaType.APPLICATION_JSON)); - page("department_id=0", "[]", "false"); - assertEquals(0, client.fetch(context).users.size()); server.verify(); - } - @Test void missingStatusAndNonEmployeesFailClosed() throws Exception { - com.fasterxml.jackson.databind.node.ObjectNode user = (com.fasterxml.jackson.databind.node.ObjectNode) employee("ou_a", "a"); - assertTrue(FeishuDirectoryClient.eligible(user)); - user.put("employee_type", 2); assertFalse(FeishuDirectoryClient.eligible(user)); - user.put("employee_type", 1); ((com.fasterxml.jackson.databind.node.ObjectNode) user.get("status")).remove("is_resigned"); - assertFalse(FeishuDirectoryClient.eligible(user)); - user.remove("status"); assertFalse(FeishuDirectoryClient.eligible(user)); - } - @Test void largeEmployeeTypeDoesNotWrapToEligible() throws Exception { - com.fasterxml.jackson.databind.node.ObjectNode user = - (com.fasterxml.jackson.databind.node.ObjectNode) employee("ou_large_type", "u_large_type"); - // 4294967297 would wrap to 1 when read through JsonNode.asInt(). - user.put("employee_type", new java.math.BigInteger("4294967297")); - assertFalse(FeishuDirectoryClient.eligible(user)); - assertNull(FeishuDirectoryClient.UserSummary.from(user, "0").getEmployeeType()); - } - @Test void userSummaryReadsOnlySafeDetailsAndSupportsPositionAndAvatarObject() throws Exception { - com.fasterxml.jackson.databind.node.ObjectNode user = (com.fasterxml.jackson.databind.node.ObjectNode) employee("ou_details", "u_details"); - user.remove("job_title"); - user.put("position", "Senior Accountant"); - user.remove("avatar_url"); - user.putObject("avatar").put("avatar_origin", "https://example.com/original.png"); - FeishuDirectoryClient.UserSummary summary = FeishuDirectoryClient.UserSummary.from(user, "0"); - - assertEquals("employee@example.com", summary.getEmail()); - assertEquals("13800000000", summary.getMobile()); - assertEquals("Senior Accountant", summary.getJobTitle()); - assertEquals(Integer.valueOf(1), summary.getEmployeeType()); - assertEquals("https://example.com/original.png", summary.getAvatarUrl()); - assertEquals("ACTIVE", summary.getEmploymentStatus()); - } - @Test void pageBoundFailsBeforeAdditionalHttp() { - settings.setMaxPages(1); page("departments/0/children", "[]", "false"); - assertThrows(RuntimeException.class, () -> client.fetch(context)); server.verify(); - } - @Test void partialRemoteErrorFailsTraversal() { - page("departments/0/children", "[]", "false"); - server.expect(requestTo(containsString("find_by_department"))).andRespond(withSuccess("{\"code\":40004,\"msg\":\"sensitive\"}", MediaType.APPLICATION_JSON)); - FeishuDirectoryClient.RemoteFailure ex = assertThrows(FeishuDirectoryClient.RemoteFailure.class, () -> client.fetch(context)); - assertEquals("FEISHU_CODE_40004", ex.getDiagnosticCode()); - assertFalse(ex.getMessage().contains("sensitive")); - } - @Test void remoteHttpStatusSurvivesBoundedWorker() { - page("departments/0/children", "[]", "false"); - server.expect(requestTo(containsString("find_by_department"))).andRespond(withStatus(org.springframework.http.HttpStatus.FORBIDDEN).body("token=secret")); - FeishuDirectoryClient.RemoteFailure ex = assertThrows(FeishuDirectoryClient.RemoteFailure.class, () -> client.fetch(context)); - assertEquals("HTTP_STATUS_403", ex.getDiagnosticCode()); - assertFalse(ex.getMessage().contains("secret")); - } - @Test void tokenFailureSurvivesBoundedWorker() { - when(tokens.token(context)).thenThrow(FeishuTenantTokenService.diagnostic("FEISHU_CODE_999")); - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context)); - assertEquals("FEISHU_CODE_999", ex.getDiagnosticCode()); - } - @Test void departmentChildrenAreConcurrentAndAllIdsAreRetained() { - page("departments/0/children", "[{\"open_department_id\":\"d1\",\"status\":{\"is_deleted\":false}}," - + "{\"open_department_id\":\"d2\",\"status\":{\"is_deleted\":false}}," - + "{\"open_department_id\":\"d3\",\"status\":{\"is_deleted\":false}}]", "false"); - CountDownLatch started = new CountDownLatch(3); - AtomicInteger inFlight = new AtomicInteger(); - AtomicInteger maximum = new AtomicInteger(); - for (String department : new String[]{"d1", "d2", "d3"}) { - server.expect(requestTo(containsString("departments/" + department + "/children"))) - .andRespond(request -> { - int active = inFlight.incrementAndGet(); - maximum.updateAndGet(previous -> Math.max(previous, active)); - started.countDown(); - try { started.await(2, TimeUnit.SECONDS); } - catch (InterruptedException e) { Thread.currentThread().interrupt(); } - finally { inFlight.decrementAndGet(); } - return withSuccess("{\"code\":0,\"data\":{\"items\":[],\"has_more\":false}}", - MediaType.APPLICATION_JSON).createResponse(request); - }); - } - for (String department : new String[]{"0", "d1", "d2", "d3"}) - page("department_id=" + department, "[]", "false"); - - FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); - assertEquals(new java.util.LinkedHashSet<>(java.util.Arrays.asList("0", "d1", "d2", "d3")), - snapshot.departments); - assertTrue(maximum.get() >= 2, "department HTTP requests did not overlap"); - server.verify(); - } - @Test void http429HonorsResetAndRetriesWithinTheBudget() { - settings.setRequestsPerSecond(50); settings.setRequestsPerMinute(1000); settings.setMaxRetries(1); - server.expect(requestTo(containsString("users/ou_rate"))) - .andRespond(rateLimit(org.springframework.http.HttpStatus.TOO_MANY_REQUESTS, "", "0")); - server.expect(requestTo(containsString("users/ou_rate"))) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"user\":{\"open_id\":\"ou_rate\",\"user_id\":\"u_rate\"}}}", MediaType.APPLICATION_JSON)); - assertEquals("ou_rate", client.verify("ou_rate", context).path("open_id").asText()); - server.verify(); - } - @Test void legacyRateCodeRetriesAndExhaustionIsSafe() { - settings.setRequestsPerSecond(50); settings.setRequestsPerMinute(1000); settings.setMaxRetries(2); - for (int i = 0; i < 3; i++) { - server.expect(requestTo(containsString("users/ou_exhausted"))) - .andRespond(rateLimit(org.springframework.http.HttpStatus.BAD_REQUEST, - "{\"code\":99991400,\"msg\":\"do not expose\"}", "0")); - } - FeishuTenantTokenService.DiagnosticFailure ex = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.verify("ou_exhausted", context)); - assertEquals("DIRECTORY_RATE_LIMIT_EXHAUSTED", ex.getDiagnosticCode()); - assertFalse(ex.getMessage().contains("do not expose")); - server.verify(); - } - @Test void departmentWorkerDiagnosticPropagatesSafely() { - page("departments/0/children", "[{\"open_department_id\":\"d1\",\"status\":{\"is_deleted\":false}}," - + "{\"open_department_id\":\"d2\",\"status\":{\"is_deleted\":false}}]", "false"); - server.expect(requestTo(containsString("departments/d1/children"))) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":[{}],\"has_more\":false}}", - MediaType.APPLICATION_JSON)); - server.expect(requestTo(containsString("departments/d2/children"))) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":[],\"has_more\":false}}", - MediaType.APPLICATION_JSON)); - - FeishuTenantTokenService.DiagnosticFailure ex = assertTimeout( - java.time.Duration.ofSeconds(3), () -> assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context))); - assertEquals("DIRECTORY_DEPARTMENT_STATUS_INVALID", ex.getDiagnosticCode()); - } - @Test void userFetchesAreConcurrentAndMergedWithoutLossOrDuplication() throws Exception { - settings.setUserFetchConcurrency(4); - page("departments/0/children", "[{\"open_department_id\":\"d1\",\"status\":{\"is_deleted\":false}}," - + "{\"open_department_id\":\"d2\",\"status\":{\"is_deleted\":false}}," - + "{\"open_department_id\":\"d3\",\"status\":{\"is_deleted\":false}}]", "false"); - page("departments/d1/children", "[]", "false"); - page("departments/d2/children", "[]", "false"); - page("departments/d3/children", "[]", "false"); - - CountDownLatch started = new CountDownLatch(4); - AtomicInteger inFlight = new AtomicInteger(); - AtomicInteger maximum = new AtomicInteger(); - String[] departments = {"0", "d1", "d2", "d3"}; - for (int i = 0; i < departments.length; i++) { - final int user = i; - server.expect(requestTo(containsString("department_id=" + departments[i]))) - .andRespond(request -> { - int active = inFlight.incrementAndGet(); - maximum.updateAndGet(previous -> Math.max(previous, active)); - started.countDown(); - try { started.await(2, TimeUnit.SECONDS); } - catch (InterruptedException e) { Thread.currentThread().interrupt(); } - finally { inFlight.decrementAndGet(); } - return withSuccess(userPage("ou_" + user, "u_" + user), MediaType.APPLICATION_JSON) - .createResponse(request); - }); - } - - FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); - assertEquals(4, snapshot.departments.size()); - assertEquals(4, snapshot.users.size()); - assertEquals(java.util.Arrays.asList("ou_0", "ou_1", "ou_2", "ou_3"), - new java.util.ArrayList<>(snapshot.users.keySet())); - assertTrue(maximum.get() >= 2, "user HTTP requests did not overlap"); - server.verify(); - } - @Test void userWorkerDiagnosticCancelsOutstandingWorkAndPropagatesSafely() throws Exception { - page("departments/0/children", "[{\"open_department_id\":\"d1\",\"status\":{\"is_deleted\":false}}," - + "{\"open_department_id\":\"d2\",\"status\":{\"is_deleted\":false}}]", "false"); - page("departments/d1/children", "[]", "false"); - page("departments/d2/children", "[]", "false"); - page("department_id=0", "[]", "false"); - server.expect(requestTo(containsString("department_id=d1"))) - .andRespond(withSuccess("{\"code\":0,\"data\":{\"items\":[1],\"has_more\":false}}", MediaType.APPLICATION_JSON)); - server.expect(requestTo(containsString("department_id=d2"))) - .andRespond(request -> { - try { Thread.sleep(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - return withSuccess(userPage("ou_d2", "u_d2"), MediaType.APPLICATION_JSON).createResponse(request); - }); - - FeishuTenantTokenService.DiagnosticFailure ex = assertTimeout( - java.time.Duration.ofSeconds(3), () -> assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> client.fetch(context))); - assertEquals("DIRECTORY_USER_ITEM_INVALID", ex.getDiagnosticCode()); - } - @Test void settingsClampUserFetchConcurrency() { - settings.setUserFetchConcurrency(-1); - assertEquals(1, settings.getUserFetchConcurrency()); - settings.setUserFetchConcurrency(99); - assertEquals(8, settings.getUserFetchConcurrency()); - settings.setUserFetchConcurrency(4); - assertEquals(4, settings.userFetchConcurrency()); - } - @Test void documentedMissingUserIsDefinitiveButServerErrorIsNot() { - server.expect(requestTo(containsString("users/ou_missing"))).andRespond(withBadRequest().body("{\"code\":41012}")); - assertNull(client.verify("ou_missing", context)); - server.reset(); server.expect(requestTo(containsString("users/ou_missing"))).andRespond(withServerError()); - assertThrows(RuntimeException.class, () -> client.verify("ou_missing", context)); - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryMigrationTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryMigrationTest.java deleted file mode 100644 index b22612d..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryMigrationTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.finance.system.adapter.feishu; - -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.core.io.ClassPathResource; -import org.springframework.jdbc.core.JdbcTemplate; -import static org.junit.jupiter.api.Assertions.*; - -class FeishuDirectoryMigrationTest { - @Test void v8DefaultsOldAccountsToUnknownAndCreatesSingleton() { - DriverManagerDataSource source = new DriverManagerDataSource("jdbc:h2:mem:directory_migration;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", "sa", ""); - JdbcTemplate jdbc = new JdbcTemplate(source); - jdbc.execute("CREATE TABLE sys_user(id BIGINT PRIMARY KEY,status VARCHAR(20),user_type VARCHAR(30))"); - jdbc.update("INSERT INTO sys_user VALUES (1,'INACTIVE','ADMIN')"); - new ResourceDatabasePopulator(new ClassPathResource("db/migration/V8__feishu_directory.sql")).execute(source); - assertEquals("UNKNOWN", jdbc.queryForObject("SELECT directory_status FROM sys_user WHERE id=1", String.class)); - assertEquals("INACTIVE", jdbc.queryForObject("SELECT status FROM sys_user WHERE id=1", String.class)); - assertEquals("ADMIN", jdbc.queryForObject("SELECT user_type FROM sys_user WHERE id=1", String.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_state WHERE id=1", Integer.class)); - assertThrows(org.springframework.dao.DataIntegrityViolationException.class, () -> jdbc.update("INSERT INTO feishu_directory_state(id) VALUES (2)")); - new ResourceDatabasePopulator(new ClassPathResource("db/migration/V9__feishu_directory_snapshot.sql")).execute(source); - new ResourceDatabasePopulator(new ClassPathResource("db/migration/V9__feishu_directory_snapshot.sql")).execute(source); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='FEISHU_DIRECTORY_STATE' AND COLUMN_NAME='LAST_SNAPSHOT'", Integer.class)); - jdbc.execute("DROP ALL OBJECTS"); - } - - @Test void v10CreatesNormalizedDirectoryTablesIdempotently() { - DriverManagerDataSource source = new DriverManagerDataSource("jdbc:h2:mem:directory_normalized_migration;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", "sa", ""); - JdbcTemplate jdbc = new JdbcTemplate(source); - ResourceDatabasePopulator migration = new ResourceDatabasePopulator( - new ClassPathResource("db/migration/V10__feishu_directory_normalized.sql")); - migration.execute(source); - migration.execute(source); - - assertEquals(4, jdbc.queryForObject("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES " - + "WHERE TABLE_NAME IN ('FEISHU_DIRECTORY_SYNC_RUN','FEISHU_DIRECTORY_DEPARTMENT'," - + "'FEISHU_DIRECTORY_USER','FEISHU_DIRECTORY_USER_DEPARTMENT')", Integer.class)); - assertEquals(37, jdbc.queryForObject("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_NAME IN ('FEISHU_DIRECTORY_SYNC_RUN','FEISHU_DIRECTORY_DEPARTMENT'," - + "'FEISHU_DIRECTORY_USER','FEISHU_DIRECTORY_USER_DEPARTMENT')", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_NAME='FEISHU_DIRECTORY_USER_DEPARTMENT' AND COLUMN_NAME='OPEN_ID'", Integer.class)); - jdbc.execute("DROP ALL OBJECTS"); - } - - @Test void v11AddsSafeUserDetailsIdempotently() { - DriverManagerDataSource source = new DriverManagerDataSource("jdbc:h2:mem:directory_user_details_migration;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", "sa", ""); - JdbcTemplate jdbc = new JdbcTemplate(source); - new ResourceDatabasePopulator(new ClassPathResource("db/migration/V10__feishu_directory_normalized.sql")).execute(source); - ResourceDatabasePopulator migration = new ResourceDatabasePopulator( - new ClassPathResource("db/migration/V11__feishu_directory_user_details.sql")); - migration.execute(source); - migration.execute(source); - - for (String column : new String[]{"EMAIL", "MOBILE", "JOB_TITLE", "EMPLOYEE_TYPE", "AVATAR_URL", "EMPLOYMENT_STATUS"}) { - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_NAME='FEISHU_DIRECTORY_USER' AND COLUMN_NAME=?", Integer.class, column)); - } - assertEquals(320, jdbc.queryForObject("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_NAME='FEISHU_DIRECTORY_USER' AND COLUMN_NAME='EMAIL'", Integer.class)); - assertEquals(500, jdbc.queryForObject("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_NAME='FEISHU_DIRECTORY_USER' AND COLUMN_NAME='AVATAR_URL'", Integer.class)); - jdbc.execute("DROP ALL OBJECTS"); - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryPersistenceTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryPersistenceTest.java deleted file mode 100644 index 9ea750e..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryPersistenceTest.java +++ /dev/null @@ -1,470 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.entity.SysUser; -import com.finance.system.repository.SysUserRepository; -import com.finance.system.exception.BusinessException; -import org.junit.jupiter.api.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.core.io.ClassPathResource; -import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.mockito.ArgumentMatchers.any; - -@DataJpaTest(showSql = false) -@ActiveProfiles("local") -@Transactional(propagation = Propagation.NOT_SUPPORTED) -class FeishuDirectoryPersistenceTest { - @Autowired JdbcTemplate jdbc; - @Autowired PlatformTransactionManager manager; - @Autowired SysUserRepository users; - FeishuTenantTokenService tokens; - FeishuDirectoryClient client; - FeishuDirectorySettings settings; - FeishuDirectoryService directory; - FeishuDirectoryAccessService access; - FeishuTenantTokenService.Context context = new FeishuTenantTokenService.Context("app", "secret", "ctx"); - @BeforeEach void setup() { - new ResourceDatabasePopulator(new ClassPathResource("db/migration/V10__feishu_directory_normalized.sql")) - .execute(jdbc.getDataSource()); - new ResourceDatabasePopulator(new ClassPathResource("db/migration/V11__feishu_directory_user_details.sql")) - .execute(jdbc.getDataSource()); - jdbc.update("DELETE FROM sys_user_role"); jdbc.update("DELETE FROM sys_user_group_member"); - jdbc.update("DELETE FROM sys_role"); jdbc.update("DELETE FROM sys_user_group"); - jdbc.update("DELETE FROM feishu_directory_user_department"); - jdbc.update("DELETE FROM feishu_directory_user"); - jdbc.update("DELETE FROM feishu_directory_department"); - jdbc.update("DELETE FROM feishu_directory_sync_run"); - jdbc.update("DELETE FROM sys_user"); jdbc.update("DELETE FROM feishu_directory_state"); - tokens = mock(FeishuTenantTokenService.class); client = mock(FeishuDirectoryClient.class); settings = new FeishuDirectorySettings(); - when(tokens.capture()).thenReturn(context); when(tokens.syncEnabled()).thenReturn(true); - directory = new FeishuDirectoryService(jdbc, manager, users, tokens, client, settings, new ObjectMapper()); directory.initializeState(); - access = new FeishuDirectoryAccessService(tokens, client, settings, new MockEnvironment(), jdbc, manager); - } - FeishuDirectoryClient.Snapshot snapshot() throws Exception { - FeishuDirectoryClient.Snapshot s = new FeishuDirectoryClient.Snapshot(); s.departments.add("0"); - com.fasterxml.jackson.databind.node.ObjectNode employee = - (com.fasterxml.jackson.databind.node.ObjectNode) FeishuDirectoryClientTest.employee("ou_a", "u_a"); - employee.put("token", "tenant-token"); - employee.putObject("raw_payload").put("unapproved", "not persisted"); - s.users.put("ou_a", employee); return s; - } - SysUser existing(String type, String status) { - return users.saveAndFlush(SysUser.builder().feishuOpenId("ou_a").feishuUserId("u_a").realName("Original") - .employeeNo("E1").userType(type).status(status).build()); - } - @Test void fullSyncPreservesDisabledAccountRoleAndIdAndPartialFailurePreservesSnapshot() throws Exception { - SysUser original = existing("ADMIN", "INACTIVE"); when(client.fetch(context)).thenReturn(snapshot()); - jdbc.update("INSERT INTO sys_role(id,role_code,role_name,built_in) VALUES (999,'EXISTING','Existing',false)"); - jdbc.update("INSERT INTO sys_user_group(id,group_code,group_name) VALUES (999,'EXISTING','Existing')"); - jdbc.update("INSERT INTO sys_user_role(user_id,role_id) VALUES (?,999)", original.getId()); - jdbc.update("INSERT INTO sys_user_group_member(user_id,group_id) VALUES (?,999)", original.getId()); - FeishuDirectoryService.Run first = directory.sync("MANUAL"); assertTrue(first.isApplied()); - String firstSnapshot = jdbc.queryForObject("SELECT last_snapshot FROM feishu_directory_state WHERE id=1", String.class); - assertNotNull(firstSnapshot); - assertTrue(firstSnapshot.contains("\"departments\"")); - assertTrue(firstSnapshot.contains("\"users\"")); - assertTrue(firstSnapshot.contains("\"email\":\"employee@example.com\"")); - assertTrue(firstSnapshot.contains("\"employmentStatus\":\"ACTIVE\"")); - assertFalse(firstSnapshot.contains("employeeNo")); - assertFalse(firstSnapshot.contains("\"eligible\"")); - assertFalse(firstSnapshot.contains("tenant-token")); - assertFalse(firstSnapshot.contains("raw_payload")); - assertFalse(firstSnapshot.contains("secret")); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_department", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_user", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_user_department", Integer.class)); - assertEquals("employee@example.com", jdbc.queryForObject("SELECT email FROM feishu_directory_user WHERE open_id='ou_a'", String.class)); - assertEquals("13800000000", jdbc.queryForObject("SELECT mobile FROM feishu_directory_user WHERE open_id='ou_a'", String.class)); - assertEquals("Accountant", jdbc.queryForObject("SELECT job_title FROM feishu_directory_user WHERE open_id='ou_a'", String.class)); - assertEquals(Integer.valueOf(1), jdbc.queryForObject("SELECT employee_type FROM feishu_directory_user WHERE open_id='ou_a'", Integer.class)); - assertEquals("https://example.com/avatar.png", jdbc.queryForObject("SELECT avatar_url FROM feishu_directory_user WHERE open_id='ou_a'", String.class)); - assertEquals("ACTIVE", jdbc.queryForObject("SELECT employment_status FROM feishu_directory_user WHERE open_id='ou_a'", String.class)); - SysUser saved = users.findById(original.getId()).get(); - assertEquals("INACTIVE", saved.getStatus()); assertEquals("ADMIN", saved.getUserType()); assertEquals("Original", saved.getRealName()); - assertEquals("ELIGIBLE", saved.getDirectoryStatus()); assertFalse(access.allowed(saved)); - when(client.fetch(context)).thenThrow(new RuntimeException("secret upstream error")); - FeishuDirectoryService.Run failed = directory.sync("MANUAL"); assertEquals("FAILED", failed.getState()); assertFalse(failed.isApplied()); - assertEquals(first.getRunId(), directory.status().get("lastSuccessfulRunId")); - assertEquals(firstSnapshot, jdbc.queryForObject("SELECT last_snapshot FROM feishu_directory_state WHERE id=1", String.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_department", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_user", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_user_department", Integer.class)); - assertEquals("SUCCEEDED", jdbc.queryForObject("SELECT state FROM feishu_directory_sync_run WHERE run_id=?", String.class, first.getRunId())); - assertEquals("FAILED", jdbc.queryForObject("SELECT state FROM feishu_directory_sync_run WHERE run_id=?", String.class, failed.getRunId())); - assertEquals(failed.getRunId(), ((FeishuDirectoryService.Run) directory.status().get("lastRun")).getRunId()); - assertEquals("ELIGIBLE", users.findById(original.getId()).get().getDirectoryStatus()); - assertFalse(failed.getErrorMessage().contains("secret")); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM sys_user_role WHERE user_id=?", Integer.class, original.getId())); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM sys_user_group_member WHERE user_id=?", Integer.class, original.getId())); - } - - @Test void organizationReadsOnlyThePublishedSnapshotWithStableFields() throws Exception { - when(client.fetch(context)).thenReturn(snapshot()); - FeishuDirectoryService.Run applied = directory.sync("MANUAL"); - assertTrue(applied.isApplied()); - jdbc.update("UPDATE feishu_directory_department SET name='Normalized Finance' WHERE snapshot_run_id=?", applied.getRunId()); - - Map organization = directory.organization(); - assertEquals("FRESH", organization.get("snapshotState")); - assertNotNull(organization.get("lastSuccessfulAt")); - assertEquals(1, ((List) organization.get("departments")).size()); - assertEquals(1, ((List) organization.get("users")).size()); - Map department = (Map) ((List) organization.get("departments")).get(0); - assertEquals("Normalized Finance", department.get("name")); - Map user = (Map) ((List) organization.get("users")).get(0); - assertEquals("ou_a", user.get("openId")); - assertEquals("u_a", user.get("userId")); - assertFalse(user.containsKey("employeeNo")); - assertEquals("employee@example.com", user.get("email")); - assertEquals("13800000000", user.get("mobile")); - assertEquals("Accountant", user.get("jobTitle")); - assertEquals(1, user.get("employeeType")); - assertEquals("https://example.com/avatar.png", user.get("avatarUrl")); - assertEquals("ACTIVE", user.get("employmentStatus")); - assertFalse(user.containsKey("eligible")); - assertFalse(organization.toString().contains("secret")); - } - - @Test void v9FallbackOrganizationOmitsEmployeeNoButKeepsFeishuIdentities() throws Exception { - when(client.fetch(context)).thenReturn(snapshot()); - FeishuDirectoryService.Run applied = directory.sync("MANUAL"); - assertTrue(applied.isApplied()); - - // The normalized view requires the V11 detail columns. Removing one - // makes organization() use the published V9 JSON snapshot instead. - jdbc.execute("ALTER TABLE feishu_directory_user DROP COLUMN email"); - - Map organization = directory.organization(); - assertEquals("FRESH", organization.get("snapshotState")); - Map user = (Map) ((List) organization.get("users")).get(0); - assertEquals("ou_a", user.get("openId")); - assertEquals("u_a", user.get("userId")); - assertFalse(user.containsKey("employeeNo")); - } - - @Test void organizationWithoutSuccessfulSnapshotReturnsEmptyArrays() { - Map organization = directory.organization(); - assertEquals("NEVER_SYNCED", organization.get("snapshotState")); - assertNull(organization.get("lastSuccessfulAt")); - assertTrue(((List) organization.get("departments")).isEmpty()); - assertTrue(((List) organization.get("users")).isEmpty()); - } - - @Test void organizationSuppressesExpiredSnapshotRows() throws Exception { - when(client.fetch(context)).thenReturn(snapshot()); - FeishuDirectoryService.Run applied = directory.sync("MANUAL"); - assertTrue(applied.isApplied()); - - settings.setMaxStatusAgeSeconds(1); - jdbc.update("UPDATE feishu_directory_state SET last_successful_at=? WHERE id=1", - java.sql.Timestamp.from(Instant.now().minusSeconds(2))); - - clearInvocations(client); - Map organization = directory.organization(); - assertEquals("STALE", organization.get("snapshotState")); - assertNotNull(organization.get("lastSuccessfulAt")); - assertTrue(((List) organization.get("departments")).isEmpty()); - assertTrue(((List) organization.get("users")).isEmpty()); - verifyNoInteractions(client); - } - - @Test void organizationSuppressesPublishedRowsWhenContextChangesOrIsUnavailable() throws Exception { - when(client.fetch(context)).thenReturn(snapshot()); - FeishuDirectoryService.Run applied = directory.sync("MANUAL"); - assertTrue(applied.isApplied()); - - when(tokens.capture()).thenReturn(new FeishuTenantTokenService.Context("other-app", "secret", "other-context")); - Map changed = directory.organization(); - assertEquals("CONTEXT_CHANGED", changed.get("snapshotState")); - assertTrue(((List) changed.get("departments")).isEmpty()); - assertTrue(((List) changed.get("users")).isEmpty()); - assertNotNull(changed.get("lastSuccessfulAt")); - - when(tokens.capture()).thenThrow(FeishuTenantTokenService.diagnostic("CONFIGURATION_UNAVAILABLE")); - Map unavailable = directory.organization(); - assertEquals("UNAVAILABLE", unavailable.get("snapshotState")); - assertTrue(((List) unavailable.get("departments")).isEmpty()); - assertTrue(((List) unavailable.get("users")).isEmpty()); - assertNotNull(unavailable.get("lastSuccessfulAt")); - } - - @Test void publicRunSerializationOmitsEligibilityCounters() throws Exception { - FeishuDirectoryService.Run run = new FeishuDirectoryService.Run(); - run.getCounts().setEligible(3); - run.getCounts().setIneligible(2); - run.getCounts().setExcluded(2); - - String json = new ObjectMapper().writeValueAsString(run); - assertFalse(json.contains("eligible")); - assertFalse(json.contains("ineligible")); - assertTrue(json.contains("excluded")); - } - - @Test void duplicateUserDepartmentRelationsAreWrittenOnce() throws Exception { - FeishuDirectoryClient.Snapshot duplicate = snapshot(); - FeishuDirectoryClient.UserSummary summary = FeishuDirectoryClient.UserSummary.from(duplicate.users.get("ou_a"), "0"); - summary.departmentIds.add("0"); - duplicate.userSummaries.put("ou_a", summary); - when(client.fetch(context)).thenReturn(duplicate); - - assertTrue(directory.sync("MANUAL").isApplied()); - assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_user_department", Integer.class)); - } - - @Test void syncResolvesAccountsOnceAndBatchesNewUserPersistence() throws Exception { - SysUserRepository observed = mock(SysUserRepository.class, org.mockito.AdditionalAnswers.delegatesTo(users)); - FeishuDirectoryService optimized = new FeishuDirectoryService(jdbc, manager, observed, tokens, client, settings, new ObjectMapper()); - FeishuDirectoryClient.Snapshot batch = snapshot(); - batch.users.put("ou_b", FeishuDirectoryClientTest.employee("ou_b", "u_b")); - when(client.fetch(context)).thenReturn(batch); - - assertTrue(optimized.sync("MANUAL").isApplied()); - - verify(observed, times(1)).findAll(); - verify(observed, never()).findByFeishuOpenId(anyString()); - verify(observed, never()).findByFeishuUserId(anyString()); - verify(observed, never()).findByEmployeeNo(anyString()); - verify(observed, never()).saveAndFlush(any(SysUser.class)); - verify(observed, times(1)).saveAll(anyList()); - verify(observed, times(1)).flush(); - assertEquals(2, users.count()); - String firstNo = users.findByFeishuOpenId("ou_a").getEmployeeNo(); - String secondNo = users.findByFeishuOpenId("ou_b").getEmployeeNo(); - assertNotEquals(firstNo, secondNo); - } - - @Test void optimizedPathRejectsDuplicateOpenIdBeforeBatchPersistence() throws Exception { - SysUserRepository observed = mock(SysUserRepository.class, org.mockito.AdditionalAnswers.delegatesTo(users)); - FeishuDirectoryService optimized = new FeishuDirectoryService(jdbc, manager, observed, tokens, client, settings, new ObjectMapper()); - FeishuDirectoryClient.Snapshot duplicate = snapshot(); - com.fasterxml.jackson.databind.node.ObjectNode second = - (com.fasterxml.jackson.databind.node.ObjectNode) FeishuDirectoryClientTest.employee("ou_b", "u_b"); - second.put("open_id", "ou_a"); - duplicate.users.put("ou_b", second); - when(client.fetch(context)).thenReturn(duplicate); - - assertFalse(optimized.sync("MANUAL").isApplied()); - verify(observed, times(1)).findAll(); - verify(observed, never()).saveAll(anyList()); - verify(observed, never()).flush(); - assertEquals(0, users.count()); - } - - @Test void memberCountsIncludeUniqueEmployeesInAllDescendants() throws Exception { - FeishuDirectoryClient.Snapshot hierarchy = new FeishuDirectoryClient.Snapshot(); - hierarchy.departments.addAll(Arrays.asList("0", "parent", "child-a", "child-b")); - hierarchy.departmentDetails.put("0", FeishuDirectoryClient.Department.root()); - hierarchy.departmentDetails.put("parent", department("parent", "0")); - hierarchy.departmentDetails.put("child-a", department("child-a", "parent")); - hierarchy.departmentDetails.put("child-b", department("child-b", "parent")); - - com.fasterxml.jackson.databind.node.ObjectNode first = - (com.fasterxml.jackson.databind.node.ObjectNode) FeishuDirectoryClientTest.employee("ou_a", "u_a"); - com.fasterxml.jackson.databind.node.ObjectNode second = - (com.fasterxml.jackson.databind.node.ObjectNode) FeishuDirectoryClientTest.employee("ou_b", "u_b"); - hierarchy.users.put("ou_a", first); - hierarchy.users.put("ou_b", second); - FeishuDirectoryClient.UserSummary firstSummary = FeishuDirectoryClient.UserSummary.from(first, "child-a"); - firstSummary.departmentIds.clear(); firstSummary.departmentIds.add("child-a"); - FeishuDirectoryClient.UserSummary secondSummary = FeishuDirectoryClient.UserSummary.from(second, "child-a"); - secondSummary.departmentIds.clear(); - secondSummary.departmentIds.addAll(Arrays.asList("child-a", "child-b")); - hierarchy.userSummaries.put("ou_a", firstSummary); - hierarchy.userSummaries.put("ou_b", secondSummary); - when(client.fetch(context)).thenReturn(hierarchy); - - assertTrue(directory.sync("MANUAL").isApplied()); - assertEquals(2, jdbc.queryForObject("SELECT member_count FROM feishu_directory_department WHERE open_department_id='0'", Integer.class)); - assertEquals(2, jdbc.queryForObject("SELECT member_count FROM feishu_directory_department WHERE open_department_id='parent'", Integer.class)); - assertEquals(2, jdbc.queryForObject("SELECT member_count FROM feishu_directory_department WHERE open_department_id='child-a'", Integer.class)); - assertEquals(1, jdbc.queryForObject("SELECT member_count FROM feishu_directory_department WHERE open_department_id='child-b'", Integer.class)); - - Map organization = directory.organization(); - Map> byId = new HashMap<>(); - for (Object value : (List) organization.get("departments")) { - Map department = (Map) value; - byId.put(String.valueOf(department.get("id")), department); - } - assertEquals(2, byId.get("0").get("memberCount")); - assertEquals(2, byId.get("parent").get("memberCount")); - } - - @Test void normalizedAndFallbackOrdersSerializeDistinctLongValuesAsStrings() throws Exception { - FeishuDirectoryClient.Snapshot ordered = new FeishuDirectoryClient.Snapshot(); - ordered.departments.addAll(Arrays.asList("0", "large-order-a", "large-order-b")); - ordered.departmentDetails.put("0", FeishuDirectoryClient.Department.root()); - FeishuDirectoryClient.Department largeA = department("large-order-a", "0"); - largeA.order = 9007199254740993L; - FeishuDirectoryClient.Department largeB = department("large-order-b", "0"); - largeB.order = 9007199254740995L; - ordered.departmentDetails.put("large-order-a", largeA); - ordered.departmentDetails.put("large-order-b", largeB); - when(client.fetch(context)).thenReturn(ordered); - - FeishuDirectoryService.Run run = directory.sync("MANUAL"); - assertTrue(run.isApplied()); - assertEquals(largeA.order, jdbc.queryForObject( - "SELECT sort_order FROM feishu_directory_department WHERE open_department_id='large-order-a'", Long.class)); - assertEquals(largeB.order, jdbc.queryForObject( - "SELECT sort_order FROM feishu_directory_department WHERE open_department_id='large-order-b'", Long.class)); - String publishedSnapshot = jdbc.queryForObject( - "SELECT last_snapshot FROM feishu_directory_state WHERE id=1", String.class); - assertTrue(publishedSnapshot.contains("\"order\":\"9007199254740993\"")); - assertTrue(publishedSnapshot.contains("\"order\":\"9007199254740995\"")); - Map organization = directory.organization(); - Map> normalizedById = new HashMap<>(); - for (Object value : (List) organization.get("departments")) { - Map department = (Map) value; - normalizedById.put(String.valueOf(department.get("id")), department); - } - assertEquals("9007199254740993", normalizedById.get("large-order-a").get("order")); - assertEquals("9007199254740995", normalizedById.get("large-order-b").get("order")); - assertTrue(normalizedById.get("large-order-a").get("order") instanceof String); - - // Force the V9 JSON path: a missing V11 column must not abort the - // publication transaction, and its order must remain a string there too. - jdbc.execute("ALTER TABLE feishu_directory_user DROP COLUMN email"); - assertTrue(directory.sync("MANUAL").isApplied()); - Map fallback = directory.organization(); - Map> fallbackById = new HashMap<>(); - for (Object value : (List) fallback.get("departments")) { - Map department = (Map) value; - fallbackById.put(String.valueOf(department.get("id")), department); - } - assertEquals("9007199254740993", fallbackById.get("large-order-a").get("order")); - assertEquals("9007199254740995", fallbackById.get("large-order-b").get("order")); - assertTrue(fallbackById.get("large-order-a").get("order") instanceof String); - } - - private static FeishuDirectoryClient.Department department(String id, String parent) { - FeishuDirectoryClient.Department department = new FeishuDirectoryClient.Department(); - department.openDepartmentId = id; - department.name = id; - department.parentOpenDepartmentId = parent; - department.status = "ACTIVE"; - return department; - } - - @Test void clientValidationDiagnosticIsPublishedWithoutReplacingPreviousSnapshot() throws Exception { - SysUser original = existing("EMPLOYEE", "ACTIVE"); - when(client.fetch(context)).thenReturn(snapshot()); - FeishuDirectoryService.Run first = directory.sync("MANUAL"); - assertTrue(first.isApplied()); - - when(client.fetch(context)).thenThrow( - FeishuTenantTokenService.diagnostic("DIRECTORY_USER_PAGE_INVALID")); - FeishuDirectoryService.Run failed = directory.sync("MANUAL"); - - assertFalse(failed.isApplied()); - assertEquals("DIRECTORY_USER_PAGE_INVALID", failed.getErrorCode()); - assertTrue(failed.getErrorMessage().contains("DIRECTORY_USER_PAGE_INVALID")); - assertEquals(first.getRunId(), directory.status().get("lastSuccessfulRunId")); - assertEquals("ELIGIBLE", users.findById(original.getId()).get().getDirectoryStatus()); - } - @Test void newEmployeesAreUnprivilegedAndAbsenceOffboardsWithoutDeletion() throws Exception { - when(client.fetch(context)).thenReturn(snapshot()); assertTrue(directory.sync("MANUAL").isApplied()); - SysUser user = users.findByFeishuOpenId("ou_a"); assertEquals("EMPLOYEE", user.getUserType()); assertNull(user.getPasswordHash()); - assertTrue(user.getEmployeeNo().length() <= 50); assertTrue(access.allowed(user)); - when(client.fetch(context)).thenReturn(new FeishuDirectoryClient.Snapshot()); assertTrue(directory.sync("MANUAL").isApplied()); - user = users.findById(user.getId()).get(); assertEquals("ACTIVE", user.getStatus()); assertEquals("OUT_OF_SCOPE", user.getDirectoryStatus()); assertFalse(access.allowed(user)); - } - @Test void blankExistingUserIdsAreFilledFromTheDirectory() throws Exception { - SysUser empty = users.saveAndFlush(SysUser.builder().feishuOpenId("ou_a").feishuUserId("").realName("Empty") - .employeeNo("E2").userType("EMPLOYEE").status("ACTIVE").build()); - SysUser whitespace = users.saveAndFlush(SysUser.builder().feishuOpenId("ou_b").feishuUserId(" ").realName("Whitespace") - .employeeNo("E3").userType("EMPLOYEE").status("ACTIVE").build()); - FeishuDirectoryClient.Snapshot snapshot = snapshot(); - snapshot.users.put("ou_b", FeishuDirectoryClientTest.employee("ou_b", "u_b")); - when(client.fetch(context)).thenReturn(snapshot); - - assertTrue(directory.sync("MANUAL").isApplied()); - assertEquals("u_a", users.findById(empty.getId()).get().getFeishuUserId()); - assertEquals("u_b", users.findById(whitespace.getId()).get().getFeishuUserId()); - } - @Test void conflictingBindingRollsBackEntirePublication() throws Exception { - SysUser original = existing("EMPLOYEE", "ACTIVE"); - users.saveAndFlush(SysUser.builder().feishuOpenId("ou_b").feishuUserId("u_b").realName("B").status("ACTIVE").build()); - FeishuDirectoryClient.Snapshot s = snapshot(); s.users.put("ou_b", FeishuDirectoryClientTest.employee("ou_b", "u_a")); - when(client.fetch(context)).thenReturn(s); assertFalse(directory.sync("MANUAL").isApplied()); - assertEquals("UNKNOWN", users.findById(original.getId()).get().getDirectoryStatus()); assertNull(directory.status().get("lastSuccessfulRunId")); - } - @Test void missingStatusExcludesNewUsersAndDeniesExistingWithoutManualDisable() throws Exception { - SysUser original = existing("EMPLOYEE", "ACTIVE"); - FeishuDirectoryClient.Snapshot snapshot = snapshot(); - ((com.fasterxml.jackson.databind.node.ObjectNode) snapshot.users.get("ou_a")).remove("status"); - com.fasterxml.jackson.databind.node.ObjectNode excluded = (com.fasterxml.jackson.databind.node.ObjectNode) FeishuDirectoryClientTest.employee("ou_b", "u_b"); - excluded.remove("status"); snapshot.users.put("ou_b", excluded); when(client.fetch(context)).thenReturn(snapshot); - FeishuDirectoryService.Run run = directory.sync("MANUAL"); assertTrue(run.isApplied()); assertEquals(2, run.getCounts().getExcluded()); - assertEquals(1, run.getCounts().getIneligible()); assertNull(users.findByFeishuOpenId("ou_b")); - SysUser saved = users.findById(original.getId()).get(); assertEquals("ACTIVE", saved.getStatus()); assertEquals("INELIGIBLE", saved.getDirectoryStatus()); - } - @Test void directoryAuthorizationRequiresSyncedSnapshotWithoutRemoteUserVerification() throws Exception { - SysUser admin = existing("ADMIN", "ACTIVE"); - final SysUser initiallyUnsynced = admin; - assertFalse(access.directoryAllowed(initiallyUnsynced)); - verifyNoInteractions(client); - when(client.fetch(context)).thenReturn(snapshot()); assertTrue(directory.sync("MANUAL").isApplied()); - admin = users.findById(admin.getId()).get(); assertTrue(access.directoryAllowed(admin)); - assertTrue(access.allowed(admin)); verify(client).fetch(context); verifyNoMoreInteractions(client); - } - @Test void unknownDirectoryStatusDoesNotPassDirectoryAuthorizationEvenInLocalProfile() throws Exception { - SysUser user = existing("EMPLOYEE", "ACTIVE"); - FeishuDirectoryAccessService local = new FeishuDirectoryAccessService(tokens, client, settings, new MockEnvironment().withProperty("spring.profiles.active", "local"), jdbc, manager); - assertFalse(local.directoryAllowed(user)); - assertEquals("UNKNOWN", users.findById(user.getId()).get().getDirectoryStatus()); - } - @Test void directoryAuthorizationRequiresBothImmutableIdentifiersFromTheSnapshot() throws Exception { - SysUser user = existing("EMPLOYEE", "ACTIVE"); - when(client.fetch(context)).thenReturn(snapshot()); assertTrue(directory.sync("MANUAL").isApplied()); - SysUser incomplete = users.findById(user.getId()).get(); incomplete.setFeishuUserId(null); - assertFalse(access.directoryAllowed(incomplete)); - verify(client).fetch(context); verifyNoMoreInteractions(client); - } - @Test void directoryAuthorizationRejectsRowsNotBelongingToTheLastSuccessfulSnapshot() throws Exception { - SysUser user = existing("EMPLOYEE", "ACTIVE"); - when(client.fetch(context)).thenReturn(snapshot()); assertTrue(directory.sync("MANUAL").isApplied()); - jdbc.update("UPDATE feishu_directory_state SET last_successful_run_id='different-run' WHERE id=1"); - SysUser staleMembership = users.findById(user.getId()).get(); - assertFalse(access.directoryAllowed(staleMembership)); - } - @Test void staleContextChangedAndSyncDisabledDoNotBypassGate() throws Exception { - when(client.fetch(context)).thenReturn(snapshot()); directory.sync("MANUAL"); SysUser user = users.findByFeishuOpenId("ou_a"); - when(tokens.syncEnabled()).thenReturn(false); assertTrue(access.allowed(user)); - FeishuDirectoryService.Run disabled = directory.sync("MANUAL"); - assertFalse(disabled.isApplied()); assertEquals("SYNC_DISABLED", disabled.getErrorCode()); - user.setDirectoryVerifiedAt(Instant.now().minusSeconds(86401)); assertFalse(access.allowed(user)); - when(tokens.capture()).thenReturn(new FeishuTenantTokenService.Context("other", "secret", "other")); - assertFalse(access.allowed(users.findById(user.getId()).get())); assertEquals("CONTEXT_CHANGED", directory.status().get("snapshotState")); - } - @Test void leaseSerializesAndFencesLateOwner() throws Exception { - when(client.fetch(context)).thenAnswer(invocation -> { - assertThrows(BusinessException.class, () -> directory.sync("MANUAL")); - jdbc.update("UPDATE feishu_directory_state SET owner='replacement' WHERE id=1"); return snapshot(); - }); - assertFalse(directory.sync("MANUAL").isApplied()); assertEquals(0, users.count()); - assertEquals("replacement", jdbc.queryForObject("SELECT owner FROM feishu_directory_state WHERE id=1", String.class)); - } - @Test void contextChangeDuringFetchPreventsPublishing() throws Exception { - when(client.fetch(context)).thenAnswer(invocation -> { - when(tokens.capture()).thenReturn(new FeishuTenantTokenService.Context("new", "secret", "new")); return snapshot(); - }); - assertFalse(directory.sync("MANUAL").isApplied()); assertEquals(0, users.count()); - } - @Test void bootstrapIsOptInAndUsesSameService() { - FeishuDirectoryService mock = mock(FeishuDirectoryService.class); FeishuDirectoryBootstrap bootstrap = new FeishuDirectoryBootstrap(settings, mock); - bootstrap.start(); verifyNoInteractions(mock); - settings.setBootstrapSyncOnStartup(true); bootstrap.start(); verify(mock).sync("STARTUP"); - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryReviewRegressionTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryReviewRegressionTest.java deleted file mode 100644 index 57493c5..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryReviewRegressionTest.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.adapter.kingdee.KingdeeConfig; -import com.finance.system.entity.SysUser; -import com.finance.system.entity.SysIntegrationConfig; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.*; -import com.finance.system.service.*; -import org.junit.jupiter.api.*; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.context.annotation.Import; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionTemplate; -import javax.persistence.EntityManager; -import java.util.*; -import java.util.concurrent.*; -import java.util.function.Consumer; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.mockito.ArgumentMatchers.*; - -/** Real JPA commits on independent threads: no mocked account/config persistence. */ -@DataJpaTest(showSql = false) -@ActiveProfiles("local") -@Import(IntegrationConfigService.class) -@Transactional(propagation = Propagation.NOT_SUPPORTED) -class FeishuDirectoryReviewRegressionTest { - @Autowired JdbcTemplate jdbc; - @Autowired EntityManager em; - @Autowired PlatformTransactionManager manager; - @Autowired SysUserRepository users; - @Autowired SysIntegrationConfigRepository configs; - @Autowired IntegrationConfigService updater; - FeishuDirectorySettings settings; - FeishuTenantTokenService tokens; - FeishuDirectoryClient client; - FeishuDirectoryService directory; - FeishuDirectoryAccessService access; - FeishuLoginPersistenceService finalizer; - ExecutorService executor; - - @BeforeEach void setup() { - jdbc.update("DELETE FROM sys_user"); jdbc.update("DELETE FROM sys_integration_config"); jdbc.update("DELETE FROM feishu_directory_state"); - ReflectionTestUtils.setField(updater, "jdbc", jdbc); - FeishuConfig config = new FeishuConfig(); config.setAppId("original-app"); config.setAppSecret("test-only-credential"); - IntegrationConfigReader reader = new IntegrationConfigReader(configs, config, new KingdeeConfig()); - ReflectionTestUtils.setField(reader, "jdbc", jdbc); - settings = new FeishuDirectorySettings(); tokens = new FeishuTenantTokenService(reader, settings); client = mock(FeishuDirectoryClient.class); - directory = new FeishuDirectoryService(jdbc, manager, users, tokens, client, settings, new ObjectMapper()); directory.initializeState(); - access = new FeishuDirectoryAccessService(tokens, client, settings, new MockEnvironment(), jdbc, manager); - finalizer = new FeishuLoginPersistenceService(jdbc, em, users, access, tokens, manager); - executor = Executors.newFixedThreadPool(2); - } - @AfterEach void cleanup() { executor.shutdownNow(); ReflectionTestUtils.setField(updater, "jdbc", jdbc); } - FeishuDirectoryClient.Snapshot snapshot() throws Exception { - FeishuDirectoryClient.Snapshot result = new FeishuDirectoryClient.Snapshot(); result.departments.add("0"); - result.users.put("ou_a", FeishuDirectoryClientTest.employee("ou_a", "u_a")); return result; - } - SysUser admittedAdmin() throws Exception { - SysUser user = users.saveAndFlush(SysUser.builder().realName("Original").status("ACTIVE").userType("ADMIN") - .feishuOpenId("ou_a").feishuUserId("u_a").employeeNo("E1").build()); - when(client.fetch(any())).thenReturn(snapshot()); assertTrue(directory.sync("MANUAL").isApplied()); - return users.findById(user.getId()).get(); - } - FeishuUserInfo info() { - FeishuUserInfo info = new FeishuUserInfo(); info.setOpenId("ou_a"); info.setUserId("u_a"); info.setName("Verified profile"); return info; - } - FeishuAuthService auth() { - FeishuAuthService auth = new FeishuAuthService(new FeishuConfig(), users, mock(SysOauthStateRepository.class), null); - ReflectionTestUtils.setField(auth, "loginPersistence", finalizer); return auth; - } - void concurrentlyChange(Long id, Consumer change) throws Exception { - executor.submit(() -> new TransactionTemplate(manager).execute(s -> { - SysUser current = users.findById(id).get(); change.accept(current); users.saveAndFlush(current); return null; - })).get(5, TimeUnit.SECONDS); - } - void updateApp(String app) { - Map body = new HashMap<>(); body.put("provider", "FEISHU"); body.put("enabled", true); - body.put("values", Collections.singletonMap("appId", app)); updater.update(body); - } - @Test void roleChangesAreNotMergedBackAndTokenUsesCurrentRole() throws Exception { - SysUser before = admittedAdmin(); - concurrentlyChange(before.getId(), user -> user.setUserType("EMPLOYEE")); - FeishuAuthService auth = spy(auth()); - doNothing().when(auth).validateCallbackState("state", "state", true); - FeishuTokenResponse remote = mock(FeishuTokenResponse.class, RETURNS_DEEP_STUBS); when(remote.getData().getAccessToken()).thenReturn("remote"); - doReturn(remote).when(auth).getAccessToken("code"); doReturn(info()).when(auth).getUserInfo("remote"); - com.finance.system.config.JwtConfig jwt = new com.finance.system.config.JwtConfig(); - ReflectionTestUtils.setField(jwt, "secret", "test-only-jwt-secret-012345678901234567890123456789"); - ReflectionTestUtils.setField(jwt, "expiration", 86400000L); ReflectionTestUtils.setField(jwt, "timeZone", "UTC"); - com.finance.system.controller.FeishuCallbackController controller = new com.finance.system.controller.FeishuCallbackController(auth, jwt, users, mock(SysDepartmentRepository.class)); - com.finance.system.dto.LoginResponse result = controller.feishuLoginGet("code", "state", "state").getBody().getData(); - assertNotNull(result); assertEquals("EMPLOYEE", jwt.parseToken(result.getToken()).get("userType")); - SysUser saved = users.findById(before.getId()).get(); assertEquals("EMPLOYEE", saved.getUserType()); - assertEquals("ACTIVE", saved.getStatus()); assertEquals("Verified profile", saved.getRealName()); assertNotNull(saved.getLastLoginAt()); - } - @Test void disabledAccountIsRejectedWithoutProfileMutation() throws Exception { - SysUser before = admittedAdmin(); - concurrentlyChange(before.getId(), user -> user.setStatus("INACTIVE")); - assertThrows(BusinessException.class, () -> auth().findOrCreateUser(info())); - SysUser saved = users.findById(before.getId()).get(); assertEquals("INACTIVE", saved.getStatus()); - assertEquals("Original", saved.getRealName()); assertNull(saved.getLastLoginAt()); - } - @Test void currentActiveStatusIsCheckedByFinalLockedCheck() throws Exception { - SysUser before = admittedAdmin(); - concurrentlyChange(before.getId(), user -> { user.setStatus("INACTIVE"); user.setUserType("EMPLOYEE"); }); - assertThrows(BusinessException.class, () -> auth().findOrCreateUser(info())); - SysUser saved = users.findById(before.getId()).get(); assertEquals("INACTIVE", saved.getStatus()); assertEquals("EMPLOYEE", saved.getUserType()); - assertEquals("Original", saved.getRealName()); assertNull(saved.getLastLoginAt()); - } - @Test void finalizerDoesNotReuseAnOuterTransactionsCachedAdministrator() throws Exception { - SysUser before = admittedAdmin(); - new TransactionTemplate(manager).execute(s -> { - SysUser cached = users.findById(before.getId()).get(); - try { concurrentlyChange(before.getId(), user -> user.setUserType("EMPLOYEE")); } catch (Exception e) { throw new AssertionError(e); } - assertEquals("ADMIN", cached.getUserType()); - SysUser current = finalizer.completeOAuth(before.getId(), info()); - assertEquals("EMPLOYEE", current.getUserType()); assertNotSame(cached, current); return null; - }); - assertEquals("EMPLOYEE", users.findById(before.getId()).get().getUserType()); - } - @Test void oauthDoesNotEraseExistingProfileWhenProviderOmitsOptionalFields() throws Exception { - SysUser before = admittedAdmin(); - before.setAvatarUrl("existing-avatar"); before.setEmail("existing@example.com"); before.setMobile("13800000000"); - users.saveAndFlush(before); - - FeishuUserInfo info = info(); - info.setAvatarUrl(null); info.setEmail(null); info.setMobile(null); - finalizer.completeOAuth(before.getId(), info); - - SysUser saved = users.findById(before.getId()).get(); - assertEquals("existing-avatar", saved.getAvatarUrl()); - assertEquals("existing@example.com", saved.getEmail()); - assertEquals("13800000000", saved.getMobile()); - } - @ParameterizedTest - @ValueSource(strings = {"UNKNOWN", "INELIGIBLE", "OUT_OF_SCOPE"}) - void boundAdministratorCanLogInWithoutDirectoryAdmission(String directoryStatus) throws Exception { - SysUser before = users.saveAndFlush(SysUser.builder().realName("Original").status("ACTIVE").userType("ADMIN") - .feishuOpenId("ou_a").feishuUserId("u_a").directoryStatus(directoryStatus).build()); - SysUser loggedIn = auth().findOrCreateUser(info()); - assertEquals(before.getId(), loggedIn.getId()); - SysUser saved = users.findById(before.getId()).get(); assertEquals("ADMIN", saved.getUserType()); - assertEquals("Verified profile", saved.getRealName()); assertNotNull(saved.getLastLoginAt()); - } - @Test void staleSnapshotDoesNotRejectOAuthIdentityLogin() throws Exception { - SysUser before = admittedAdmin(); - settings.setMaxStatusAgeSeconds(1); - jdbc.update("UPDATE sys_user SET directory_verified_at=? WHERE id=?", - java.sql.Timestamp.from(java.time.Instant.now().minusSeconds(2)), before.getId()); - em.clear(); - SysUser loggedIn = auth().findOrCreateUser(info()); - assertEquals(before.getId(), loggedIn.getId()); - assertEquals("ELIGIBLE", users.findById(before.getId()).get().getDirectoryStatus()); - assertNotNull(users.findById(before.getId()).get().getLastLoginAt()); - } - @ParameterizedTest @ValueSource(strings = {"ADMIN", "SUPER_ADMIN", "EMPLOYEE"}) - void tenantSwitchCannotAdoptUserIdOnlyLegacyAccount(String role) throws Exception { - SysUser legacy = users.saveAndFlush(SysUser.builder().realName("Legacy").status("ACTIVE").userType(role).feishuUserId("u_a").build()); - updateApp("different-tenant-app"); when(client.fetch(any())).thenReturn(snapshot()); - assertFalse(directory.sync("MANUAL").isApplied()); - clearInvocations(client); assertThrows(BusinessException.class, () -> auth().findOrCreateUser(info())); verifyNoInteractions(client); - SysUser saved = users.findById(legacy.getId()).get(); assertNull(saved.getFeishuOpenId()); assertEquals(role, saved.getUserType()); - assertEquals("UNKNOWN", saved.getDirectoryStatus()); assertEquals("Legacy", saved.getRealName()); assertNull(saved.getLastLoginAt()); assertEquals(1, users.count()); - } - @Test void freshContextBypassesAlreadyCachedJpaConfiguration() throws Exception { - updateApp("first-app"); String oldContext = tokens.capture().fingerprint; - new TransactionTemplate(manager).execute(s -> { - SysIntegrationConfig cached = configs.findByProviderAndConfigKey("FEISHU", "appId").get(); - try { executor.submit(() -> updateApp("second-app")).get(5, TimeUnit.SECONDS); } catch (Exception e) { throw new AssertionError(e); } - assertSame(cached, configs.findByProviderAndConfigKey("FEISHU", "appId").get()); assertEquals("first-app", cached.getConfigValue()); - assertNotEquals(oldContext, tokens.capture().fingerprint); return null; - }); - } - @Test void configurationWriterWaitsForPublicationCommitOnTheSameSingleton() throws Exception { - updateApp("first-app"); when(client.fetch(any())).thenReturn(snapshot()); - CountDownLatch publishing = new CountDownLatch(1), release = new CountDownLatch(1), writerAttempted = new CountDownLatch(1); - SysUserRepository observed = mock(SysUserRepository.class, org.mockito.AdditionalAnswers.delegatesTo(users)); - doAnswer(invocation -> { - publishing.countDown(); if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("publication release timed out"); - return users.findAll(); - }).when(observed).findAll(); - FeishuDirectoryService publishingDirectory = new FeishuDirectoryService(jdbc, manager, observed, tokens, client, settings, new ObjectMapper()); - JdbcTemplate watched = spy(jdbc); - doAnswer(invocation -> { writerAttempted.countDown(); return invocation.callRealMethod(); }) - .when(watched).queryForMap("SELECT * FROM feishu_directory_state WHERE id=1 FOR UPDATE"); - ReflectionTestUtils.setField(updater, "jdbc", watched); - Future run = executor.submit(() -> publishingDirectory.sync("MANUAL")); - try { - assertTrue(publishing.await(5, TimeUnit.SECONDS)); - Future change = executor.submit(() -> updateApp("second-app")); assertTrue(writerAttempted.await(5, TimeUnit.SECONDS)); - assertThrows(TimeoutException.class, () -> change.get(200, TimeUnit.MILLISECONDS)); - assertEquals("first-app", jdbc.queryForObject("SELECT config_value FROM sys_integration_config WHERE provider='FEISHU' AND config_key='appId'", String.class)); - release.countDown(); assertTrue(run.get(5, TimeUnit.SECONDS).isApplied()); change.get(5, TimeUnit.SECONDS); - assertEquals("CONTEXT_CHANGED", directory.status().get("snapshotState")); - } finally { release.countDown(); } - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuTenantTokenServiceTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuTenantTokenServiceTest.java deleted file mode 100644 index b450db9..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuTenantTokenServiceTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.finance.system.service.IntegrationConfigReader; -import org.junit.jupiter.api.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestTemplate; - -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; - -class FeishuTenantTokenServiceTest { - private final IntegrationConfigReader config = mock(IntegrationConfigReader.class); - private final FeishuDirectorySettings settings = new FeishuDirectorySettings(); - private final RestTemplate http = new RestTemplate(); - private final MockRestServiceServer server = MockRestServiceServer.createServer(http); - private final FeishuTenantTokenService service = new FeishuTenantTokenService(config, settings, http); - private final FeishuTenantTokenService.Context context = - new FeishuTenantTokenService.Context("app", "secret", "ctx"); - - private Map values(boolean enabled) { - Map values = new HashMap<>(); - values.put("appId", "app"); - values.put("appSecret", "secret"); - values.put(IntegrationConfigReader.INTERNAL_ENABLED_KEY, Boolean.toString(enabled)); - return values; - } - - @Test - void missingConfigurationHasDedicatedSafeDiagnostic() { - Map values = values(true); - values.put("appSecret", ""); - when(config.freshFeishu()).thenReturn(values); - - FeishuTenantTokenService.DiagnosticFailure failure = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, service::capture); - assertEquals("CONFIGURATION_MISSING", failure.getDiagnosticCode()); - } - - @Test - void disabledConfigurationHasDedicatedSafeDiagnostic() { - when(config.freshFeishu()).thenReturn(values(false)); - - FeishuTenantTokenService.DiagnosticFailure failure = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, service::capture); - assertEquals("CONFIGURATION_MISSING", failure.getDiagnosticCode()); - } - - @Test - void tokenApiCodeIsPropagatedWithoutResponseBody() { - server.expect(requestTo(containsString("tenant_access_token/internal"))) - .andRespond(withSuccess("{\"code\":999999,\"msg\":\"secret response body\"}", - MediaType.APPLICATION_JSON)); - - FeishuTenantTokenService.DiagnosticFailure failure = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> service.token(context)); - assertEquals("FEISHU_CODE_999999", failure.getDiagnosticCode()); - org.junit.jupiter.api.Assertions.assertFalse(failure.getMessage().contains("secret response body")); - server.verify(); - } - - @Test - void oversizedTokenResponseCodeCannotWrapToSuccess() { - server.expect(requestTo(containsString("tenant_access_token/internal"))) - .andRespond(withSuccess("{\"code\":18446744073709551616,\"tenant_access_token\":\"token\"}", - MediaType.APPLICATION_JSON)); - - FeishuTenantTokenService.DiagnosticFailure failure = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> service.token(context)); - assertEquals("TOKEN_RESPONSE_INVALID", failure.getDiagnosticCode()); - server.verify(); - } - - @Test - void tokenHttpStatusIsPropagatedWithoutResponseBody() { - server.expect(requestTo(containsString("tenant_access_token/internal"))) - .andRespond(withStatus(org.springframework.http.HttpStatus.UNAUTHORIZED).body("app_secret=secret")); - - FeishuTenantTokenService.DiagnosticFailure failure = assertThrows( - FeishuTenantTokenService.DiagnosticFailure.class, () -> service.token(context)); - assertEquals("HTTP_STATUS_401", failure.getDiagnosticCode()); - org.junit.jupiter.api.Assertions.assertFalse(failure.getMessage().contains("app_secret")); - server.verify(); - } -} diff --git a/src/test/java/com/finance/system/config/JwtConfigTest.java b/src/test/java/com/finance/system/config/JwtConfigTest.java deleted file mode 100644 index 5f4f83d..0000000 --- a/src/test/java/com/finance/system/config/JwtConfigTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.finance.system.config; - -import com.finance.system.controller.AuthController; -import com.finance.system.entity.SysUser; -import com.finance.system.repository.SysDepartmentRepository; -import com.finance.system.repository.SysUserRepository; -import com.finance.system.security.JwtAuthenticationFilter; -import com.finance.system.security.UserPrincipal; -import io.jsonwebtoken.Claims; -import org.junit.jupiter.api.Test; -import org.springframework.core.env.Environment; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.mock.web.MockFilterChain; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.security.crypto.password.PasswordEncoder; - -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.Collections; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class JwtConfigTest { - - @Test - void rejectsBlankSecret() { - IllegalStateException exception = assertThrows(IllegalStateException.class, - () -> JwtConfig.validateSecretValue(" ")); - - assertTrue(exception.getMessage().contains("JWT_SECRET")); - } - - @Test - void rejectsSecretShorterThan32Utf8Bytes() { - IllegalStateException exception = assertThrows(IllegalStateException.class, - () -> JwtConfig.validateSecretValue("1234567890123456789012345678901")); - - assertTrue(exception.getMessage().contains("JWT_SECRET")); - } - - @Test - void acceptsSecretWithAtLeast32Utf8Bytes() { - assertDoesNotThrow(() -> JwtConfig.validateSecretValue("12345678901234567890123456789012")); - } - - @Test - void rejectsZeroExpiration() { - IllegalStateException exception = assertThrows(IllegalStateException.class, - () -> JwtConfig.validateExpirationValue(0L)); - - assertTrue(exception.getMessage().contains("JWT_EXPIRATION")); - } - - @Test - void rejectsNegativeExpiration() { - IllegalStateException exception = assertThrows(IllegalStateException.class, - () -> JwtConfig.validateExpirationValue(-1L)); - - assertTrue(exception.getMessage().contains("JWT_EXPIRATION")); - } - - @Test - void acceptsPositiveExpiration() { - assertDoesNotThrow(() -> JwtConfig.validateExpirationValue(1L)); - } - - @Test - void calculatesNextMidnightAndPositiveBoundedTtl() { - ZoneId zone = ZoneId.of("Asia/Shanghai"); - Instant beforeMidnight = ZonedDateTime.of(2026, 1, 1, 23, 59, 59, 0, zone).toInstant(); - Instant midnight = ZonedDateTime.of(2026, 1, 2, 0, 0, 0, 0, zone).toInstant(); - - assertEquals(midnight, JwtConfig.nextMidnight(beforeMidnight, zone)); - long ttl = JwtConfig.calculateTokenTtlMillis(beforeMidnight, zone, 86_400_000L); - assertEquals(1_000L, ttl); - assertTrue(ttl > 0); - assertTrue(ttl <= 86_400_000L); - } - - @Test - void midnightBoundaryUsesTheFollowingLocalDate() { - ZoneId zone = ZoneId.of("Asia/Shanghai"); - Instant midnight = ZonedDateTime.of(2026, 1, 2, 0, 0, 0, 0, zone).toInstant(); - Instant followingMidnight = ZonedDateTime.of(2026, 1, 3, 0, 0, 0, 0, zone).toInstant(); - - assertEquals(followingMidnight, JwtConfig.nextMidnight(midnight, zone)); - assertEquals(86_400_000L, - JwtConfig.calculateTokenTtlMillis(midnight, zone, 86_400_000L)); - } - - @Test - void usesZoneRulesForDaylightSavingTime() { - ZoneId zone = ZoneId.of("America/New_York"); - Instant startOfShortDstDay = ZonedDateTime.of(2026, 3, 8, 0, 0, 0, 0, zone).toInstant(); - - assertEquals(23 * 60 * 60 * 1_000L, - JwtConfig.calculateTokenTtlMillis(startOfShortDstDay, zone, 172_800_000L)); - } - - @Test - void inactiveUserTokenDoesNotCreateAuthentication() throws Exception { - JwtConfig jwtConfig = mock(JwtConfig.class); - SysUserRepository users = mock(SysUserRepository.class); - Claims claims = io.jsonwebtoken.Jwts.claims(); - claims.put("userId", 42L); - when(jwtConfig.parseToken("token")).thenReturn(claims); - when(users.findById(42L)).thenReturn(Optional.of(SysUser.builder() - .id(42L).status("INACTIVE").userType("ADMIN").build())); - - SecurityContextHolder.clearContext(); - new ExposedJwtAuthenticationFilter(jwtConfig, users).run( - bearerRequest("token"), new MockHttpServletResponse(), new MockFilterChain()); - - assertNull(SecurityContextHolder.getContext().getAuthentication()); - SecurityContextHolder.clearContext(); - } - - @Test - void refreshBuildsTokenFromLatestDatabaseRole() { - JwtConfig jwtConfig = configuredJwtConfig(86_400_000L); - SysUserRepository users = mock(SysUserRepository.class); - SysUser latestUser = SysUser.builder() - .id(42L).employeeNo("E42").realName("Latest Name") - .userType("ADMIN").status("ACTIVE").build(); - when(users.findById(42L)).thenReturn(Optional.of(latestUser)); - - UserPrincipal stalePrincipal = UserPrincipal.builder() - .id(42L).employeeNo("E42").realName("Old Name") - .userType("EMPLOYEE").build(); - SecurityContextHolder.getContext().setAuthentication( - new UsernamePasswordAuthenticationToken(stalePrincipal, null, - Collections.emptyList())); - - AuthController controller = new AuthController(users, mock(SysDepartmentRepository.class), - jwtConfig, null, mock(Environment.class), mock(PasswordEncoder.class)); - ReflectionTestUtils.setField(controller, "directoryAccess", mock(com.finance.system.adapter.feishu.FeishuDirectoryAccessService.class)); - com.finance.system.dto.LoginResponse response = controller.refreshToken() - .getBody().getData(); - - assertEquals("ADMIN", jwtConfig.parseToken(response.getToken()).get("userType", String.class)); - assertEquals("ADMIN", response.getUser().getUserType()); - assertTrue(response.getExpiresIn() > 0); - SecurityContextHolder.clearContext(); - } - - private JwtConfig configuredJwtConfig(long expiration) { - JwtConfig jwtConfig = new JwtConfig(); - ReflectionTestUtils.setField(jwtConfig, "secret", - "test-only-jwt-secret-012345678901234567890123456789"); - ReflectionTestUtils.setField(jwtConfig, "expiration", expiration); - ReflectionTestUtils.setField(jwtConfig, "timeZone", "Asia/Shanghai"); - return jwtConfig; - } - - private MockHttpServletRequest bearerRequest(String token) { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader("Authorization", "Bearer " + token); - return request; - } - - private static class ExposedJwtAuthenticationFilter extends JwtAuthenticationFilter { - ExposedJwtAuthenticationFilter(JwtConfig jwtConfig, SysUserRepository users) { - super(jwtConfig, users); - } - - void run(MockHttpServletRequest request, MockHttpServletResponse response, - MockFilterChain chain) throws Exception { - doFilterInternal(request, response, chain); - } - } -} diff --git a/src/test/java/com/finance/system/config/WebConfigTest.java b/src/test/java/com/finance/system/config/WebConfigTest.java deleted file mode 100644 index 057cb39..0000000 --- a/src/test/java/com/finance/system/config/WebConfigTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.finance.system.config; - -import org.junit.jupiter.api.Test; -import org.springframework.mock.web.MockFilterChain; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.filter.CorsFilter; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class WebConfigTest { - - @Test - void corsAllowsOnlyConfiguredFrontendOrigin() throws Exception { - WebConfig webConfig = new WebConfig(); - ReflectionTestUtils.setField(webConfig, "frontendUrl", "http://frontend.example"); - CorsFilter filter = webConfig.corsFilter(); - - MockHttpServletRequest allowed = preflight("http://frontend.example"); - MockHttpServletResponse allowedResponse = new MockHttpServletResponse(); - filter.doFilter(allowed, allowedResponse, new MockFilterChain()); - assertEquals("http://frontend.example", allowedResponse.getHeader("Access-Control-Allow-Origin")); - assertEquals("true", allowedResponse.getHeader("Access-Control-Allow-Credentials")); - - MockHttpServletRequest denied = preflight("http://attacker.example"); - MockHttpServletResponse deniedResponse = new MockHttpServletResponse(); - filter.doFilter(denied, deniedResponse, new MockFilterChain()); - assertNull(deniedResponse.getHeader("Access-Control-Allow-Origin")); - } - - private MockHttpServletRequest preflight(String origin) { - MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/api/auth/login"); - request.addHeader("Origin", origin); - request.addHeader("Access-Control-Request-Method", "POST"); - return request; - } -} diff --git a/src/test/java/com/finance/system/controller/AuthControllerTest.java b/src/test/java/com/finance/system/controller/AuthControllerTest.java deleted file mode 100644 index 478766d..0000000 --- a/src/test/java/com/finance/system/controller/AuthControllerTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.finance.system.controller; - -import com.finance.system.config.JwtConfig; -import com.finance.system.dto.LoginRequest; -import com.finance.system.entity.SysUser; -import com.finance.system.repository.SysDepartmentRepository; -import com.finance.system.repository.SysUserRepository; -import org.junit.jupiter.api.Test; -import org.springframework.core.env.Environment; -import org.springframework.http.ResponseEntity; -import org.springframework.security.crypto.password.PasswordEncoder; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -class AuthControllerTest { - - @Test - void passwordLoginIsRejectedOutsideLocalProfile() { - Environment environment = mock(Environment.class); - when(environment.getActiveProfiles()).thenReturn(new String[]{"prod"}); - SysUserRepository users = mock(SysUserRepository.class); - AuthController controller = new AuthController(users, mock(SysDepartmentRepository.class), - mock(JwtConfig.class), null, environment, mock(PasswordEncoder.class)); - LoginRequest request = new LoginRequest(); - request.setEmployeeNo("E1001"); - request.setPassword("does-not-matter"); - - ResponseEntity response = controller.login(request); - - assertEquals(403, response.getStatusCodeValue()); - assertEquals(403, ((com.finance.system.dto.ApiResponse) response.getBody()).getCode()); - verifyNoInteractions(users); - } - - @Test - void localLoginRejectsMissingPasswordHashAndDoesNotIssueToken() { - Environment environment = mock(Environment.class); - when(environment.getActiveProfiles()).thenReturn(new String[]{"local"}); - SysUserRepository users = mock(SysUserRepository.class); - SysUser user = SysUser.builder().id(1L).employeeNo("E1001") - .status("ACTIVE").passwordHash(null).build(); - when(users.findByEmployeeNo("E1001")).thenReturn(user); - JwtConfig jwtConfig = mock(JwtConfig.class); - AuthController controller = new AuthController(users, mock(SysDepartmentRepository.class), - jwtConfig, null, environment, mock(PasswordEncoder.class)); - LoginRequest request = new LoginRequest(); - request.setEmployeeNo("E1001"); - request.setPassword("local-password"); - - ResponseEntity response = controller.login(request); - - assertEquals(401, response.getStatusCodeValue()); - verifyNoInteractions(jwtConfig); - } -} diff --git a/src/test/java/com/finance/system/controller/CashierControllerTest.java b/src/test/java/com/finance/system/controller/CashierControllerTest.java deleted file mode 100644 index 4ceb86c..0000000 --- a/src/test/java/com/finance/system/controller/CashierControllerTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.finance.system.controller; - -import com.finance.system.dto.CreatePaymentRequest; -import com.finance.system.dto.PaymentResultDto; -import com.finance.system.exception.BusinessException; -import com.finance.system.security.UserPrincipal; -import com.finance.system.service.ReimPaymentService; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; - -import java.math.BigDecimal; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - -class CashierControllerTest { - private final ReimPaymentService paymentService = mock(ReimPaymentService.class); - private CashierController controller; - - @BeforeEach - void setUp() { - controller = new CashierController(paymentService); - UserPrincipal principal = UserPrincipal.builder().id(7L).employeeNo("E7") - .realName("Cashier").userType("FINANCE").build(); - SecurityContextHolder.getContext().setAuthentication( - new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities())); - } - - @AfterEach - void tearDown() { - SecurityContextHolder.clearContext(); - } - - @Test - void payRejectsConflictingHeaderAndBodyIdempotencyKeys() { - CreatePaymentRequest request = request("body-key"); - - BusinessException error = assertThrows(BusinessException.class, - () -> controller.executePayment(request, "header-key")); - - assertEquals(409, error.getStatusCode()); - verifyNoInteractions(paymentService); - } - - @Test - void partialPayUsesBodyKeyWhenHeaderIsBlank() throws Exception { - CreatePaymentRequest request = request(" body-key "); - when(paymentService.processPartialPayment(eq(10L), eq(new BigDecimal("12.00")), eq(7L), - isNull(), isNull(), isNull(), eq("body-key"))) - .thenReturn(PaymentResultDto.builder().paymentNo("PAY-1").build()); - - controller.processPartialPayment(request, " "); - - verify(paymentService).processPartialPayment(10L, new BigDecimal("12.00"), 7L, - null, null, null, "body-key"); - } - - @Test - void payUsesHeaderKeyWhenBothValuesMatchAfterTrim() { - CreatePaymentRequest request = request(" key-1 "); - when(paymentService.executePayment(eq(10L), eq(new BigDecimal("12.00")), eq(7L), - isNull(), isNull(), isNull(), eq("key-1"))) - .thenReturn(PaymentResultDto.builder().paymentNo("PAY-1").build()); - - controller.executePayment(request, " key-1 "); - - verify(paymentService).executePayment(10L, new BigDecimal("12.00"), 7L, - null, null, null, "key-1"); - } - - private CreatePaymentRequest request(String idempotencyKey) { - CreatePaymentRequest request = new CreatePaymentRequest(); - request.setApplicationId(10L); - request.setPaymentAmount(new BigDecimal("12.00")); - request.setIdempotencyKey(idempotencyKey); - return request; - } -} diff --git a/src/test/java/com/finance/system/controller/FeishuDirectoryControllerTest.java b/src/test/java/com/finance/system/controller/FeishuDirectoryControllerTest.java deleted file mode 100644 index 4bea227..0000000 --- a/src/test/java/com/finance/system/controller/FeishuDirectoryControllerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.finance.system.controller; - -import com.finance.system.adapter.feishu.FeishuDirectoryService; -import com.finance.system.security.PermissionChecker; -import org.junit.jupiter.api.Test; -import org.springframework.context.annotation.*; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import java.util.Collections; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.mockito.ArgumentMatchers.*; - -class FeishuDirectoryControllerTest { - @Configuration - @EnableGlobalMethodSecurity(prePostEnabled = true) - static class Config { - @Bean FeishuDirectoryService directory() { return mock(FeishuDirectoryService.class); } - @Bean PermissionChecker permissionChecker() { return mock(PermissionChecker.class); } - @Bean FeishuDirectoryController controller(FeishuDirectoryService directory) { return new FeishuDirectoryController(directory); } - } - @Test void unauthorizedSyncIsRejectedAndBindOnlyCanReadStatus() { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class)) { - FeishuDirectoryController controller = context.getBean(FeishuDirectoryController.class); - FeishuDirectoryService directory = context.getBean(FeishuDirectoryService.class); - PermissionChecker checker = context.getBean(PermissionChecker.class); - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("employee", null, Collections.emptyList())); - assertThrows(org.springframework.security.access.AccessDeniedException.class, controller::sync); verify(directory, never()).sync(anyString()); - when(checker.has(any(), eq("system:feishu:bind"))).thenReturn(true); - controller.status(); verify(directory).status(); - assertThrows(org.springframework.security.access.AccessDeniedException.class, controller::sync); - } finally { SecurityContextHolder.clearContext(); } - } - @Test void failedSyncReturnsNon2xxEnvelopeWithRun() { - FeishuDirectoryService directory = mock(FeishuDirectoryService.class); FeishuDirectoryService.Run run = new FeishuDirectoryService.Run(); - run.setState("FAILED"); run.setErrorMessage("Sanitized failure"); when(directory.sync("MANUAL")).thenReturn(run); - org.springframework.http.ResponseEntity response = new FeishuDirectoryController(directory).sync(); - assertEquals(503, response.getStatusCodeValue()); - assertSame(run, ((com.finance.system.dto.ApiResponse) response.getBody()).getData()); - } -} diff --git a/src/test/java/com/finance/system/controller/FeishuWebhookControllerTest.java b/src/test/java/com/finance/system/controller/FeishuWebhookControllerTest.java deleted file mode 100644 index 44d1b24..0000000 --- a/src/test/java/com/finance/system/controller/FeishuWebhookControllerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.finance.system.controller; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.adapter.feishu.FeishuApprovalService; -import com.finance.system.adapter.feishu.FeishuAuthService; -import com.finance.system.entity.SysWebhookEvent; -import com.finance.system.repository.SysWebhookEventRepository; -import org.junit.jupiter.api.Test; -import org.springframework.http.ResponseEntity; - -import java.time.LocalDateTime; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class FeishuWebhookControllerTest { - - @Test - void failedWebhookRemainsRetryableAndSuccessfulEventIsDeduplicated() { - FeishuAuthService auth = mock(FeishuAuthService.class); - FeishuApprovalService approvals = mock(FeishuApprovalService.class); - SysWebhookEventRepository events = mock(SysWebhookEventRepository.class); - ObjectMapper mapper = new ObjectMapper(); - String raw = "{\"event_type\":\"approval_task\",\"event_id\":\"evt-1\",\"task\":{}}"; - String timestamp = String.valueOf(Instant.now().getEpochSecond()); - when(auth.isWebhookAuthorized(anyMap(), isNull(), eq(timestamp), isNull(), eq(raw))).thenReturn(true); - doThrow(new IllegalStateException("temporary failure")) - .doNothing().when(approvals).handleApprovalEvent(org.mockito.ArgumentMatchers.anyMap()); - SysWebhookEvent event = new SysWebhookEvent("evt-1", SysWebhookEvent.FAILED, LocalDateTime.now()); - when(events.findById("evt-1")).thenReturn(Optional.of(event)); - FeishuAuthController controller = new FeishuAuthController(auth, approvals, mapper, events); - - ResponseEntity> failed = controller.handleWebhook(raw, null, timestamp, null); - assertEquals(500, failed.getStatusCodeValue()); - assertEquals(SysWebhookEvent.FAILED, event.getStatus()); - - ResponseEntity> retry = controller.handleWebhook(raw, null, timestamp, null); - ResponseEntity> duplicate = controller.handleWebhook(raw, null, timestamp, null); - - assertEquals(SysWebhookEvent.PROCESSED, event.getStatus()); - assertEquals(200, retry.getStatusCodeValue()); - assertEquals(200, duplicate.getStatusCodeValue()); - verify(approvals, org.mockito.Mockito.times(2)).handleApprovalEvent(org.mockito.ArgumentMatchers.anyMap()); - verify(events, org.mockito.Mockito.times(3)).insertIfAbsent("evt-1"); - verify(events, org.mockito.Mockito.times(3)).findById("evt-1"); - } - - @Test - void eventIdAndFreshTimestampAreRequiredForNonChallengeRequests() { - FeishuAuthService auth = mock(FeishuAuthService.class); - FeishuApprovalService approvals = mock(FeishuApprovalService.class); - SysWebhookEventRepository events = mock(SysWebhookEventRepository.class); - ObjectMapper mapper = new ObjectMapper(); - String timestamp = String.valueOf(Instant.now().getEpochSecond()); - when(auth.isWebhookAuthorized(anyMap(), isNull(), anyString(), isNull(), anyString())).thenReturn(true); - FeishuAuthController controller = new FeishuAuthController(auth, approvals, mapper, events); - - assertEquals(400, controller.handleWebhook("{}", null, timestamp, null).getStatusCodeValue()); - assertEquals(400, controller.handleWebhook( - "{\"event_id\":\"evt-old\",\"event_type\":\"approval_task\"}", - null, String.valueOf(Instant.now().getEpochSecond() - 301), null).getStatusCodeValue()); - assertEquals(400, controller.handleWebhook("{}", null, "not-a-timestamp", null).getStatusCodeValue()); - } - - @Test - void v2EnvelopeUsesNestedEventIdForInboxDeduplication() { - FeishuAuthService auth = mock(FeishuAuthService.class); - FeishuApprovalService approvals = mock(FeishuApprovalService.class); - SysWebhookEventRepository events = mock(SysWebhookEventRepository.class); - ObjectMapper mapper = new ObjectMapper(); - String raw = "{\"header\":{\"event_type\":\"approval_task\"}," - + "\"event\":{\"event_id\":\"v2-evt-1\",\"task\":{}}}"; - String timestamp = String.valueOf(Instant.now().getEpochSecond()); - when(auth.isWebhookAuthorized(anyMap(), isNull(), eq(timestamp), isNull(), eq(raw))).thenReturn(true); - SysWebhookEvent event = new SysWebhookEvent("v2-evt-1", SysWebhookEvent.PROCESSED, LocalDateTime.now()); - when(events.findById("v2-evt-1")).thenReturn(Optional.of(event)); - FeishuAuthController controller = new FeishuAuthController(auth, approvals, mapper, events); - - ResponseEntity> response = controller.handleWebhook(raw, null, timestamp, null); - - assertEquals(200, response.getStatusCodeValue()); - assertNotNull(event); - verify(events).insertIfAbsent("v2-evt-1"); - } -} diff --git a/src/test/java/com/finance/system/repository/SysWebhookEventRepositoryTest.java b/src/test/java/com/finance/system/repository/SysWebhookEventRepositoryTest.java deleted file mode 100644 index 0c989c7..0000000 --- a/src/test/java/com/finance/system/repository/SysWebhookEventRepositoryTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.finance.system.repository; - -import com.finance.system.entity.SysWebhookEvent; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ActiveProfiles; - -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@DataJpaTest -@ActiveProfiles("local") -class SysWebhookEventRepositoryTest { - - @Autowired - private SysWebhookEventRepository repository; - - @Test - void insertIfAbsentIsIdempotentAndFindByIdUsesInboxRow() { - assertEquals(1, repository.insertIfAbsent("evt-repository-test")); - assertEquals(0, repository.insertIfAbsent("evt-repository-test")); - - Optional event = repository.findById("evt-repository-test"); - assertTrue(event.isPresent()); - assertEquals(SysWebhookEvent.PROCESSING, event.get().getStatus()); - assertTrue(event.get().getCreatedAt() != null); - } -} diff --git a/src/test/java/com/finance/system/security/PermissionEnforcementTest.java b/src/test/java/com/finance/system/security/PermissionEnforcementTest.java deleted file mode 100644 index 401924a..0000000 --- a/src/test/java/com/finance/system/security/PermissionEnforcementTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.finance.system.security; - -import com.finance.system.entity.SysUser; -import com.finance.system.repository.*; -import com.finance.system.service.RoleService; -import com.finance.system.controller.RoleController; -import org.springframework.security.access.prepost.PreAuthorize; -import org.junit.jupiter.api.Test; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; - -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -class PermissionEnforcementTest { - @Test - void employeeCannotUseManagementPermissionButLegacyAdminCan() { - SysUserRepository users = mock(SysUserRepository.class); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - RoleService roleService = new RoleService(mock(SysRoleRepository.class), mock(SysPermissionRepository.class), - mock(SysRolePermissionRepository.class), mock(SysUserRoleRepository.class), users, - mock(SysUserGroupRepository.class), mock(SysUserGroupMemberRepository.class), mock(SysUserGroupRoleRepository.class)); - PermissionChecker checker = new PermissionChecker(roleService); - UserPrincipal principal = UserPrincipal.builder().id(1L).employeeNo("E1").userType(null).build(); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()); - - assertFalse(checker.has(authentication, "system:role:manage")); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("ADMIN").build())); - assertTrue(checker.has(authentication, "system:role:manage")); - } - - @Test - void roleManagementEndpointsDeclareBackendPermissionChecks() throws Exception { - assertEquals("@permissionChecker.has(authentication, 'system:role:manage')", - RoleController.class.getMethod("create", java.util.Map.class).getAnnotation(PreAuthorize.class).value()); - assertEquals("@permissionChecker.has(authentication, 'system:role:manage')", - RoleController.class.getMethod("delete", Long.class).getAnnotation(PreAuthorize.class).value()); - } - - @Test - void employeeCannotUseAllReimbursementOrPaymentPermissions() { - SysUserRepository users = mock(SysUserRepository.class); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder() - .id(1L).userType("EMPLOYEE").build())); - RoleService roleService = new RoleService(mock(SysRoleRepository.class), mock(SysPermissionRepository.class), - mock(SysRolePermissionRepository.class), mock(SysUserRoleRepository.class), users, - mock(SysUserGroupRepository.class), mock(SysUserGroupMemberRepository.class), mock(SysUserGroupRoleRepository.class)); - PermissionChecker checker = new PermissionChecker(roleService); - UserPrincipal principal = UserPrincipal.builder().id(1L).userType("EMPLOYEE").build(); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - principal, null, principal.getAuthorities()); - - assertFalse(checker.has(authentication, "reimbursement:view-all")); - assertFalse(checker.has(authentication, "payment:register")); - } -} diff --git a/src/test/java/com/finance/system/service/IntegrationConfigCryptoTest.java b/src/test/java/com/finance/system/service/IntegrationConfigCryptoTest.java deleted file mode 100644 index c04c60f..0000000 --- a/src/test/java/com/finance/system/service/IntegrationConfigCryptoTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.finance.system.service; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class IntegrationConfigCryptoTest { - @Test - void encryptionUsesVersionedRandomNonceAndRoundTrips() { - IntegrationConfigCrypto crypto = new IntegrationConfigCrypto("unit-test-key"); - - String first = crypto.encrypt("top-secret-value"); - String second = crypto.encrypt("top-secret-value"); - - assertTrue(first.startsWith(IntegrationConfigCrypto.PREFIX)); - assertNotEquals("top-secret-value", first); - assertNotEquals(first, second); - assertEquals("top-secret-value", crypto.decrypt(first)); - } - - @Test - void missingKeyCannotEncrypt() { - IntegrationConfigCrypto crypto = new IntegrationConfigCrypto(""); - - IllegalStateException error = assertThrows(IllegalStateException.class, - () -> crypto.encrypt("secret")); - assertTrue(error.getMessage().contains("APP_INTEGRATION_ENCRYPTION_KEY")); - } - - @Test - void nonEncryptedLegacyValueRemainsReadable() { - IntegrationConfigCrypto crypto = new IntegrationConfigCrypto(""); - - assertEquals("legacy-secret", crypto.decrypt("legacy-secret")); - } -} diff --git a/src/test/java/com/finance/system/service/IntegrationConfigReaderTest.java b/src/test/java/com/finance/system/service/IntegrationConfigReaderTest.java deleted file mode 100644 index 13bb653..0000000 --- a/src/test/java/com/finance/system/service/IntegrationConfigReaderTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.finance.system.service; - -import com.finance.system.adapter.feishu.FeishuConfig; -import com.finance.system.adapter.kingdee.KingdeeConfig; -import com.finance.system.entity.SysIntegrationConfig; -import com.finance.system.repository.SysIntegrationConfigRepository; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.*; - -class IntegrationConfigReaderTest { - @Test - void databaseValueWinsAndMissingValueFallsBackToEnvironment() { - SysIntegrationConfigRepository repository = mock(SysIntegrationConfigRepository.class); - FeishuConfig feishu = new FeishuConfig(); feishu.setAppId("env-app-id"); feishu.setAppSecret("env-secret"); - KingdeeConfig kingdee = new KingdeeConfig(); - when(repository.findByProviderAndConfigKey("FEISHU", "appId")) - .thenReturn(Optional.of(SysIntegrationConfig.builder().configValue("db-app-id").build())); - when(repository.findByProviderAndConfigKey("FEISHU", "appSecret")).thenReturn(Optional.empty()); - IntegrationConfigReader reader = new IntegrationConfigReader(repository, feishu, kingdee); - - assertEquals("db-app-id", reader.get("FEISHU", "appId")); - assertEquals("env-secret", reader.get("FEISHU", "appSecret")); - } - - @Test - void persistedDisabledFlagOverridesEnabledEnvironment() { - SysIntegrationConfigRepository repository = mock(SysIntegrationConfigRepository.class); - FeishuConfig feishu = new FeishuConfig(); feishu.setAppId("env-id"); feishu.setAppSecret("env-secret"); - KingdeeConfig kingdee = new KingdeeConfig(); kingdee.setEnabled(true); - when(repository.findByProviderOrderByConfigKeyAsc("KINGDEE")) - .thenReturn(Collections.singletonList(SysIntegrationConfig.builder().enabled(false).build())); - IntegrationConfigReader reader = new IntegrationConfigReader(repository, feishu, kingdee); - - assertTrue(kingdee.isEnabled()); - org.junit.jupiter.api.Assertions.assertFalse(reader.isEnabled("KINGDEE")); - } - - @Test - void explicitProviderSwitchIsUsedEvenWithoutProviderFields() { - SysIntegrationConfigRepository repository = mock(SysIntegrationConfigRepository.class); - FeishuConfig feishu = new FeishuConfig(); feishu.setAppId("env-id"); feishu.setAppSecret("env-secret"); - KingdeeConfig kingdee = new KingdeeConfig(); kingdee.setEnabled(true); - SysIntegrationConfig disabled = SysIntegrationConfig.builder().provider("KINGDEE") - .configKey(IntegrationConfigReader.INTERNAL_ENABLED_KEY).configValue("false").enabled(false).build(); - when(repository.findByProviderAndConfigKey("KINGDEE", IntegrationConfigReader.INTERNAL_ENABLED_KEY)) - .thenReturn(Optional.of(disabled)); - when(repository.findByProviderOrderByConfigKeyAsc("KINGDEE")) - .thenReturn(Collections.singletonList(disabled)); - IntegrationConfigReader reader = new IntegrationConfigReader(repository, feishu, kingdee); - - assertFalse(reader.isEnabled("KINGDEE")); - disabled.setConfigValue("true"); - assertTrue(reader.isEnabled("KINGDEE")); - } - - @Test - void encryptedDatabaseSecretIsDecryptedAndLegacyPlaintextStillWorks() { - SysIntegrationConfigRepository repository = mock(SysIntegrationConfigRepository.class); - FeishuConfig feishu = new FeishuConfig(); - KingdeeConfig kingdee = new KingdeeConfig(); - IntegrationConfigCrypto crypto = new IntegrationConfigCrypto("unit-test-key"); - SysIntegrationConfig encrypted = SysIntegrationConfig.builder().provider("FEISHU") - .configKey("appSecret").configValue(crypto.encrypt("db-secret")) - .secret(true).build(); - when(repository.findByProviderAndConfigKey("FEISHU", "appSecret")) - .thenReturn(Optional.of(encrypted)); - IntegrationConfigReader reader = new IntegrationConfigReader(repository, feishu, kingdee); - reader.setIntegrationConfigCrypto(crypto); - - assertEquals("db-secret", reader.get("FEISHU", "appSecret")); - - SysIntegrationConfig legacy = SysIntegrationConfig.builder().provider("FEISHU") - .configKey("verificationToken").configValue("legacy-token").secret(true).build(); - when(repository.findByProviderAndConfigKey("FEISHU", "verificationToken")) - .thenReturn(Optional.of(legacy)); - assertEquals("legacy-token", reader.get("FEISHU", "verificationToken")); - } -} diff --git a/src/test/java/com/finance/system/service/IntegrationConfigServiceTest.java b/src/test/java/com/finance/system/service/IntegrationConfigServiceTest.java deleted file mode 100644 index f803191..0000000 --- a/src/test/java/com/finance/system/service/IntegrationConfigServiceTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.finance.system.service; - -import com.finance.system.entity.SysIntegrationConfig; -import com.finance.system.repository.SysIntegrationConfigRepository; -import org.junit.jupiter.api.Test; - -import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -class IntegrationConfigServiceTest { - private final SysIntegrationConfigRepository repository = mock(SysIntegrationConfigRepository.class); - private final IntegrationConfigService service = new IntegrationConfigService(repository); - @org.junit.jupiter.api.BeforeEach void persistenceCollaborators() { - org.springframework.test.util.ReflectionTestUtils.setField(service, "jdbc", mock(org.springframework.jdbc.core.JdbcTemplate.class)); - org.springframework.test.util.ReflectionTestUtils.setField(service, "entityManager", mock(javax.persistence.EntityManager.class)); - } - - @Test - void secretIsMaskedAndBlankSecretKeepsExistingValue() { - SysIntegrationConfig existing = SysIntegrationConfig.builder().id(1L).provider("FEISHU") - .configKey("appSecret").configValue("do-not-return-this-secret").secret(true).enabled(true).build(); - when(repository.findByProviderAndConfigKey("FEISHU", "appSecret")).thenReturn(Optional.of(existing)); - when(repository.findByProviderOrderByConfigKeyAsc("FEISHU")).thenReturn(Collections.singletonList(existing)); - - Map body = new HashMap<>(); body.put("provider", "FEISHU"); body.put("enabled", true); - body.put("values", Collections.singletonMap("appSecret", "")); - service.update(body); - - assertEquals("do-not-return-this-secret", existing.getConfigValue()); - Map view = service.view(); - @SuppressWarnings("unchecked") Map feishu = (Map) view.get("feishu"); - @SuppressWarnings("unchecked") List> fields = (List>) feishu.get("fields"); - Map secretField = fields.stream().filter(x -> "appSecret".equals(x.get("key"))).findFirst().get(); - assertEquals(true, secretField.get("configured")); - assertFalse(String.valueOf(secretField.get("value")).contains("do-not-return-this-secret")); - } - - @Test - void newSecretIsStoredEncryptedAndViewOnlyReturnsMask() { - IntegrationConfigCrypto crypto = new IntegrationConfigCrypto("unit-test-key"); - service.setIntegrationConfigCrypto(crypto); - when(repository.findByProviderAndConfigKey(eq("FEISHU"), anyString())).thenReturn(Optional.empty()); - when(repository.findByProviderOrderByConfigKeyAsc("FEISHU")).thenReturn(Collections.emptyList()); - - Map body = new HashMap<>(); - body.put("provider", "FEISHU"); - body.put("enabled", true); - body.put("values", Collections.singletonMap("appSecret", "new-secret-value")); - service.update(body); - - SysIntegrationConfig saved = argumentCaptorValue("appSecret"); - assertTrue(saved.getConfigValue().startsWith(IntegrationConfigCrypto.PREFIX)); - assertFalse(saved.getConfigValue().contains("new-secret-value")); - assertEquals("new-secret-value", crypto.decrypt(saved.getConfigValue())); - - when(repository.findByProviderOrderByConfigKeyAsc("FEISHU")) - .thenReturn(Collections.singletonList(saved)); - Map view = service.view(); - @SuppressWarnings("unchecked") Map feishu = (Map) view.get("feishu"); - @SuppressWarnings("unchecked") List> fields = (List>) feishu.get("fields"); - Map secretField = fields.stream().filter(x -> "appSecret".equals(x.get("key"))).findFirst().get(); - assertTrue(Boolean.TRUE.equals(secretField.get("configured"))); - assertFalse(String.valueOf(secretField.get("value")).contains("new-secret-value")); - } - - @Test - void missingKeyRejectsSecretBeforeWritingAnything() { - Map body = new HashMap<>(); - body.put("provider", "FEISHU"); - body.put("enabled", true); - body.put("values", Collections.singletonMap("appSecret", "must-not-be-plain")); - - assertThrows(com.finance.system.exception.BadRequestException.class, () -> service.update(body)); - verify(repository, never()).save(any(SysIntegrationConfig.class)); - } - - private SysIntegrationConfig argumentCaptorValue(String key) { - return (SysIntegrationConfig) mockingDetails(repository).getInvocations().stream() - .filter(invocation -> "save".equals(invocation.getMethod().getName())) - .map(invocation -> invocation.getArguments()[0]) - .filter(value -> value instanceof SysIntegrationConfig - && key.equals(((SysIntegrationConfig) value).getConfigKey())) - .findFirst().orElseThrow(() -> new AssertionError("missing saved config")); - } - - @Test - void unknownConfigurationKeyIsRejected() { - Map body = new HashMap<>(); body.put("provider", "FEISHU"); body.put("enabled", true); - body.put("values", Collections.singletonMap("arbitrary.property", "x")); - assertThrows(RuntimeException.class, () -> service.update(body)); - verify(repository, never()).save(any()); - } - - @Test - void disabledProviderIsPersistedEvenWhenThereAreNoExistingFields() { - when(repository.findByProviderAndConfigKey("FEISHU", IntegrationConfigReader.INTERNAL_ENABLED_KEY)) - .thenReturn(Optional.empty()); - when(repository.findByProviderOrderByConfigKeyAsc("FEISHU")) - .thenReturn(Collections.emptyList()); - Map body = new HashMap<>(); body.put("provider", "FEISHU"); body.put("enabled", false); - body.put("values", Collections.emptyMap()); - - service.update(body); - - verify(repository).save(argThat(value -> IntegrationConfigReader.INTERNAL_ENABLED_KEY.equals(value.getConfigKey()) - && "false".equals(value.getConfigValue()) && Boolean.FALSE.equals(value.getEnabled()))); - } - - @Test - void kingdeeEndpointRequiresAllowListedHttpsHost() { - service.setKingdeeAllowedHosts("app.kingdee.com"); - - assertDoesNotThrow(() -> service.validateKingdeeBaseUrl("https://app.kingdee.com/")); - assertThrows(RuntimeException.class, - () -> service.validateKingdeeBaseUrl("http://app.kingdee.com/")); - assertThrows(RuntimeException.class, - () -> service.validateKingdeeBaseUrl("https://localhost/")); - assertThrows(RuntimeException.class, - () -> service.validateKingdeeBaseUrl("https://127.0.0.1/")); - assertThrows(RuntimeException.class, - () -> service.validateKingdeeBaseUrl("https://evil.example/")); - } -} diff --git a/src/test/java/com/finance/system/service/RoleServiceTest.java b/src/test/java/com/finance/system/service/RoleServiceTest.java deleted file mode 100644 index 6faf5c3..0000000 --- a/src/test/java/com/finance/system/service/RoleServiceTest.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.finance.system.service; - -import com.finance.system.entity.*; -import com.finance.system.repository.*; -import org.junit.jupiter.api.Test; -import org.mockito.InOrder; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -class RoleServiceTest { - private final SysRoleRepository roles = mock(SysRoleRepository.class); - private final SysPermissionRepository permissions = mock(SysPermissionRepository.class); - private final SysRolePermissionRepository rolePermissions = mock(SysRolePermissionRepository.class); - private final SysUserRoleRepository userRoles = mock(SysUserRoleRepository.class); - private final SysUserRepository users = mock(SysUserRepository.class); - private final SysUserGroupRepository groups = mock(SysUserGroupRepository.class); - private final SysUserGroupMemberRepository members = mock(SysUserGroupMemberRepository.class); - private final SysUserGroupRoleRepository groupRoles = mock(SysUserGroupRoleRepository.class); - private final JdbcTemplate jdbc = mock(JdbcTemplate.class); - private final RoleService service = new RoleService(roles, permissions, rolePermissions, userRoles, users, groups, members, groupRoles); - private final com.finance.system.adapter.feishu.FeishuDirectoryAccessService directory = mock(com.finance.system.adapter.feishu.FeishuDirectoryAccessService.class); - @org.junit.jupiter.api.BeforeEach - void directoryPolicy() { - org.springframework.test.util.ReflectionTestUtils.setField(service, "directoryAccess", directory); - org.springframework.test.util.ReflectionTestUtils.setField(service, "jdbc", jdbc); - when(jdbc.queryForMap(anyString())).thenReturn(Collections.emptyMap()); - } - - @Test - void staleMemberCannotBeAddedButCanBeRemoved() { - when(groups.findById(9L)).thenReturn(Optional.of(SysUserGroup.builder().id(9L).status("ACTIVE").build())); - SysUser user = SysUser.builder().id(7L).build(); when(users.findById(7L)).thenReturn(Optional.of(user)); - doThrow(new com.finance.system.exception.BusinessException("Ineligible", 403)).when(directory).requireSynced(user); - assertThrows(com.finance.system.exception.BusinessException.class, () -> service.replaceGroupMembers(9L, Collections.singletonList(7L))); - verify(members, never()).deleteByIdGroupId(anyLong()); - when(members.findByIdGroupId(9L)).thenReturn(Collections.singletonList(new SysUserGroupMember(9L, 7L))); - service.replaceGroupMembers(9L, Collections.emptyList()); - verify(members).deleteByIdGroupId(9L); - } - - @Test - void userWithoutConfiguredRoleUsesEmployeeDefaults() { - SysUser user = SysUser.builder().id(7L).realName("普通用户").userType(null).build(); - when(users.findById(7L)).thenReturn(Optional.of(user)); - when(userRoles.findByIdUserId(7L)).thenReturn(Collections.emptyList()); - when(members.findByIdUserId(7L)).thenReturn(Collections.emptyList()); - when(groups.findAllById(any())).thenReturn(Collections.emptyList()); - when(roles.findByRoleCode("EMPLOYEE")).thenReturn(Optional.empty()); - - RoleService.ResolvedPermissions result = service.currentPermissions(7L); - - assertEquals(Collections.singleton("EMPLOYEE"), result.getRoleCodes()); - assertTrue(result.getPermissionCodes().contains("application:create")); - assertTrue(result.getPermissionCodes().contains("application:view-own")); - assertFalse(result.getPermissionCodes().contains("system:role:manage")); - } - - @Test - void directAndGroupRolesAreUnioned() { - SysUser user = SysUser.builder().id(7L).userType("EMPLOYEE").build(); - SysUserGroup group = SysUserGroup.builder().id(9L).status("ACTIVE").build(); - SysRole direct = SysRole.builder().id(2L).roleCode("DIRECT").status("ACTIVE").build(); - SysRole groupRole = SysRole.builder().id(3L).roleCode("GROUP_ROLE").status("ACTIVE").build(); - SysPermission directPermission = SysPermission.builder().id(11L).permissionCode("direct:read").permissionType("BUTTON").build(); - SysPermission groupPermission = SysPermission.builder().id(12L).permissionCode("group:edit").permissionType("BUTTON").build(); - when(users.findById(7L)).thenReturn(Optional.of(user)); - when(userRoles.findByIdUserId(7L)).thenReturn(Collections.singletonList(new SysUserRole(7L, 2L))); - when(members.findByIdUserId(7L)).thenReturn(Collections.singletonList(new SysUserGroupMember(9L, 7L))); - when(groups.findAllById(any())).thenReturn(Collections.singletonList(group)); - when(groupRoles.findByIdGroupId(9L)).thenReturn(Collections.singletonList(new SysUserGroupRole(9L, 3L))); - when(roles.findAllById(any())).thenReturn(Arrays.asList(direct, groupRole)); - when(rolePermissions.findByIdRoleIdIn(any())).thenReturn(Arrays.asList( - new SysRolePermission(2L, 11L, "READ"), new SysRolePermission(3L, 12L, "EDIT"))); - when(permissions.findAllById(any())).thenReturn(Arrays.asList(directPermission, groupPermission)); - - RoleService.ResolvedPermissions result = service.currentPermissions(7L); - - assertEquals(new LinkedHashSet<>(Arrays.asList("DIRECT", "GROUP_ROLE")), result.getRoleCodes()); - assertTrue(result.getPermissionCodes().contains("direct:read")); - assertTrue(result.getPermissionCodes().contains("group:edit")); - } - - @Test - void rolePermissionReplacementIsReadBackWithFieldAccess() { - SysRole role = SysRole.builder().id(4L).roleCode("CUSTOM").status("ACTIVE").build(); - SysPermission button = SysPermission.builder().id(21L).permissionCode("custom:edit").permissionType("BUTTON").build(); - SysPermission field = SysPermission.builder().id(22L).permissionCode("custom:amount").permissionType("FIELD").build(); - when(roles.findById(4L)).thenReturn(Optional.of(role)); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("SUPER_ADMIN").build())); - when(permissions.findAll()).thenReturn(Arrays.asList(button, field)); - Map request = new HashMap<>(); - request.put("permissionCodes", Collections.singletonList("custom:edit")); - request.put("fieldPermissions", Collections.singletonMap("custom:amount", "READ")); - - service.replaceRolePermissions(4L, request, 1L); - verify(rolePermissions).deleteByIdRoleId(4L); - verify(rolePermissions).saveAll(any()); - - when(rolePermissions.findByIdRoleId(4L)).thenReturn(Arrays.asList( - new SysRolePermission(4L, 21L, "READ"), new SysRolePermission(4L, 22L, "READ"))); - when(permissions.findAllById(any())).thenReturn(Arrays.asList(button, field)); - Map result = service.rolePermissions(4L); - assertEquals(Collections.singletonList("custom:edit"), result.get("permissionCodes")); - assertEquals(Collections.singletonMap("custom:amount", "READ"), result.get("fieldPermissions")); - } - - @Test - void duplicateGroupMembersAreCollapsedBeforePersistence() { - when(groups.findById(9L)).thenReturn(Optional.of(SysUserGroup.builder().id(9L).status("ACTIVE").build())); - when(users.findById(7L)).thenReturn(Optional.of(SysUser.builder().id(7L).build())); - when(users.findById(8L)).thenReturn(Optional.of(SysUser.builder().id(8L).build())); - - service.replaceGroupMembers(9L, Arrays.asList(7L, 7L, 8L)); - - verify(members).deleteByIdGroupId(9L); - verify(members, times(2)).save(any(SysUserGroupMember.class)); - } - - @Test - void directoryStateIsLockedBeforeValidationAndMemberReplacement() { - when(groups.findById(9L)).thenReturn(Optional.of(SysUserGroup.builder().id(9L).status("ACTIVE").build())); - SysUser user = SysUser.builder().id(7L).build(); - when(users.findById(7L)).thenReturn(Optional.of(user)); - - service.replaceGroupMembers(9L, Collections.singletonList(7L)); - - InOrder order = inOrder(jdbc, directory, members); - order.verify(jdbc).queryForMap("SELECT * FROM feishu_directory_state WHERE id=1 FOR UPDATE"); - order.verify(directory).requireSynced(user); - order.verify(members).deleteByIdGroupId(9L); - order.verify(members).save(any(SysUserGroupMember.class)); - } - - @Test - void clearingRolesPersistsEmployeeCompatibilityFallback() { - SysUser user = SysUser.builder().id(7L).userType("ADMIN").build(); - when(users.findById(7L)).thenReturn(Optional.of(user)); - - service.replaceUserRoles(7L, Collections.emptyList()); - - assertEquals("EMPLOYEE", user.getUserType()); - verify(userRoles).deleteByIdUserId(7L); - verify(users).save(user); - } - - @Test - void ordinaryUserManagerCannotAssignAdministratorRole() { - SysRole admin = SysRole.builder().id(90L).roleCode("ADMIN").status("ACTIVE").build(); - when(users.findById(2L)).thenReturn(Optional.of(SysUser.builder().id(2L).userType("EMPLOYEE").build())); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - when(roles.findById(90L)).thenReturn(Optional.of(admin)); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceUserRoles(2L, Collections.singletonList(90L), 1L)); - verify(userRoles, never()).deleteByIdUserId(2L); - } - - @Test - void superAdminCannotAssignPrivilegedRoleToItself() { - SysRole admin = SysRole.builder().id(90L).roleCode("ADMIN").status("ACTIVE").build(); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("SUPER_ADMIN").status("ACTIVE").build())); - when(roles.findById(90L)).thenReturn(Optional.of(admin)); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceUserRoles(1L, Collections.singletonList(90L), 1L)); - verify(userRoles, never()).deleteByIdUserId(1L); - } - - @Test - void ordinaryUserManagerCannotBindAdministratorRoleToGroup() { - SysRole admin = SysRole.builder().id(90L).roleCode("ADMIN").status("ACTIVE").build(); - when(groups.findById(3L)).thenReturn(Optional.of(SysUserGroup.builder().id(3L).status("ACTIVE").build())); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - when(roles.findById(90L)).thenReturn(Optional.of(admin)); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceGroupRoles(3L, Collections.singletonList(90L), 1L)); - verify(groupRoles, never()).deleteByIdGroupId(3L); - } - - @Test - void ordinaryManagerCannotChangeBuiltInRolePermissions() { - SysRole builtIn = SysRole.builder().id(10L).roleCode("FINANCE").builtIn(true).status("ACTIVE").build(); - when(roles.findById(10L)).thenReturn(Optional.of(builtIn)); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("ADMIN").build())); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceRolePermissions(10L, Collections.emptyMap(), 1L)); - verify(rolePermissions, never()).deleteByIdRoleId(10L); - } - - @Test - void ordinaryManagerCannotGrantHighRiskPermissionOrFieldEdit() { - SysRole role = SysRole.builder().id(11L).roleCode("CUSTOM").builtIn(false).status("ACTIVE").build(); - SysPermission highRisk = SysPermission.builder().id(31L).permissionCode("payment:register") - .permissionType("BUTTON").build(); - SysPermission field = SysPermission.builder().id(32L).permissionCode("application:amount") - .permissionType("FIELD").build(); - when(roles.findById(11L)).thenReturn(Optional.of(role)); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - when(users.findById(2L)).thenReturn(Optional.of(SysUser.builder().id(2L).userType("EMPLOYEE").build())); - when(userRoles.findByIdUserId(1L)).thenReturn(Collections.singletonList(new SysUserRole(1L, 20L))); - when(members.findByIdUserId(1L)).thenReturn(Collections.emptyList()); - when(groups.findAllById(any())).thenReturn(Collections.emptyList()); - when(roles.findAllById(any())).thenReturn(Collections.singletonList( - SysRole.builder().id(20L).roleCode("ROLE_MANAGER").status("ACTIVE").build())); - when(rolePermissions.findByIdRoleIdIn(any())).thenReturn(Collections.singletonList( - new SysRolePermission(20L, 33L, "READ"))); - when(permissions.findAllById(any())).thenReturn(Collections.singletonList( - SysPermission.builder().id(33L).permissionCode("system:role:manage").permissionType("BUTTON").build())); - when(permissions.findAll()).thenReturn(Arrays.asList(highRisk, field)); - - Map request = new HashMap<>(); - request.put("permissionCodes", Collections.singletonList("payment:register")); - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceRolePermissions(11L, request, 1L)); - request.clear(); - request.put("fieldPermissions", Collections.singletonMap("application:amount", "EDIT")); - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceRolePermissions(11L, request, 1L)); - verify(rolePermissions, never()).deleteByIdRoleId(11L); - } - - @Test - void ordinaryManagerCannotAddMembersToPrivilegedGroup() { - SysRole admin = SysRole.builder().id(90L).roleCode("ADMIN").status("ACTIVE").build(); - when(groups.findById(3L)).thenReturn(Optional.of(SysUserGroup.builder().id(3L).status("ACTIVE").build())); - when(groupRoles.findByIdGroupId(3L)).thenReturn(Collections.singletonList(new SysUserGroupRole(3L, 90L))); - when(roles.findById(90L)).thenReturn(Optional.of(admin)); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceGroupMembers(3L, Collections.singletonList(1L), 1L)); - verify(members, never()).deleteByIdGroupId(3L); - } - - @Test - void ordinaryUserManagerCannotAssignHighRiskCustomRoleToItself() { - SysRole manager = SysRole.builder().id(20L).roleCode("USER_MANAGER").status("ACTIVE").build(); - SysRole highRiskRole = SysRole.builder().id(30L).roleCode("PAYMENT_ADMIN").status("ACTIVE").build(); - SysPermission manageUsers = SysPermission.builder().id(33L) - .permissionCode("system:user:manage").permissionType("BUTTON").build(); - SysPermission payment = SysPermission.builder().id(34L) - .permissionCode("payment:register").permissionType("BUTTON").build(); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - when(roles.findAllById(any())).thenReturn(Collections.singletonList(manager)); - when(userRoles.findByIdUserId(1L)).thenReturn(Collections.singletonList(new SysUserRole(1L, 20L))); - when(members.findByIdUserId(1L)).thenReturn(Collections.emptyList()); - when(groups.findAllById(any())).thenReturn(Collections.emptyList()); - when(rolePermissions.findByIdRoleIdIn(any())).thenReturn( - Collections.singletonList(new SysRolePermission(20L, 33L, "EDIT"))); - when(permissions.findAllById(any())).thenReturn(Arrays.asList(manageUsers, payment)); - when(users.findById(2L)).thenReturn(Optional.of(SysUser.builder().id(2L).userType("EMPLOYEE").build())); - when(roles.findById(30L)).thenReturn(Optional.of(highRiskRole)); - when(rolePermissions.findByIdRoleId(30L)).thenReturn( - Collections.singletonList(new SysRolePermission(30L, 34L, "READ"))); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceUserRoles(2L, Collections.singletonList(30L), 1L)); - verify(userRoles, never()).deleteByIdUserId(2L); - } - - @Test - void ordinaryUserManagerCannotAssignHighRiskCustomRoleToGroup() { - SysRole manager = SysRole.builder().id(20L).roleCode("USER_MANAGER").status("ACTIVE").build(); - SysRole highRiskRole = SysRole.builder().id(30L).roleCode("PAYMENT_ADMIN").status("ACTIVE").build(); - SysPermission manageUsers = SysPermission.builder().id(33L) - .permissionCode("system:user:manage").permissionType("BUTTON").build(); - SysPermission payment = SysPermission.builder().id(34L) - .permissionCode("payment:register").permissionType("BUTTON").build(); - when(groups.findById(3L)).thenReturn(Optional.of(SysUserGroup.builder().id(3L).status("ACTIVE").build())); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - when(roles.findAllById(any())).thenReturn(Collections.singletonList(manager)); - when(userRoles.findByIdUserId(1L)).thenReturn(Collections.singletonList(new SysUserRole(1L, 20L))); - when(members.findByIdUserId(1L)).thenReturn(Collections.emptyList()); - when(groups.findAllById(any())).thenReturn(Collections.emptyList()); - when(rolePermissions.findByIdRoleIdIn(any())).thenReturn( - Collections.singletonList(new SysRolePermission(20L, 33L, "EDIT"))); - when(permissions.findAllById(any())).thenReturn(Arrays.asList(manageUsers, payment)); - when(roles.findById(30L)).thenReturn(Optional.of(highRiskRole)); - when(rolePermissions.findByIdRoleId(30L)).thenReturn( - Collections.singletonList(new SysRolePermission(30L, 34L, "READ"))); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceGroupRoles(3L, Collections.singletonList(30L), 1L)); - verify(groupRoles, never()).deleteByIdGroupId(3L); - } - - @Test - void ordinaryUserManagerCannotAddMemberToGroupWithHighRiskCustomRole() { - SysRole manager = SysRole.builder().id(20L).roleCode("USER_MANAGER").status("ACTIVE").build(); - SysRole highRiskRole = SysRole.builder().id(30L).roleCode("PAYMENT_ADMIN").status("ACTIVE").build(); - SysPermission manageUsers = SysPermission.builder().id(33L) - .permissionCode("system:user:manage").permissionType("BUTTON").build(); - SysPermission payment = SysPermission.builder().id(34L) - .permissionCode("payment:register").permissionType("BUTTON").build(); - when(groups.findById(3L)).thenReturn(Optional.of(SysUserGroup.builder().id(3L).status("ACTIVE").build())); - when(groupRoles.findByIdGroupId(3L)).thenReturn( - Collections.singletonList(new SysUserGroupRole(3L, 30L))); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).userType("EMPLOYEE").build())); - when(roles.findAllById(any())).thenReturn(Collections.singletonList(manager)); - when(userRoles.findByIdUserId(1L)).thenReturn(Collections.singletonList(new SysUserRole(1L, 20L))); - when(members.findByIdUserId(1L)).thenReturn(Collections.emptyList()); - when(groups.findAllById(any())).thenReturn(Collections.emptyList()); - when(rolePermissions.findByIdRoleIdIn(any())).thenReturn( - Collections.singletonList(new SysRolePermission(20L, 33L, "EDIT"))); - when(permissions.findAllById(any())).thenReturn(Arrays.asList(manageUsers, payment)); - when(roles.findById(30L)).thenReturn(Optional.of(highRiskRole)); - when(rolePermissions.findByIdRoleId(30L)).thenReturn( - Collections.singletonList(new SysRolePermission(30L, 34L, "READ"))); - - assertThrows(com.finance.system.exception.BusinessException.class, - () -> service.replaceGroupMembers(3L, Collections.singletonList(2L), 1L)); - verify(members, never()).deleteByIdGroupId(3L); - } -} diff --git a/src/test/java/com/finance/system/service/impl/ApprovalSecurityTest.java b/src/test/java/com/finance/system/service/impl/ApprovalSecurityTest.java deleted file mode 100644 index 07dc0bf..0000000 --- a/src/test/java/com/finance/system/service/impl/ApprovalSecurityTest.java +++ /dev/null @@ -1,284 +0,0 @@ -package com.finance.system.service.impl; - -import com.finance.system.adapter.kingdee.KingdeeConfig; -import com.finance.system.entity.ReimApplication; -import com.finance.system.entity.ReimExpenseItem; -import com.finance.system.entity.SysApprovalNode; -import com.finance.system.entity.SysBankAccount; -import com.finance.system.entity.SysUser; -import com.finance.system.enums.ApplicationStatus; -import com.finance.system.enums.ApprovalStatus; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.ReimApprovalRecordRepository; -import com.finance.system.repository.ReimApplicationRepository; -import com.finance.system.repository.ReimAttachmentRepository; -import com.finance.system.repository.ReimExpenseItemRepository; -import com.finance.system.repository.ReimInvoiceRepository; -import com.finance.system.repository.ReimPaymentRepository; -import com.finance.system.repository.SysApprovalNodeRepository; -import com.finance.system.repository.SysBankAccountRepository; -import com.finance.system.repository.SysDepartmentRepository; -import com.finance.system.repository.SysExpenseTypeRepository; -import com.finance.system.repository.SysUserRepository; -import com.finance.system.security.UserPrincipal; -import com.finance.system.service.RoleService; -import com.finance.system.dto.CreateApplicationRequest; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; - -import java.math.BigDecimal; -import java.util.Collections; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class ApprovalSecurityTest { - - @Test - void roleMappingUsesTheConfiguredPosition() { - assertTrue(ApprovalRoutingRules.matchesRole( - activeUser(1L, "FINANCE", "应付会计"), "ACCOUNTS_PAYABLE")); - assertTrue(ApprovalRoutingRules.matchesRole( - activeUser(2L, "FINANCE", "财务经理"), "FINANCE_MANAGER")); - assertTrue(ApprovalRoutingRules.matchesRole( - activeUser(3L, "FINANCE", "出纳"), "CASHIER")); - assertFalse(ApprovalRoutingRules.matchesRole( - activeUser(4L, "FINANCE", "财务专员"), "UNKNOWN")); - assertFalse(ApprovalRoutingRules.isApprovalNode(SysApprovalNode.builder() - .status("ACTIVE").approverType("FIXED").approverRole(null).build())); - } - - @AfterEach - void clearSecurityContext() { - SecurityContextHolder.clearContext(); - } - - @Test - void submitRejectsApplicationsWhenNoApprovalNodeExists() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - SysBankAccountRepository banks = mock(SysBankAccountRepository.class); - SysApprovalNodeRepository nodes = mock(SysApprovalNodeRepository.class); - ReimApplication app = draftApplication(); - when(applications.findByIdForUpdate(1L)).thenReturn(Optional.of(app)); - when(items.findByApplicationId(1L)).thenReturn(Collections.singletonList( - ReimExpenseItem.builder().amount(new BigDecimal("10.00")).build())); - when(banks.findById(2L)).thenReturn(Optional.of(SysBankAccount.builder().id(2L).userId(1L).build())); - when(nodes.findAllByOrderBySortOrder()).thenReturn(Collections.emptyList()); - asEmployee(1L); - - ReimApplicationServiceImpl service = applicationService(applications, users, items, banks, nodes); - - assertThrows(BusinessException.class, () -> service.submitApplication(1L)); - verify(applications, never()).save(any(ReimApplication.class)); - } - - @Test - void submitRejectsInactiveExplicitApprover() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - SysBankAccountRepository banks = mock(SysBankAccountRepository.class); - SysApprovalNodeRepository nodes = mock(SysApprovalNodeRepository.class); - when(applications.findByIdForUpdate(1L)).thenReturn(Optional.of(draftApplication())); - when(items.findByApplicationId(1L)).thenReturn(Collections.singletonList( - ReimExpenseItem.builder().amount(new BigDecimal("10.00")).build())); - when(banks.findById(2L)).thenReturn(Optional.of(SysBankAccount.builder().id(2L).userId(1L).build())); - when(nodes.findAllByOrderBySortOrder()).thenReturn(Collections.singletonList( - SysApprovalNode.builder().status("ACTIVE").approverId(9L).build())); - when(users.findById(9L)).thenReturn(Optional.of(SysUser.builder().id(9L).status("INACTIVE").build())); - asEmployee(1L); - - ReimApplicationServiceImpl service = applicationService(applications, users, items, banks, nodes); - - assertThrows(BusinessException.class, () -> service.submitApplication(1L)); - verify(applications, never()).save(any(ReimApplication.class)); - } - - @Test - void submitRejectsUnknownRoleAndRoleWithoutMatchingApprover() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - SysBankAccountRepository banks = mock(SysBankAccountRepository.class); - SysApprovalNodeRepository nodes = mock(SysApprovalNodeRepository.class); - when(applications.findByIdForUpdate(1L)).thenReturn(Optional.of(draftApplication())); - when(items.findByApplicationId(1L)).thenReturn(Collections.singletonList( - ReimExpenseItem.builder().amount(new BigDecimal("10.00")).build())); - when(banks.findById(2L)).thenReturn(Optional.of(SysBankAccount.builder().id(2L).userId(1L).build())); - when(nodes.findAllByOrderBySortOrder()).thenReturn(Collections.singletonList( - SysApprovalNode.builder().status("ACTIVE").approverRole("CASHIER").build())); - when(users.findByUserType("FINANCE")).thenReturn(Collections.singletonList( - activeUser(9L, "FINANCE", "财务专员"))); - asEmployee(1L); - - ReimApplicationServiceImpl service = applicationService(applications, users, items, banks, nodes); - - assertThrows(BusinessException.class, () -> service.submitApplication(1L)); - verify(applications, never()).save(any(ReimApplication.class)); - - when(nodes.findAllByOrderBySortOrder()).thenReturn(Collections.singletonList( - SysApprovalNode.builder().status("ACTIVE").approverRole("NOT_A_ROLE").build())); - assertThrows(BusinessException.class, () -> service.submitApplication(1L)); - } - - @Test - void approvalRejectsMissingCurrentApprover() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimApplication app = ReimApplication.builder() - .id(1L).applicationStatus(ApplicationStatus.SUBMITTED.name()) - .approvalStatus(ApprovalStatus.PENDING.name()).currentApproverId(null).build(); - when(applications.findByIdForUpdate(1L)).thenReturn(Optional.of(app)); - when(users.findById(5L)).thenReturn(Optional.of(activeUser(5L, "FINANCE"))); - asFinance(5L); - - ReimApprovalServiceImpl service = approvalService(applications, users); - - assertThrows(BusinessException.class, () -> service.approve(1L, 5L, "ok")); - } - - @Test - void approvalRejectsMissingOrInactiveCurrentApprover() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimApplication app = ReimApplication.builder() - .id(1L).applicationStatus(ApplicationStatus.SUBMITTED.name()) - .approvalStatus(ApprovalStatus.PENDING.name()).currentApproverId(9L).build(); - when(applications.findByIdForUpdate(1L)).thenReturn(Optional.of(app)); - when(users.findById(5L)).thenReturn(Optional.of(activeUser(5L, "FINANCE"))); - when(users.findById(9L)).thenReturn(Optional.empty()); - asFinance(5L); - - ReimApprovalServiceImpl service = approvalService(applications, users); - - assertThrows(BusinessException.class, () -> service.approve(1L, 5L, "ok")); - } - - @Test - void readOnlyApplicationFieldCannotBeChangedOnUpdate() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimApplication app = ReimApplication.builder().id(1L).applicantId(1L) - .totalAmount(new BigDecimal("10.00")).payeeName("原收款人") - .applicationStatus(ApplicationStatus.DRAFT.name()).build(); - when(applications.findById(1L)).thenReturn(Optional.of(app)); - RoleService roles = mock(RoleService.class); - when(roles.hasPermission(1L, "reimbursement:create")).thenReturn(true); - when(roles.hasPermission(1L, "application:create")).thenReturn(false); - when(roles.fieldAccess(1L, "application:amount")).thenReturn("READ"); - ReimApplicationServiceImpl service = applicationService(applications, users, - mock(ReimExpenseItemRepository.class), mock(SysBankAccountRepository.class), - mock(SysApprovalNodeRepository.class)); - service.setRoleService(roles); - CreateApplicationRequest request = new CreateApplicationRequest(); - request.setTotalAmount(new BigDecimal("11.00")); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service.updateApplication(1L, request, 1L)); - - assertTrue(exception.getStatusCode() == 403); - verify(applications, never()).save(any(ReimApplication.class)); - } - - @Test - void hiddenPayeeFieldCannotBeChangedOnUpdate() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - ReimApplication app = ReimApplication.builder().id(1L).applicantId(1L) - .totalAmount(new BigDecimal("10.00")).payeeName("原收款人") - .applicationStatus(ApplicationStatus.DRAFT.name()).build(); - when(applications.findById(1L)).thenReturn(Optional.of(app)); - RoleService roles = mock(RoleService.class); - when(roles.hasPermission(1L, "reimbursement:create")).thenReturn(true); - when(roles.fieldAccess(1L, "application:amount")).thenReturn("EDIT"); - when(roles.fieldAccess(1L, "application:payeeName")).thenReturn("HIDDEN"); - ReimApplicationServiceImpl service = applicationService(applications, users, - mock(ReimExpenseItemRepository.class), mock(SysBankAccountRepository.class), - mock(SysApprovalNodeRepository.class)); - service.setRoleService(roles); - CreateApplicationRequest request = new CreateApplicationRequest(); - request.setTotalAmount(new BigDecimal("10.00")); - request.setPayeeName("攻击者收款人"); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service.updateApplication(1L, request, 1L)); - - assertTrue(exception.getStatusCode() == 403); - verify(applications, never()).save(any(ReimApplication.class)); - } - - @Test - void createReportsMissingEditableFieldClearly() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - when(users.findById(1L)).thenReturn(Optional.of(SysUser.builder().id(1L).departmentId(10L).build())); - RoleService roles = mock(RoleService.class); - when(roles.hasPermission(1L, "reimbursement:create")).thenReturn(true); - when(roles.fieldAccess(1L, "application:amount")).thenReturn("EDIT"); - ReimApplicationServiceImpl service = applicationService(applications, users, - mock(ReimExpenseItemRepository.class), mock(SysBankAccountRepository.class), - mock(SysApprovalNodeRepository.class)); - service.setRoleService(roles); - - BusinessException exception = assertThrows(BusinessException.class, - () -> service.createApplication(new CreateApplicationRequest(), 1L)); - - assertTrue(exception.getStatusCode() == 400); - verify(applications, never()).save(any(ReimApplication.class)); - } - - private ReimApplication draftApplication() { - return ReimApplication.builder().id(1L).applicantId(1L) - .totalAmount(new BigDecimal("10.00")).payeeBankId(2L) - .applicationStatus(ApplicationStatus.DRAFT.name()).build(); - } - - private ReimApplicationServiceImpl applicationService(ReimApplicationRepository applications, - SysUserRepository users, - ReimExpenseItemRepository items, - SysBankAccountRepository banks, - SysApprovalNodeRepository nodes) { - return new ReimApplicationServiceImpl(applications, users, - mock(SysDepartmentRepository.class), mock(SysExpenseTypeRepository.class), banks, items, - mock(ReimInvoiceRepository.class), mock(ReimAttachmentRepository.class), - mock(ReimApprovalRecordRepository.class), mock(ReimPaymentRepository.class), nodes, - mock(KingdeeConfig.class)); - } - - private ReimApprovalServiceImpl approvalService(ReimApplicationRepository applications, - SysUserRepository users) { - return new ReimApprovalServiceImpl(applications, mock(ReimApprovalRecordRepository.class), users, - mock(SysApprovalNodeRepository.class)); - } - - private SysUser activeUser(Long id, String type) { - return activeUser(id, type, null); - } - - private SysUser activeUser(Long id, String type, String position) { - return SysUser.builder().id(id).status("ACTIVE").userType(type).position(position).build(); - } - - private void asEmployee(Long id) { - UserPrincipal principal = UserPrincipal.builder().id(id).userType("EMPLOYEE").build(); - SecurityContextHolder.getContext().setAuthentication( - new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities())); - } - - private void asFinance(Long id) { - UserPrincipal principal = UserPrincipal.builder().id(id).userType("FINANCE").build(); - SecurityContextHolder.getContext().setAuthentication( - new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities())); - } -} diff --git a/src/test/java/com/finance/system/service/impl/DashboardServiceTest.java b/src/test/java/com/finance/system/service/impl/DashboardServiceTest.java deleted file mode 100644 index 2303d51..0000000 --- a/src/test/java/com/finance/system/service/impl/DashboardServiceTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.finance.system.service.impl; - -import com.finance.system.entity.ReimApplication; -import com.finance.system.entity.SysUser; -import com.finance.system.repository.*; -import com.finance.system.service.RoleService; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - -class DashboardServiceTest { - @Test - void effectiveViewAllPermissionUsesFullStatisticsForCustomRole() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - DashboardServiceImpl service = new DashboardServiceImpl(applications, users, - mock(SysDepartmentRepository.class), mock(SysExpenseTypeRepository.class)); - RoleService roles = mock(RoleService.class); - service.setRoleService(roles); - - SysUser user = SysUser.builder().id(7L).userType("EMPLOYEE").build(); - ReimApplication first = ReimApplication.builder().id(1L).totalAmount(new java.math.BigDecimal("10.00")) - .approvalStatus("APPROVED").build(); - ReimApplication second = ReimApplication.builder().id(2L).totalAmount(new java.math.BigDecimal("20.00")) - .approvalStatus("PENDING").build(); - when(users.findById(7L)).thenReturn(java.util.Optional.of(user)); - when(roles.hasPermission(7L, "reimbursement:view-all")).thenReturn(true); - when(applications.findAll()).thenReturn(Arrays.asList(first, second)); - - assertEquals(2L, service.getDashboardStats(7L).getTotalApplications()); - verify(applications).findAll(); - verify(applications, never()).findByApplicantIdOrderByCreatedAtDesc(7L); - } - - @Test - void effectiveOwnPermissionDoesNotUseUserTypeAsFullAccess() { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - DashboardServiceImpl service = new DashboardServiceImpl(applications, users, - mock(SysDepartmentRepository.class), mock(SysExpenseTypeRepository.class)); - RoleService roles = mock(RoleService.class); - service.setRoleService(roles); - when(users.findById(7L)).thenReturn(java.util.Optional.of(SysUser.builder().id(7L).userType("FINANCE").build())); - when(roles.hasPermission(anyLong(), anyString())).thenReturn(false); - when(applications.findByApplicantIdOrderByCreatedAtDesc(7L)).thenReturn(Collections.emptyList()); - - assertEquals(0L, service.getDashboardStats(7L).getTotalApplications()); - verify(applications).findByApplicantIdOrderByCreatedAtDesc(7L); - verify(applications, never()).findAll(); - } -} diff --git a/src/test/java/com/finance/system/service/impl/ReimApplicationFeishuSubmissionTest.java b/src/test/java/com/finance/system/service/impl/ReimApplicationFeishuSubmissionTest.java deleted file mode 100644 index 26ad48e..0000000 --- a/src/test/java/com/finance/system/service/impl/ReimApplicationFeishuSubmissionTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.finance.system.service.impl; - -import com.finance.system.adapter.feishu.FeishuApprovalService; -import com.finance.system.adapter.kingdee.KingdeeConfig; -import com.finance.system.entity.*; -import com.finance.system.enums.ApplicationStatus; -import com.finance.system.enums.ApprovalStatus; -import com.finance.system.repository.*; -import com.finance.system.service.RoleService; -import org.junit.jupiter.api.Test; - -import java.math.BigDecimal; -import java.util.Collections; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -class ReimApplicationFeishuSubmissionTest { - - @Test - void incompleteFeishuConfigurationKeepsLocalApprovalWorkflow() { - Fixture fixture = fixture(false); - SysApprovalNode node = SysApprovalNode.builder().nodeName("应付会计审核") - .approverType("ROLE").approverRole("ACCOUNTS_PAYABLE") - .status("ACTIVE").sortOrder(1).build(); - when(fixture.nodes.findAllByOrderBySortOrder()).thenReturn(Collections.singletonList(node)); - - fixture.service.submitApplication(1L, 1L); - - assertEquals(ApplicationStatus.SUBMITTED.name(), fixture.application.getApplicationStatus()); - assertEquals(ApprovalStatus.PENDING.name(), fixture.application.getApprovalStatus()); - assertEquals(2L, fixture.application.getCurrentApproverId()); - verify(fixture.feishu, never()).createApprovalInstance(any(ReimApplication.class)); - } - - @Test - void configuredFeishuApprovalIsCreatedAfterLocalSave() { - Fixture fixture = fixture(true); - - fixture.service.submitApplication(1L, 1L); - - assertEquals(ApplicationStatus.SUBMITTED.name(), fixture.application.getApplicationStatus()); - assertEquals(ApprovalStatus.PENDING.name(), fixture.application.getApprovalStatus()); - assertEquals("飞书审批", fixture.application.getCurrentApprovalNode()); - verify(fixture.applications).save(fixture.application); - verify(fixture.feishu).createApprovalInstance(fixture.application); - verifyNoInteractions(fixture.nodes); - } - - @Test - void cancelledApplicationCanBeSubmittedAgain() { - Fixture fixture = fixture(true); - fixture.application.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); - fixture.application.setApprovalStatus(ApprovalStatus.CANCELLED.name()); - - fixture.service.submitApplication(1L, 1L); - - assertEquals(ApplicationStatus.SUBMITTED.name(), fixture.application.getApplicationStatus()); - assertEquals(ApprovalStatus.PENDING.name(), fixture.application.getApprovalStatus()); - verify(fixture.feishu).createApprovalInstance(fixture.application); - } - - private Fixture fixture(boolean feishuEnabled) { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - SysDepartmentRepository departments = mock(SysDepartmentRepository.class); - SysExpenseTypeRepository expenseTypes = mock(SysExpenseTypeRepository.class); - SysBankAccountRepository banks = mock(SysBankAccountRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - ReimInvoiceRepository invoices = mock(ReimInvoiceRepository.class); - ReimAttachmentRepository attachments = mock(ReimAttachmentRepository.class); - ReimApprovalRecordRepository approvalRecords = mock(ReimApprovalRecordRepository.class); - ReimPaymentRepository payments = mock(ReimPaymentRepository.class); - SysApprovalNodeRepository nodes = mock(SysApprovalNodeRepository.class); - RoleService roles = mock(RoleService.class); - FeishuApprovalService feishu = mock(FeishuApprovalService.class); - - ReimApplication application = ReimApplication.builder().id(1L).applicationNo("REIM-1") - .title("travel").applicantId(1L).totalAmount(new BigDecimal("10.00")) - .payeeBankId(9L).applicationStatus(ApplicationStatus.DRAFT.name()) - .approvalStatus(ApprovalStatus.REJECTED.name()).build(); - ReimExpenseItem item = new ReimExpenseItem(); - item.setAmount(new BigDecimal("10.00")); - SysBankAccount bank = SysBankAccount.builder().id(9L).userId(1L) - .bankName("Bank").accountName("Employee").accountNo("123").build(); - SysUser applicant = SysUser.builder().id(1L).realName("Employee").status("ACTIVE").build(); - SysUser approver = SysUser.builder().id(2L).realName("AP").status("ACTIVE") - .position("AP").build(); - - when(applications.findByIdForUpdate(1L)).thenReturn(Optional.of(application)); - when(applications.save(any(ReimApplication.class))).thenAnswer(invocation -> invocation.getArgument(0)); - when(roles.hasPermission(1L, "reimbursement:create")).thenReturn(true); - when(roles.hasPermission(2L, "approval:view")).thenReturn(true); - when(feishu.isApprovalEnabledAndConfigured()).thenReturn(feishuEnabled); - when(items.findByApplicationId(1L)).thenReturn(Collections.singletonList(item)); - when(banks.findById(9L)).thenReturn(Optional.of(bank)); - when(users.findAll()).thenReturn(Collections.singletonList(approver)); - when(users.findById(1L)).thenReturn(Optional.of(applicant)); - when(users.findById(2L)).thenReturn(Optional.of(approver)); - stubEmptyDetails(invoices, attachments, approvalRecords, payments); - - ReimApplicationServiceImpl service = new ReimApplicationServiceImpl(applications, users, - departments, expenseTypes, banks, items, invoices, attachments, approvalRecords, - payments, nodes, mock(KingdeeConfig.class)); - service.setRoleService(roles); - service.setFeishuApprovalService(feishu); - return new Fixture(service, applications, nodes, feishu, application); - } - - private void stubEmptyDetails(ReimInvoiceRepository invoices, ReimAttachmentRepository attachments, - ReimApprovalRecordRepository records, ReimPaymentRepository payments) { - when(invoices.findByApplicationId(1L)).thenReturn(Collections.emptyList()); - when(attachments.findByApplicationId(1L)).thenReturn(Collections.emptyList()); - when(records.findByApplicationIdOrderByActionTimeAsc(1L)).thenReturn(Collections.emptyList()); - when(payments.findByApplicationId(1L)).thenReturn(Collections.emptyList()); - } - - private static class Fixture { - private final ReimApplicationServiceImpl service; - private final ReimApplicationRepository applications; - private final SysApprovalNodeRepository nodes; - private final FeishuApprovalService feishu; - private final ReimApplication application; - - private Fixture(ReimApplicationServiceImpl service, ReimApplicationRepository applications, - SysApprovalNodeRepository nodes, FeishuApprovalService feishu, - ReimApplication application) { - this.service = service; - this.applications = applications; - this.nodes = nodes; - this.feishu = feishu; - this.application = application; - } - } -} diff --git a/src/test/java/com/finance/system/service/impl/ReimPaymentServiceIdempotencyTest.java b/src/test/java/com/finance/system/service/impl/ReimPaymentServiceIdempotencyTest.java deleted file mode 100644 index 7f76433..0000000 --- a/src/test/java/com/finance/system/service/impl/ReimPaymentServiceIdempotencyTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.finance.system.service.impl; - -import com.finance.system.entity.ReimApplication; -import com.finance.system.entity.ReimPayment; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.*; -import com.finance.system.security.UserPrincipal; -import com.finance.system.service.RoleService; -import com.finance.system.service.PaymentIdempotencyLock; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.mockito.ArgumentCaptor; -import org.mockito.InOrder; - -import java.math.BigDecimal; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; - -class ReimPaymentServiceIdempotencyTest { - private final ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - private final ReimPaymentRepository payments = mock(ReimPaymentRepository.class); - private final RoleService roleService = mock(RoleService.class); - private final PaymentIdempotencyLock idempotencyLock = mock(PaymentIdempotencyLock.class); - private ReimPaymentServiceImpl service; - - @BeforeEach - void setUp() { - service = new ReimPaymentServiceImpl(applications, payments, - mock(ReimPaymentInstallmentRepository.class), mock(ReimApprovalRecordRepository.class), - mock(SysUserRepository.class), mock(SysBankAccountRepository.class), - mock(SysDepartmentRepository.class), idempotencyLock); - service.setRoleService(roleService); - when(roleService.hasPermission(7L, "payment:register")).thenReturn(true); - UserPrincipal principal = UserPrincipal.builder().id(7L).employeeNo("E7") - .realName("Operator").userType("FINANCE").build(); - SecurityContextHolder.getContext().setAuthentication( - new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities())); - ReimApplication application = ReimApplication.builder().id(10L).applicantId(20L) - .totalAmount(new BigDecimal("100.00")).approvalStatus("APPROVED") - .receiptStatus("RECEIVED").build(); - when(applications.findByIdForUpdate(10L)).thenReturn(Optional.of(application)); - } - - @AfterEach - void tearDown() { - SecurityContextHolder.clearContext(); - } - - @Test - void sameRequestReturnsExistingPaymentWithoutCreatingAnotherRecord() { - when(payments.findByIdempotencyKey(anyString())).thenReturn(existingPayment()); - - assertEquals("PAY-1", service.executePayment(10L, new BigDecimal("100.00"), 7L, - null, "REF-1", "memo", " key ").getPaymentNo()); - - verify(payments, never()).save(any(ReimPayment.class)); - InOrder order = inOrder(idempotencyLock, payments); - order.verify(idempotencyLock).lock("key"); - order.verify(payments).findByIdempotencyKey("key"); - } - - @Test - void sameKeyWithDifferentAmountReturnsConflict() { - when(payments.findByIdempotencyKey(anyString())).thenReturn(existingPayment()); - - BusinessException error = assertThrows(BusinessException.class, - () -> service.executePayment(10L, new BigDecimal("99.00"), 7L, - null, "REF-1", "memo", "key")); - - assertEquals(409, error.getStatusCode()); - assertTrue(error.getMessage().contains("幂等键")); - verify(payments, never()).save(any(ReimPayment.class)); - verify(idempotencyLock).lock("key"); - } - - @Test - void paymentNumberUsesReadableDateAndRandomSuffixWithoutSequenceLookup() { - when(payments.findByIdempotencyKey(anyString())).thenReturn(null); - when(payments.findByApplicationId(10L)).thenReturn(java.util.Collections.emptyList()); - when(payments.save(any(ReimPayment.class))).thenAnswer(invocation -> invocation.getArgument(0)); - - service.executePayment(10L, new BigDecimal("100.00"), 7L, - null, "REF-2", "memo", "new-key"); - - ArgumentCaptor captor = ArgumentCaptor.forClass(ReimPayment.class); - verify(payments).save(captor.capture()); - assertTrue(captor.getValue().getPaymentNo().matches("PAY-\\d{8}-[A-F0-9]{12}")); - assertTrue(captor.getValue().getPaymentNo().length() <= 50); - verify(payments, never()).findTopByPaymentNoStartingWithOrderByPaymentNoDesc(anyString()); - } - - private ReimPayment existingPayment() { - return ReimPayment.builder().paymentNo("PAY-1").applicationId(10L).operatorId(7L) - .paymentAmount(new BigDecimal("100.00")).paymentMethod("BANK_TRANSFER") - .referenceNo("REF-1").remark("memo").paymentStatus("COMPLETED") - .idempotencyKey("key").build(); - } -}