commit 0a83dfb7bef2e2837ac877294ddbc186a92b1d9f Author: Weiming Date: Fri Sep 11 13:54:37 2026 +0800 初始化 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d70cda5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +target/ + +.idea/ +*.iml +out/ + +*.class +*.log + +.env +application-local.yml +application-local.yaml +application-local.properties + +logs/ +uploads/ +tmp/ + +.DS_Store +Thumbs.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..5ded15d --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# Backend deployment notes + +Before saving any `secret=true` value in `sys_integration_config`, configure +`APP_INTEGRATION_ENCRYPTION_KEY` (preferably a randomly generated 32-byte or +longer secret) in the backend runtime environment. Do not commit the key or +place a real value in `src/main/resources/application.yml`. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..5e5140a --- /dev/null +++ b/pom.xml @@ -0,0 +1,173 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + + com.finance.system + finance-system + 1.0.0 + finance-system + 统一费用支付平台 - 员工报销管理系统 + + + 8 + 0.11.5 + 1.5.5.Final + 1.6.15 + 1.18.30 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-actuator + + + + + org.postgresql + postgresql + runtime + + + com.h2database + h2 + runtime + + + org.flywaydb + flyway-core + + + + + io.jsonwebtoken + jjwt-api + ${jjwt.version} + + + io.jsonwebtoken + jjwt-impl + ${jjwt.version} + runtime + + + io.jsonwebtoken + jjwt-jackson + ${jjwt.version} + runtime + + + + + org.mapstruct + mapstruct + ${mapstruct.version} + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + provided + + + + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + + + + + org.projectlombok + lombok + ${lombok.version} + true + + + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + org.projectlombok + lombok + ${lombok.version} + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + + + + + diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..3c6ef09 --- /dev/null +++ b/run.bat @@ -0,0 +1,21 @@ +@echo off +set JAVA_HOME=C:\PROGRA~1\Java\OPENJD~1 +set MAVEN_HOME=C:\Users\it\.m2 +set PROJECT_DIR=D:\code\Java\financial_system\finance-system\backend + +cd /d "%PROJECT_DIR%" + +REM Find the classworlds jar +set CLASSWORLDS_JAR= +for %%i in ("%MAVEN_HOME%\boot\plexus-classworlds-*.jar") do set CLASSWORLDS_JAR=%%i + +REM Run Maven directly +"%JAVA_HOME%\bin\java.exe" ^ + -classpath "%CLASSWORLDS_JAR%" ^ + "-Dclassworlds.conf=%MAVEN_HOME%\bin\m2.conf" ^ + "-Dmaven.home=%MAVEN_HOME%" ^ + "-Dmaven.multiModuleProjectDirectory=%PROJECT_DIR%" ^ + "-Dspring-boot.run.profiles=local" ^ + "-Dmaven.test.skip=true" ^ + org.codehaus.plexus.classworlds.launcher.Launcher ^ + spring-boot:run diff --git a/src/main/java/com/finance/system/FinanceSystemApplication.java b/src/main/java/com/finance/system/FinanceSystemApplication.java new file mode 100644 index 0000000..30795e6 --- /dev/null +++ b/src/main/java/com/finance/system/FinanceSystemApplication.java @@ -0,0 +1,14 @@ +package com.finance.system; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +@SpringBootApplication +@EnableConfigurationProperties +public class FinanceSystemApplication { + + public static void main(String[] args) { + SpringApplication.run(FinanceSystemApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java new file mode 100644 index 0000000..b4b0926 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java @@ -0,0 +1,82 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.ReimApplication; +import com.finance.system.entity.ReimExpenseItem; +import com.finance.system.entity.SysUser; +import com.finance.system.entity.SysDepartment; +import com.finance.system.entity.SysExpenseType; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 飞书审批表单构建器 + * 将系统报销数据转换为飞书审批实例的表单数据 + */ +public class FeishuApprovalFormBuilder { + + /** + * 构建审批表单数据 + */ + public static Map buildForm(ReimApplication app, SysUser applicant, + SysDepartment department, SysExpenseType expenseType, + List items) { + Map form = new HashMap<>(); + + // 基本字段 + form.put("application_no", app.getApplicationNo()); + form.put("title", app.getTitle()); + form.put("applicant_name", applicant != null ? applicant.getRealName() : ""); + form.put("department", department != null ? department.getDeptName() : ""); + form.put("expense_type", expenseType != null ? expenseType.getTypeName() : ""); + form.put("total_amount", app.getTotalAmount() != null ? app.getTotalAmount().toString() : "0"); + form.put("description", app.getDescription() != null ? app.getDescription() : ""); + form.put("source_doc_no", app.getSourceDocNo() != null ? app.getSourceDocNo() : ""); + + // 费用明细(多行文本展示) + if (items != null && !items.isEmpty()) { + String itemDetail = items.stream() + .map(item -> String.format("%s | %s | ¥%.2f", + item.getExpenseDate() != null ? item.getExpenseDate().toString() : "", + item.getDescription() != null ? item.getDescription() : "", + item.getAmount() != null ? item.getAmount() : BigDecimal.ZERO)) + .collect(Collectors.joining("\n")); + form.put("expense_items", itemDetail); + } + + return form; + } + + /** + * 构建飞书审批表单(用于创建审批实例的API请求) + */ + public static String buildFormJson(Map formData) { + StringBuilder json = new StringBuilder("{"); + boolean first = true; + for (Map.Entry entry : formData.entrySet()) { + if (!first) { + json.append(","); + } + json.append("\"") + .append(escapeJson(entry.getKey())) + .append("\":\"") + .append(escapeJson(entry.getValue() != null ? entry.getValue() : "")) + .append("\""); + first = false; + } + json.append("}"); + return json.toString(); + } + + private static String escapeJson(String value) { + if (value == null) return ""; + return value.replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t"); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java new file mode 100644 index 0000000..42f5b77 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java @@ -0,0 +1,129 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * 飞书审批API响应DTO + */ +@Data +@NoArgsConstructor +public class FeishuApprovalResponse { + + private int code; + private String msg; + private Data data; + + @lombok.Data + @NoArgsConstructor + public static class Data { + /** 审批实例编码 */ + @JsonProperty("instance_code") + private String instanceCode; + + /** 审批定义编码 */ + @JsonProperty("approval_code") + private String approvalCode; + + /** 审批状态 PENDING/APPROVED/REJECTED/CANCELED/TERMINATED */ + private String status; + + /** 审批实例链接 */ + private String url; + + /** 审批节点列表 */ + @JsonProperty("node_list") + private List nodeList; + + /** 审批时间线 */ + private List timeline; + + /** 审批定义名称 */ + @JsonProperty("approval_name") + private String approvalName; + + /** 审批表单 */ + private Object form; + } + + /** + * 审批节点定义 + */ + @lombok.Data + @NoArgsConstructor + public static class ApprovalNode { + private String id; + private String name; + + /** AND/OR */ + private String type; + + /** 审批人列表 */ + private List approver; + + /** 超时时间(分钟) */ + private int timeout; + + /** 节点层级 */ + private int level; + } + + /** + * 审批人 + */ + @lombok.Data + @NoArgsConstructor + public static class Approver { + /** user/role/free */ + private String type; + + /** 用户ID或角色ID */ + @JsonProperty("user_id") + private String userId; + + /** 角色ID */ + @JsonProperty("role_id") + private String roleId; + + /** 角色名称 */ + @JsonProperty("role_name") + private String roleName; + + /** 用户姓名 */ + private String name; + } + + /** + * 审批时间线节点(审批进度) + */ + @lombok.Data + @NoArgsConstructor + public static class TimelineNode { + /** approval/cc/comment */ + private String type; + + /** 节点名称 */ + @JsonProperty("node_name") + private String nodeName; + + /** 审批状态 */ + private String status; + + /** 审批人姓名 */ + private String approver; + + /** 审批人头像 */ + @JsonProperty("approver_avatar") + private String approverAvatar; + + /** 审批意见 */ + private String comment; + + /** 审批时间 */ + @JsonProperty("action_time") + private String actionTime; + } +} \ 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 new file mode 100644 index 0000000..1b4331d --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java @@ -0,0 +1,449 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.*; +import com.finance.system.enums.ApplicationStatus; +import com.finance.system.enums.ApprovalStatus; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.*; +import com.finance.system.service.IntegrationConfigReader; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; +import org.springframework.util.StringUtils; + +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.*; + +/** + * 飞书审批服务 + * 负责:创建审批实例、查询审批定义(节点信息)、同步审批结果 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class FeishuApprovalService { + + private final FeishuConfig feishuConfig; + private final FeishuAuthService feishuAuthService; + private final SysUserRepository sysUserRepository; + private final SysDepartmentRepository sysDepartmentRepository; + private final SysExpenseTypeRepository sysExpenseTypeRepository; + private final ReimExpenseItemRepository reimExpenseItemRepository; + private final IntFeishuApprovalRepository intFeishuApprovalRepository; + private final ReimApplicationRepository reimApplicationRepository; + private final RestTemplate restTemplate; + private IntegrationConfigReader integrationConfigReader; + + @Autowired(required = false) + public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) { + this.integrationConfigReader = integrationConfigReader; + } + + private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis"; + + /** + * Whether submission should be delegated to Feishu rather than the local + * approval-node workflow. A missing approval definition is not a usable + * integration even when the app credentials are present. + */ + public boolean isApprovalEnabledAndConfigured() { + String appId = configValue("appId", feishuConfig.getAppId()); + String appSecret = configValue("appSecret", feishuConfig.getAppSecret()); + String code = approvalCode(); + boolean configured = StringUtils.hasText(appId) + && StringUtils.hasText(appSecret) + && StringUtils.hasText(code); + return configured && (integrationConfigReader == null || integrationConfigReader.isEnabled("FEISHU")); + } + + // ==================== 1. 获取审批定义(审批节点信息) ==================== + + /** + * 获取飞书审批定义详情 + * 包括审批流程的所有节点、审批人配置、表单定义 + */ + public FeishuApprovalResponse getApprovalDefinition() { + String token = feishuAuthService.getTenantAccessToken(); + String url = FEISHU_OPEN_API + "/approval/openapi/v2/approval/get"; + + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(token); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map requestBody = new HashMap<>(); + requestBody.put("approval_code", approvalCode()); + + HttpEntity> request = new HttpEntity<>(requestBody, headers); + + 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()); + } + return resp; + } catch (Exception e) { + log.error("获取飞书审批定义失败", e); + throw new BusinessException("获取审批节点信息失败,请检查飞书权限配置"); + } + } + + /** + * 获取审批节点列表(用于前端展示审批流程) + */ + public List getApprovalNodes() { + FeishuApprovalResponse response = getApprovalDefinition(); + if (response != null && response.getData() != null) { + return response.getData().getNodeList(); + } + return Collections.emptyList(); + } + + // ==================== 2. 创建审批实例 ==================== + + /** + * 创建飞书审批实例 + * + * @param application 报销申请 + * @return 飞书审批实例编码 + */ + @Transactional + public String createApprovalInstance(ReimApplication application) { + if (application == null || application.getId() == null) { + throw new BusinessException("报销申请不存在,无法创建飞书审批", 400); + } + Optional existing = intFeishuApprovalRepository + .findByApplicationId(application.getId()); + IntFeishuApproval reusableRecord = existing.orElse(null); + if (existing.isPresent()) { + String existingStatus = normalizeApprovalStatus(existing.get().getStatus()); + if (!isRetryableTerminal(existingStatus) && StringUtils.hasText(existing.get().getFeishuInstanceCode())) { + log.info("飞书审批实例已存在,跳过重复创建: applicationNo={}, instanceCode={}", + application.getApplicationNo(), existing.get().getFeishuInstanceCode()); + return existing.get().getFeishuInstanceCode(); + } + if (!isRetryableTerminal(existingStatus)) { + throw new BusinessException("该申请已有未完成的飞书同步记录,请稍后重试"); + } + } + + if (application.getApplicantId() == null) { + throw new BusinessException("申请人不存在,无法创建飞书审批", 400); + } + SysUser applicant = sysUserRepository.findById(application.getApplicantId()) + .orElseThrow(() -> new BusinessException("申请人不存在,无法创建飞书审批", 400)); + if (!StringUtils.hasText(applicant.getFeishuUserId()) + && !StringUtils.hasText(applicant.getFeishuOpenId())) { + throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 400); + } + + String token = feishuAuthService.getTenantAccessToken(); + String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/create"; + + // 获取关联数据 + SysDepartment department = application.getDepartmentId() != null + ? sysDepartmentRepository.findById(application.getDepartmentId()).orElse(null) : null; + SysExpenseType expenseType = application.getExpenseTypeId() != null + ? sysExpenseTypeRepository.findById(application.getExpenseTypeId()).orElse(null) : null; + List 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); + + 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); + throw e; + } catch (Exception e) { + log.error("创建飞书审批实例失败: applicationNo={}", application.getApplicationNo(), e); + throw new BusinessException("创建飞书审批失败,请稍后重试"); + } + } + + // ==================== 3. 查询审批实例详情(含进度) ==================== + + /** + * 获取审批实例详情 + * 包含审批进度、各节点状态、审批意见 + */ + public FeishuApprovalResponse getApprovalInstanceDetail(String instanceCode) { + String token = feishuAuthService.getTenantAccessToken(); + String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/get"; + + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(token); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map requestBody = new HashMap<>(); + requestBody.put("instance_code", instanceCode); + + HttpEntity> request = new HttpEntity<>(requestBody, headers); + + 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()); + } + return resp; + } catch (Exception e) { + log.error("获取审批实例详情失败: instanceCode={}", instanceCode, e); + throw new BusinessException("获取审批进度失败"); + } + } + + /** + * 获取审批时间线(各节点审批进度) + */ + public List getApprovalTimeline(String instanceCode) { + FeishuApprovalResponse detail = getApprovalInstanceDetail(instanceCode); + if (detail != null && detail.getData() != null) { + return detail.getData().getTimeline(); + } + return Collections.emptyList(); + } + + // ==================== 4. 同步审批结果 ==================== + + /** + * 同步审批结果到系统 + * 由Webhook回调触发,或定时任务调用 + * + * @param instanceCode 飞书审批实例编码 + * @param status 审批状态 + * @param comment 审批意见 + */ + @Transactional + public void syncApprovalResult(String instanceCode, String status, String comment) { + IntFeishuApproval syncRecord = intFeishuApprovalRepository + .findByFeishuInstanceCodeForUpdate(instanceCode) + .orElseThrow(() -> new BusinessException("未找到对应的审批同步记录")); + + String normalizedStatus = normalizeApprovalStatus(status); + if (normalizedStatus == null) { + log.warn("忽略未知飞书审批状态: instanceCode={}, status={}", instanceCode, status); + return; + } + + // Terminal records are monotonic. This prevents a delayed PENDING + // callback from reopening an already approved/rejected application. + String previousStatus = normalizeApprovalStatus(syncRecord.getStatus()); + if (isTerminal(previousStatus)) { + log.info("忽略终态后的旧飞书审批事件: instanceCode={}, oldStatus={}, status={}", + instanceCode, previousStatus, normalizedStatus); + return; + } + + ReimApplication application = reimApplicationRepository.findById(syncRecord.getApplicationId()) + .orElseThrow(() -> new BusinessException("未找到对应的报销申请")); + + // 更新同步记录 + syncRecord.setStatus(normalizedStatus); + syncRecord.setSyncedAt(LocalDateTime.now()); + intFeishuApprovalRepository.save(syncRecord); + + application.setApprovalStatus(normalizedStatus); + if (ApprovalStatus.PENDING.name().equals(normalizedStatus)) { + application.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); + application.setCurrentApprovalNode("飞书审批"); + application.setCurrentApproverId(null); + application.setApproveTime(null); + } else { + application.setCurrentApproverId(null); + application.setCurrentApprovalNode(null); + if (ApprovalStatus.APPROVED.name().equals(normalizedStatus)) { + application.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); + application.setApproveTime(LocalDateTime.now()); + } else { + // Rejected/cancelled applications follow the existing local + // returned-draft behavior and can be corrected and resubmitted. + application.setApplicationStatus(ApplicationStatus.DRAFT.name()); + application.setApproveTime(null); + } + } + reimApplicationRepository.save(application); + + log.info("飞书审批同步成功: instanceCode={}, status={}, comment={}", + instanceCode, normalizedStatus, comment); + } + + /** + * 根据报销单ID查询审批进度 + */ + public List getApprovalTimelineByApplication(Long applicationId) { + IntFeishuApproval syncRecord = intFeishuApprovalRepository + .findByApplicationId(applicationId) + .orElse(null); + + if (syncRecord == null || syncRecord.getFeishuInstanceCode() == null) { + return Collections.emptyList(); + } + + return getApprovalTimeline(syncRecord.getFeishuInstanceCode()); + } + + // ==================== 5. Webhook 处理 ==================== + + /** + * 处理飞书审批事件回调 + * + * 支持的事件类型: + * - approval_instance: 审批实例状态变更 + * - approval_task: 审批任务变更 + */ + @Transactional + public void handleApprovalEvent(Map eventData) { + String eventType = (String) eventData.get("event_type"); + if (eventType == null) { + log.warn("飞书事件回调缺少event_type"); + return; + } + + switch (eventType) { + case "approval_instance": + handleInstanceStatusChange(eventData); + break; + case "approval_task": + handleTaskChange(eventData); + break; + default: + log.info("未处理的事件类型: {}", eventType); + } + } + + /** + * 处理审批实例状态变更事件 + */ + private void handleInstanceStatusChange(Map eventData) { + Map instance = nestedMap(eventData.get("instance")); + // Feishu v2 approval_instance events put instance_code/status directly + // under event. FeishuAuthController flattens that event map, while + // older payloads still use the nested instance object. + if (instance == null && eventData.containsKey("instance_code")) { + instance = eventData; + } + if (instance == null) return; + + String instanceCode = (String) instance.get("instance_code"); + String status = (String) instance.get("status"); + String comment = (String) instance.get("comment"); + + if (instanceCode != null && status != null) { + syncApprovalResult(instanceCode, status, comment); + } + } + + /** + * 处理审批任务变更事件 + */ + private void handleTaskChange(Map eventData) { + @SuppressWarnings("unchecked") + Map task = (Map) eventData.get("task"); + if (task == null) return; + + String instanceCode = (String) task.get("instance_code"); + log.info("审批任务变更: instanceCode={}", instanceCode); + } + + private String approvalCode() { + String fallback = feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getApprovalCode(); + return integrationConfigReader == null ? fallback : integrationConfigReader.get("FEISHU", "approvalCode"); + } + + private String configValue(String key, String fallback) { + if (integrationConfigReader == null) return fallback; + String value = integrationConfigReader.get("FEISHU", key); + return StringUtils.hasText(value) ? value : fallback; + } + + private String createRequestId(ReimApplication application, IntFeishuApproval reusableRecord) { + String seed = "finance-system:feishu:approval:" + application.getId(); + if (reusableRecord != null && isRetryableTerminal(normalizeApprovalStatus(reusableRecord.getStatus()))) { + String originalInstance = StringUtils.hasText(reusableRecord.getFeishuInstanceCode()) + ? reusableRecord.getFeishuInstanceCode() : "none"; + seed += ":retry:" + originalInstance; + } + return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString(); + } + + @SuppressWarnings("unchecked") + private Map nestedMap(Object value) { + return value instanceof Map ? (Map) value : null; + } + + private String normalizeApprovalStatus(String status) { + if (!StringUtils.hasText(status)) return null; + String normalized = status.trim().toUpperCase(Locale.ROOT); + if ("CANCELED".equals(normalized)) normalized = ApprovalStatus.CANCELLED.name(); + for (ApprovalStatus known : ApprovalStatus.values()) { + if (known.name().equals(normalized)) return normalized; + } + return null; + } + + private boolean isTerminal(String status) { + return ApprovalStatus.APPROVED.name().equals(status) + || ApprovalStatus.REJECTED.name().equals(status) + || ApprovalStatus.CANCELLED.name().equals(status); + } + + private boolean isRetryableTerminal(String status) { + return ApprovalStatus.REJECTED.name().equals(status) + || ApprovalStatus.CANCELLED.name().equals(status); + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java new file mode 100644 index 0000000..cde8a1e --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java @@ -0,0 +1,355 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.SysUser; +import com.finance.system.entity.SysOauthState; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysOauthStateRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.service.IntegrationConfigReader; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Map; +import java.util.Base64; + +@Slf4j +@Service +@RequiredArgsConstructor +public class FeishuAuthService { + + private final FeishuConfig feishuConfig; + private final SysUserRepository sysUserRepository; + private final SysOauthStateRepository sysOauthStateRepository; + private final RestTemplate restTemplate; + private IntegrationConfigReader integrationConfigReader; + @Autowired + private FeishuTenantTokenService tenantTokens; + @Autowired + private FeishuLoginPersistenceService loginPersistence; + + @Autowired(required = false) + public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) { + this.integrationConfigReader = integrationConfigReader; + } + + private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis"; + private static final String FEISHU_AUTH_URL = "https://open.feishu.cn/open-apis/authen/v1/authorize"; + private static final long OAUTH_STATE_TTL_MILLIS = 5 * 60 * 1000L; + private final SecureRandom secureRandom = new SecureRandom(); + + /** + * 构建飞书授权URL + */ + @Transactional + public AuthUrl buildAuthUrlWithState() { + requireConfigured(); + long now = System.currentTimeMillis(); + // Cleanup is deliberately limited to expired rows. There is no fixed + // capacity or random eviction, so one unauthenticated caller cannot + // invalidate another browser's state. + sysOauthStateRepository.deleteExpired(now); + + byte[] randomState = new byte[32]; + secureRandom.nextBytes(randomState); + String state = Base64.getUrlEncoder().withoutPadding().encodeToString(randomState); + long expiresAt = now + OAUTH_STATE_TTL_MILLIS; + sysOauthStateRepository.save(new SysOauthState(state, expiresAt)); + + String authUrl = FEISHU_AUTH_URL + + "?app_id=" + encode(appId()) + + "&redirect_uri=" + encode(redirectUri()) + + "&response_type=code" + + "&state=" + state; + return new AuthUrl(authUrl, state); + } + + /** Builds the URL while retaining the original service method contract. */ + @Transactional + public String buildAuthUrl() { + return buildAuthUrlWithState().getAuthUrl(); + } + + @Transactional + public void validateCallbackState(String state) { + validateCallbackState(state, null, false); + } + + /** + * Validate the one-time state against the shared database. The callback + * only checks state existence; the code exchange consumes it so the + * authorization code and state are both single-use. + */ + @Transactional + public void validateCallbackState(String state, String browserState, boolean consume) { + if (!StringUtils.hasText(state)) { + throw new BusinessException("飞书登录状态缺失,请重新发起授权", 400); + } + if (consume && (!StringUtils.hasText(browserState) + || !java.security.MessageDigest.isEqual( + state.getBytes(StandardCharsets.UTF_8), browserState.getBytes(StandardCharsets.UTF_8)))) { + throw new BusinessException("飞书登录状态与当前浏览器不匹配,请重新发起授权", 400); + } + long now = System.currentTimeMillis(); + if (consume) { + if (sysOauthStateRepository.consumeIfValid(state, now) != 1) { + throw new BusinessException("飞书登录状态无效或已过期", 400); + } + } else if (!sysOauthStateRepository.findByStateAndExpiresAtGreaterThan(state, now).isPresent()) { + throw new BusinessException("飞书登录状态无效或已过期", 400); + } + } + + private void requireConfigured() { + if (integrationConfigReader != null && !integrationConfigReader.isEnabled("FEISHU")) { + throw new BusinessException("飞书集成未启用,请先完成配置"); + } + if (!StringUtils.hasText(appId()) || !StringUtils.hasText(appSecret())) { + throw new BusinessException("飞书登录未配置,请在后端运行配置中设置 FEISHU_APP_ID 和 FEISHU_APP_SECRET"); + } + } + + private String encode(String value) { + try { return URLEncoder.encode(value == null ? "" : value, "UTF-8"); } + catch (Exception e) { return ""; } + } + + /** Validates the token supplied by Feishu, or its documented SHA-256 signature. */ + public boolean isWebhookAuthorized(Map body, String signature, + String timestamp, String nonce, String rawBody) { + String configuredToken = verificationToken(); + Object requestToken = body == null ? null : body.get("token"); + if (configuredToken != null && !configuredToken.trim().isEmpty() + && configuredToken.equals(requestToken)) return true; + if (signature == null || signature.trim().isEmpty() + || !StringUtils.hasText(encryptKey())) return false; + try { + String signed = (timestamp == null ? "" : timestamp) + (nonce == null ? "" : nonce) + + encryptKey() + (rawBody == null ? "" : rawBody); + byte[] digest = java.security.MessageDigest.getInstance("SHA-256") + .digest(signed.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(); + for (byte b : digest) hex.append(String.format("%02x", b & 0xff)); + return secureEquals(hex.toString(), signature); + } catch (Exception e) { + return false; + } + } + + private boolean secureEquals(String expected, String actual) { + return java.security.MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), + actual.getBytes(StandardCharsets.UTF_8)); + } + + /** + * 通过授权码获取access_token + */ + public FeishuTokenResponse getAccessToken(String code) { + requireConfigured(); + String url = FEISHU_OPEN_API + "/authen/v1/access_token"; + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map requestBody = new java.util.HashMap<>(); + requestBody.put("grant_type", "authorization_code"); + requestBody.put("code", code); + requestBody.put("app_id", appId()); + requestBody.put("app_secret", appSecret()); + + HttpEntity> request = new HttpEntity<>(requestBody, headers); + + try { + ResponseEntity response = restTemplate.postForEntity( + url, request, FeishuTokenResponse.class); + FeishuTokenResponse tokenResponse = response.getBody(); + if (tokenResponse == null) throw new BusinessException("飞书授权未返回令牌"); + if (tokenResponse.getCode() != 0) throw new BusinessException("飞书授权失败: " + tokenResponse.getMsg()); + if (tokenResponse.getData() == null || !StringUtils.hasText(tokenResponse.getData().getAccessToken())) + throw new BusinessException("飞书授权未返回有效令牌"); + return tokenResponse; + } catch (Exception e) { + log.error("飞书获取access_token失败", e); + throw new BusinessException("飞书授权失败,请稍后重试"); + } + } + + /** + * 获取用户信息 + */ + public FeishuUserInfo getUserInfo(String accessToken) { + String url = FEISHU_OPEN_API + "/authen/v1/user_info"; + + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(accessToken); + + HttpEntity request = new HttpEntity<>(headers); + + try { + 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()); + } + + FeishuUserInfo userInfo = new FeishuUserInfo(); + userInfo.setOpenId(userResponse.getData().getOpenId()); + userInfo.setUserId(userResponse.getData().getUserId()); + userInfo.setName(userResponse.getData().getName()); + userInfo.setAvatarUrl(userResponse.getData().getAvatarUrl()); + userInfo.setEmail(userResponse.getData().getEmail()); + userInfo.setMobile(userResponse.getData().getMobile()); + return userInfo; + } catch (Exception e) { + log.error("获取飞书用户信息失败", e); + throw new BusinessException("获取用户信息失败"); + } + } + + /** + * 获取tenant_access_token + */ + public String getTenantAccessToken() { + return tenantTokens.getTenantAccessToken(); + } + + /** + * Resolve the local account from the exact Feishu open_id and finalize the + * identity/profile binding. Directory synchronization is operational data, + * not an OAuth login admission check. + */ + public SysUser findOrCreateUser(FeishuUserInfo feishuUserInfo) { + if (feishuUserInfo == null || !StringUtils.hasText(feishuUserInfo.getOpenId())) { + throw invalidFeishuIdentity(); + } + + String openId = feishuUserInfo.getOpenId().trim(); + String userId = StringUtils.hasText(feishuUserInfo.getUserId()) + ? feishuUserInfo.getUserId().trim() : null; + validateOAuthProfile(openId, userId, feishuUserInfo); + + // open_id is mandatory for account matching. Never query with null or + // bind a record based on an incomplete Feishu response. + SysUser user = sysUserRepository.findByFeishuOpenId(openId); + + // Check ownership before provisioning. user_id is only a duplicate- + // ownership guard; it is never used to discover or adopt an account. + SysUser otherOwner = userId == null ? null : sysUserRepository.findByFeishuUserId(userId); + if (otherOwner != null && (user == null || !java.util.Objects.equals(user.getId(), otherOwner.getId()))) { + throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403); + } + + if (user == null) { + try { + user = provisionEmployee(feishuUserInfo); + } catch (DataIntegrityViolationException race) { + // A concurrent first login may have won the unique open_id + // insert. Reuse that committed account instead of exposing + // a database 500 to the OAuth callback. + user = sysUserRepository.findByFeishuOpenId(openId); + if (user == null) throw new BusinessException("飞书账号绑定冲突,请联系管理员", 403); + } + } + + // Reject dual ownership even when both identifiers on the selected record are populated. + if (otherOwner != null && !java.util.Objects.equals(user.getId(), otherOwner.getId())) + throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403); + + // The finalizer rechecks the exact open_id and current ACTIVE status + // under a row lock, then performs only the safe profile/binding update. + return loginPersistence.completeOAuth(user.getId(), feishuUserInfo); + } + + /** Provision an ordinary employee; OAuth can never create a privileged account. */ + @Transactional + protected SysUser provisionEmployee(FeishuUserInfo feishuUserInfo) { + String openId = feishuUserInfo.getOpenId().trim(); + SysUser existing = sysUserRepository.findByFeishuOpenId(openId); + if (existing != null) return existing; + + String userId = feishuUserInfo.getUserId() == null ? null : feishuUserInfo.getUserId().trim(); + String number = uniqueEmployeeNo(); + + SysUser user = SysUser.builder() + .feishuOpenId(openId) + .feishuUserId(StringUtils.hasText(userId) ? userId : null) + .employeeNo(number) + .realName(StringUtils.hasText(feishuUserInfo.getName()) ? feishuUserInfo.getName() : "Feishu User") + .avatarUrl(feishuUserInfo.getAvatarUrl()) + .email(feishuUserInfo.getEmail()) + .mobile(feishuUserInfo.getMobile()) + .userType("EMPLOYEE") + .status("ACTIVE") + .directoryStatus("UNKNOWN") + .build(); + SysUser saved = sysUserRepository.save(user); + if (saved != null) user = saved; + log.info("自动创建 Feishu EMPLOYEE 用户: openId={}, employeeNo={}, name={}", openId, number, user.getRealName()); + // Flush so the subsequent lookup sees the new record + sysUserRepository.flush(); + return user; + } + + private void validateOAuthProfile(String openId, String userId, FeishuUserInfo info) { + validateLength(openId, 100); + validateLength(userId, 100); + validateLength(info.getName(), 100); + validateLength(info.getAvatarUrl(), 500); + validateLength(info.getEmail(), 200); + validateLength(info.getMobile(), 20); + } + + private void validateLength(String value, int max) { + if (value != null && value.length() > max) { + throw new BusinessException("飞书用户资料无效,请重新授权", 403); + } + } + + private String uniqueEmployeeNo() { + for (int attempt = 0; attempt < 5; attempt++) { + String number = "FS-" + java.util.UUID.randomUUID(); + if (sysUserRepository.findByEmployeeNo(number) == null) return number; + } + throw new BusinessException("员工编号生成失败,请稍后重试", 503); + } + + private BusinessException invalidFeishuIdentity() { + return new BusinessException("飞书身份无效,请重新授权", 403); + } + + private String appId() { return configured("appId", feishuConfig.getAppId()); } + private String appSecret() { return configured("appSecret", feishuConfig.getAppSecret()); } + private String redirectUri() { return configured("redirectUri", feishuConfig.getRedirectUri()); } + private String approvalCode() { return configured("approvalCode", feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getApprovalCode()); } + private String verificationToken() { return configured("verificationToken", feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getVerificationToken()); } + private String encryptKey() { return configured("encryptKey", feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getEncryptKey()); } + private String configured(String key, String fallback) { return integrationConfigReader == null ? fallback : integrationConfigReader.get("FEISHU", key); } + + public static final class AuthUrl { + private final String authUrl; + private final String state; + + public AuthUrl(String authUrl, String state) { + this.authUrl = authUrl; + this.state = state; + } + + public String getAuthUrl() { + return authUrl; + } + + public String getState() { + return state; + } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java new file mode 100644 index 0000000..b6ce8c6 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java @@ -0,0 +1,35 @@ +package com.finance.system.adapter.feishu; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "feishu") +public class FeishuConfig { + private String appId; + private String appSecret; + private String redirectUri; + /** + * Legacy setting retained for configuration compatibility. OAuth no + * longer has a local bootstrap exception and always provisions an + * ordinary employee. + */ + @Deprecated + private boolean localBootstrapEnabled = false; + /** @deprecated No longer used for OAuth identity provisioning. */ + @Deprecated + private String localBootstrapOpenId; + private Approval approval = new Approval(); + + @Data + public static class Approval { + /** 飞书审批定义编码,如 EXPENSE_REIMBURSEMENT_001 */ + private String approvalCode; + /** 事件回调验证Token */ + private String verificationToken; + /** 事件回调加密Key(可选) */ + private String encryptKey; + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java new file mode 100644 index 0000000..887d635 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java @@ -0,0 +1,62 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import org.springframework.core.env.Environment; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; + +@Service +public class FeishuDirectoryAccessService { + private final FeishuTenantTokenService tokens; + private final FeishuDirectorySettings settings; + private final Environment environment; + private final JdbcTemplate jdbc; + public FeishuDirectoryAccessService(FeishuTenantTokenService tokens, FeishuDirectoryClient client, + FeishuDirectorySettings settings, Environment environment, JdbcTemplate jdbc, + org.springframework.transaction.PlatformTransactionManager manager) { + this.tokens = tokens; this.settings = settings; this.environment = environment; this.jdbc = jdbc; + } + public boolean allowed(SysUser user) { + if (user == null || !"ACTIVE".equalsIgnoreCase(user.getStatus())) return false; + if (Arrays.stream(environment.getActiveProfiles()).anyMatch("local"::equalsIgnoreCase) + && blank(user.getFeishuOpenId()) && blank(user.getFeishuUserId())) return true; + return directoryAllowed(user); + } + public boolean directoryAllowed(SysUser user) { + try { + return user != null && !blank(user.getFeishuOpenId()) && "ACTIVE".equalsIgnoreCase(user.getStatus()) && "ELIGIBLE".equals(user.getDirectoryStatus()) + && tokens.capture().fingerprint.equals(user.getDirectoryContext()) && user.getDirectoryVerifiedAt() != null + && !user.getDirectoryVerifiedAt().isAfter(Instant.now()) + && user.getDirectoryVerifiedAt().plusSeconds(settings.statusAge()).isAfter(Instant.now()) + && !blank(user.getDirectoryLastSeenRunId()) && !blank(user.getFeishuUserId()) + && currentSnapshotMatches(user); + } catch (Exception e) { return false; } + } + public void requireAllowed(SysUser user) { if (!allowed(user)) throw denied(); } + public void requireSynced(SysUser user) { + if (!directoryAllowed(user) || user.getDirectoryLastSeenRunId() == null) throw denied(); + } + private boolean currentSnapshotMatches(SysUser user) { + if (jdbc == null) return false; + try { + Map state = jdbc.queryForMap("SELECT last_successful_run_id,last_successful_at,successful_context FROM feishu_directory_state WHERE id=1"); + Object runId = state.get("last_successful_run_id"); + Object successfulContext = state.get("successful_context"); + Timestamp successfulAt = (Timestamp) state.get("last_successful_at"); + Instant now = Instant.now(); + return runId != null && successfulContext != null && successfulAt != null + && runId.toString().equals(user.getDirectoryLastSeenRunId()) + && successfulContext.toString().equals(user.getDirectoryContext()) + && !successfulAt.toInstant().isAfter(now) + && successfulAt.toInstant().plusSeconds(settings.statusAge()).isAfter(now); + } catch (Exception e) { return false; } + } + + private static boolean blank(String value) { return value == null || value.trim().isEmpty(); } + private static BusinessException denied() { return new BusinessException("Current eligible Feishu employee verification required", 403); } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java new file mode 100644 index 0000000..f6ac463 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java @@ -0,0 +1,21 @@ +package com.finance.system.adapter.feishu; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class FeishuDirectoryBootstrap { + private final FeishuDirectorySettings settings; + private final FeishuDirectoryService directory; + @EventListener(ApplicationReadyEvent.class) + public void start() { + if (!settings.isBootstrapSyncOnStartup()) return; + try { directory.sync("STARTUP"); } + catch (Exception e) { log.warn("Startup directory sync unavailable; employee access remains fail-closed"); } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java new file mode 100644 index 0000000..f78c63c --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java @@ -0,0 +1,809 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.databind.JsonNode; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.*; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import lombok.extern.slf4j.Slf4j; +import java.math.BigInteger; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.concurrent.locks.LockSupport; + +/** Contact v3 only. No caller-controlled host, URL or identifier type. */ +@Component +@Slf4j +public class FeishuDirectoryClient { + private static final BigInteger SUCCESS_CODE = BigInteger.ZERO; + private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L); + private static final BigInteger DEFINITIVE_CODE_41012 = BigInteger.valueOf(41012L); + private static final BigInteger DEFINITIVE_CODE_41050 = BigInteger.valueOf(41050L); + private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); + private static final String DEPARTMENT_STATUS_INVALID = "DIRECTORY_DEPARTMENT_STATUS_INVALID"; + private static final String IDENTITY_INVALID = "DIRECTORY_IDENTITY_INVALID"; + private static final String LIMIT_EXCEEDED = "DIRECTORY_LIMIT_EXCEEDED"; + + private enum PageKind { + DEPARTMENT("DIRECTORY_DEPARTMENT_PAGE_INVALID", "DIRECTORY_DEPARTMENT_ITEM_INVALID", + "DIRECTORY_DEPARTMENT_PAGE_TOKEN_INVALID", "DIRECTORY_DEPARTMENT_ITEMS_INVALID", + "DIRECTORY_DEPARTMENT_HAS_MORE_INVALID"), + USER("DIRECTORY_USER_PAGE_INVALID", "DIRECTORY_USER_ITEM_INVALID", + "DIRECTORY_USER_PAGE_TOKEN_INVALID", "DIRECTORY_USER_ITEMS_INVALID", + "DIRECTORY_USER_HAS_MORE_INVALID"); + + private final String pageInvalid; + private final String itemInvalid; + private final String pageTokenInvalid; + private final String itemsInvalid; + private final String hasMoreInvalid; + + PageKind(String pageInvalid, String itemInvalid, String pageTokenInvalid) { + this(pageInvalid, itemInvalid, pageTokenInvalid, pageInvalid, pageInvalid); + } + + PageKind(String pageInvalid, String itemInvalid, String pageTokenInvalid, + String itemsInvalid, String hasMoreInvalid) { + this.pageInvalid = pageInvalid; + this.itemInvalid = itemInvalid; + this.pageTokenInvalid = pageTokenInvalid; + this.itemsInvalid = itemsInvalid; + this.hasMoreInvalid = hasMoreInvalid; + } + } + + private final FeishuTenantTokenService tokens; + private final FeishuDirectorySettings settings; + private final RestTemplate http; + private final RateGate rateGate; + // A hard wall-clock deadline also covers slow/trickling HTTP bodies. No unbounded work queue. + private final ExecutorService workers = new ThreadPoolExecutor(0, 2, 30, + TimeUnit.SECONDS, new SynchronousQueue<>(), task -> { + Thread thread = new Thread(task, "feishu-directory-http"); thread.setDaemon(true); return thread; + }); + // Department and user pages are fetched in bounded batches. The queue is + // bounded as well so concurrent snapshots cannot turn a large department + // tree into thousands of pending tasks. + private final ExecutorService directoryWorkers; + @Autowired + public FeishuDirectoryClient(FeishuTenantTokenService tokens, FeishuDirectorySettings settings) { + this(tokens, settings, httpClient()); + } + FeishuDirectoryClient(FeishuTenantTokenService tokens, FeishuDirectorySettings settings, RestTemplate http) { + this.tokens = tokens; this.settings = settings; this.http = http; + this.rateGate = new RateGate(settings); + int concurrency = settings.getDirectoryConcurrency(); + this.directoryWorkers = new ThreadPoolExecutor(concurrency, concurrency, 0L, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(concurrency), task -> { + Thread thread = new Thread(task, "feishu-directory-user-http"); thread.setDaemon(true); return thread; + }); + } + @javax.annotation.PreDestroy + public void close() { + shutdownGracefully(workers); + shutdownGracefully(directoryWorkers); + } + private static void shutdownGracefully(ExecutorService executor) { + executor.shutdown(); + try { + if (!executor.awaitTermination(1, TimeUnit.SECONDS)) executor.shutdownNow(); + } catch (InterruptedException e) { + executor.shutdownNow(); Thread.currentThread().interrupt(); + } + } + private static RestTemplate httpClient() { + SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); f.setConnectTimeout(3000); f.setReadTimeout(5000); + return new RestTemplate(f); + } + public Snapshot fetch(FeishuTenantTokenService.Context context) { + final Budget budget = new Budget(); + return bounded(() -> fetchSnapshot(context, budget), settings.elapsed()); + } + private Snapshot fetchSnapshot(FeishuTenantTokenService.Context context, Budget budget) { + budget.check(); + String token = tokens.token(context); + budget.check(); + Snapshot snapshot = new Snapshot(); + snapshot.departments.add("0"); + snapshot.departmentDetails.put("0", Department.root()); + discoverDepartments(snapshot, token, budget); + fetchUsers(snapshot, token, budget); + budget.check(); return snapshot; + } + private void discoverDepartments(Snapshot snapshot, String token, Budget budget) { + ArrayDeque 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; + while (true) { + budget.page(); + HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(token); + 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); + } + return body.path("data"); + } catch (DefinitiveDenial e) { throw e; } + catch (FeishuTenantTokenService.DiagnosticFailure e) { throw e; } + catch (RateLimited e) { + if (retries++ >= settings.maxRetries()) + throw FeishuTenantTokenService.diagnostic("DIRECTORY_RATE_LIMIT_EXHAUSTED"); + rateGate.block(e.resetSeconds); + budget.awaitRateLimit(e.resetSeconds, retries); + } catch (org.springframework.web.client.HttpStatusCodeException e) { + JsonNode body = null; + try { body = readErrorBody(e.getResponseBodyAsString()); } catch (Exception ignored) { } + if (live && definitive(body)) throw new DefinitiveDenial(); + if (isRateLimited(body, e.getStatusCode().value())) { + if (retries++ >= settings.maxRetries()) + throw FeishuTenantTokenService.diagnostic("DIRECTORY_RATE_LIMIT_EXHAUSTED"); + String reset = e.getResponseHeaders() == null ? null + : e.getResponseHeaders().getFirst("x-ogw-ratelimit-reset"); + Long resetSeconds = parseResetSeconds(reset); + rateGate.block(resetSeconds); + budget.awaitRateLimit(resetSeconds, retries); + continue; + } + RemoteFailure failure = remoteFailure(body, e.getStatusCode().value()); + if (failure != null) throw failure; + throw FeishuTenantTokenService.diagnostic("DIRECTORY_REQUEST_FAILED"); + } catch (Exception e) { throw FeishuTenantTokenService.diagnostic("DIRECTORY_REQUEST_FAILED"); } + } + } + private static boolean isRateLimited(JsonNode body, Integer status) { + return (status != null && status == 429) || (body != null && body.path("code").isIntegralNumber() + && RATE_LIMIT_CODE.equals(responseCode(body))); + } + private static Long parseResetSeconds(String value) { + if (value == null || !value.trim().matches("[0-9]{1,10}")) return null; + try { return Long.valueOf(value.trim()); } catch (NumberFormatException ignored) { return null; } + } + private static JsonNode readErrorBody(String responseBody) throws java.io.IOException { + // Error text is deliberately never retained or included in an exception. Avoid + // parsing an unexpectedly large response while looking for its numeric code. + if (responseBody == null || responseBody.length() > 16384) return null; + return new com.fasterxml.jackson.databind.ObjectMapper().readTree(responseBody); + } + private static RemoteFailure remoteFailure(JsonNode body, Integer httpStatus) { + Long code = safeCode(body); + if (code != null) return new RemoteFailure("FEISHU_CODE_" + code); + if (httpStatus != null && httpStatus >= 100 && httpStatus <= 599) + return new RemoteFailure("HTTP_STATUS_" + httpStatus); + return null; + } + private static Long safeCode(JsonNode body) { + BigInteger code = responseCode(body); + if (code == null || code.signum() <= 0 || code.compareTo(MAX_DIAGNOSTIC_CODE) > 0) return null; + return code.longValueExact(); + } + private static boolean definitive(JsonNode body) { + BigInteger code = responseCode(body); + return DEFINITIVE_CODE_41050.equals(code) || DEFINITIVE_CODE_41012.equals(code); + } + private static BigInteger responseCode(JsonNode body) { + if (body == null) return null; + JsonNode value = body.path("code"); + if (!value.isIntegralNumber()) return null; + try { return value.bigIntegerValue(); } + catch (RuntimeException ignored) { return null; } + } + private static class DefinitiveDenial extends RuntimeException { } + /** Numeric-only diagnostic that is safe to cross the bounded worker boundary. */ + public static final class RemoteFailure extends FeishuTenantTokenService.DiagnosticFailure { + private RemoteFailure(String diagnosticCode) { + super(diagnosticCode); + } + } + private T 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); } + } + public static boolean eligible(JsonNode user) { + JsonNode status = user.path("status"); + return status.path("is_activated").isBoolean() && status.path("is_activated").booleanValue() + && status.path("is_resigned").isBoolean() && !status.path("is_resigned").booleanValue() + && status.path("is_frozen").isBoolean() && !status.path("is_frozen").booleanValue() + && status.path("is_exited").isBoolean() && !status.path("is_exited").booleanValue() + && status.path("is_unjoin").isBoolean() && !status.path("is_unjoin").booleanValue() + && user.path("employee_type").isIntegralNumber() + && BigInteger.ONE.equals(user.path("employee_type").bigIntegerValue()); + } + static String required(JsonNode node, String key) { + return required(node, key, 100); + } + static String requiredIdentity(JsonNode node, String key) { + JsonNode value = node == null ? null : node.path(key); + if (!validText(value, 100)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); + return value.asText().trim(); + } + private static String requiredDepartmentIdentity(JsonNode node, String key) { + JsonNode value = node == null ? null : node.path(key); + if (!validText(value, 64)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); + return value.asText().trim(); + } + private static String required(JsonNode node, String key, int maxLength) { + JsonNode value = node == null ? null : node.path(key); + if (!validText(value, maxLength)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); + return value.asText(); + } + private static String requiredPageToken(JsonNode node, PageKind kind) { + JsonNode value = node == null ? null : node.path("page_token"); + if (!validText(value, 4096)) throw FeishuTenantTokenService.diagnostic(kind.pageTokenInvalid); + return value.asText(); + } + private static boolean validText(JsonNode value, int maxLength) { + return value != null && value.isTextual() && !value.asText().trim().isEmpty() + && value.asText().length() <= maxLength; + } + private static boolean validText(String value, int maxLength) { + return value != null && !value.trim().isEmpty() && value.length() <= maxLength; + } + private static String segment(String id) { + if (id == null || !id.matches("[A-Za-z0-9][A-Za-z0-9_@.\\-]{0,63}")) + throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID); + return id; + } + public static class Snapshot { + public final Set 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 static class Department { + public String openDepartmentId; + public String name; + public String parentOpenDepartmentId; + public long order; + public String status; + public int memberCount; + + public static Department root() { + Department root = new Department(); + root.openDepartmentId = "0"; + root.name = "根部门"; + root.parentOpenDepartmentId = "0"; + root.status = "ACTIVE"; + return root; + } + + static Department from(JsonNode node, String id, String traversalParent) { + Department department = new Department(); + department.openDepartmentId = id; + department.name = optionalText(node, "name", ""); + // parent_department_id is deliberately not used here: with an + // open-id request it may still be a legacy/custom identifier. + // The traversal request already establishes the parent with an + // open id. Prefer it over any legacy parent_department_id-shaped + // value returned in the payload. + department.parentOpenDepartmentId = traversalParent; + department.order = optionalLong(node, "order", 0L); + department.status = "ACTIVE"; + return department; + } + + public String getOpenDepartmentId() { return openDepartmentId; } + public String getName() { return name; } + public String getParentOpenDepartmentId() { return parentOpenDepartmentId; } + public long getOrder() { return order; } + public String getStatus() { return status; } + public int getMemberCount() { return memberCount; } + } + + public static class UserSummary { + public String openId; + public String userId; + public String name; + public String employeeNo; + public String email; + public String mobile; + public String jobTitle; + public Integer employeeType; + public String avatarUrl; + public String employmentStatus; + public final List departmentIds = new ArrayList<>(); + public boolean eligible; + + static UserSummary from(JsonNode node, String fallbackDepartment) { + UserSummary summary = new UserSummary(); + summary.openId = optionalText(node, "open_id", ""); + summary.userId = optionalText(node, "user_id", ""); + summary.name = optionalText(node, "name", ""); + summary.employeeNo = optionalText(node, "employee_no", ""); + // Keep this allow-list deliberately explicit. Contact v3 user nodes + // contain more data than the directory API is allowed to retain. + summary.email = optionalText(node, "email", "", 320); + summary.mobile = optionalText(node, "mobile", "", 50); + summary.jobTitle = optionalText(node, "job_title", "", 200); + if (summary.jobTitle.isEmpty()) summary.jobTitle = optionalText(node, "position", "", 200); + summary.employeeType = optionalInteger(node, "employee_type"); + summary.avatarUrl = optionalAvatarUrl(node); + summary.employmentStatus = employmentStatus(node); + JsonNode ids = node == null ? null : node.path("department_ids"); + if (ids != null && ids.isArray()) { + for (JsonNode id : ids) { + if (id.isTextual() && validText(id, 64) && !summary.departmentIds.contains(id.asText().trim())) + summary.departmentIds.add(id.asText().trim()); + } + } + // A missing department_ids field is common on reduced contact + // responses. The requested department is already an open id and + // is therefore a safe fallback; department_id is never consulted. + if (summary.departmentIds.isEmpty() && validText(fallbackDepartment, 64)) + summary.departmentIds.add(fallbackDepartment.trim()); + summary.eligible = eligible(node); + return summary; + } + + void addDepartment(String department) { + if (validText(department, 64) && !departmentIds.contains(department.trim())) + departmentIds.add(department.trim()); + } + + void merge(JsonNode node, Set 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; } + } + + private static String optionalText(JsonNode node, String key, String fallback) { + return optionalText(node, key, fallback, 100); + } + + private static String optionalText(JsonNode node, String key, String fallback, int maxLength) { + JsonNode value = node == null ? null : node.path(key); + return value != null && value.isTextual() && value.asText().length() <= maxLength + ? value.asText().trim() : fallback; + } + + private static Integer optionalInteger(JsonNode node, String key) { + JsonNode value = node == null ? null : node.path(key); + if (value == null || !value.isIntegralNumber()) return null; + try { + BigInteger integer = value.bigIntegerValue(); + if (integer.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 + || integer.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) + return null; + return integer.intValueExact(); + } catch (RuntimeException ignored) { + return null; + } + } + + private static String optionalAvatarUrl(JsonNode node) { + String value = optionalText(node, "avatar_url", "", 500); + if (!value.isEmpty()) return value; + value = optionalText(node, "avatar", "", 500); + if (!value.isEmpty()) return value; + + // Some Contact v3 responses represent avatar as an object. Select only + // documented URL variants; never serialize the object itself. + JsonNode avatar = node == null ? null : node.path("avatar"); + if (avatar != null && avatar.isObject()) { + for (String key : new String[]{"avatar_url", "avatar_origin", "avatar_640", "avatar_240", "avatar_72"}) { + value = optionalText(avatar, key, "", 500); + if (!value.isEmpty()) return value; + } + } + return ""; + } + + /** Safe summary derived from the official status booleans, not a raw status object. */ + private static String employmentStatus(JsonNode node) { + JsonNode status = node == null ? null : node.path("status"); + if (status == null || !status.isObject()) return "UNKNOWN"; + if (status.path("is_exited").isBoolean() && status.path("is_exited").booleanValue()) return "EXITED"; + if (status.path("is_resigned").isBoolean() && status.path("is_resigned").booleanValue()) return "RESIGNED"; + if (status.path("is_frozen").isBoolean() && status.path("is_frozen").booleanValue()) return "FROZEN"; + if (status.path("is_unjoin").isBoolean() && status.path("is_unjoin").booleanValue()) return "UNJOINED"; + if (status.path("is_activated").isBoolean()) + return status.path("is_activated").booleanValue() ? "ACTIVE" : "INACTIVE"; + return "UNKNOWN"; + } + + private static long optionalLong(JsonNode node, String key, long fallback) { + JsonNode value = node == null ? null : node.path(key); + if (value == null) return fallback; + if (value.isIntegralNumber()) { + try { return value.bigIntegerValue().longValueExact(); } + catch (ArithmeticException ignored) { return fallback; } + } + if (!value.isTextual()) return fallback; + String text = value.asText().trim(); + // Contact v3 has returned order both as a JSON number and as a + // numeric string. Bound the text before parsing so malformed provider + // data cannot trigger unbounded numeric work. + if (text.length() == 0 || text.length() > 20 || !text.matches("[+-]?[0-9]+")) return fallback; + try { return new BigInteger(text).longValueExact(); } + catch (NumberFormatException | ArithmeticException ignored) { return fallback; } + } + private static final class RateLimited extends RuntimeException { + private final Long resetSeconds; + private RateLimited(Long resetSeconds) { this.resetSeconds = resetSeconds; } + } + /** One gate is shared by department discovery, user paging and verification. */ + private final class RateGate { + private final FeishuDirectorySettings settings; + private final Deque 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(); + } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java new file mode 100644 index 0000000..aebdf93 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java @@ -0,0 +1,811 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysUserRepository; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.*; + +@Service +@Slf4j +public class FeishuDirectoryService { + private final JdbcTemplate jdbc; + private final TransactionTemplate tx; + private final SysUserRepository users; + private final FeishuTenantTokenService tokens; + private final FeishuDirectoryClient client; + private final FeishuDirectorySettings settings; + private final ObjectMapper mapper; + public FeishuDirectoryService(JdbcTemplate jdbc, PlatformTransactionManager manager, SysUserRepository users, + FeishuTenantTokenService tokens, FeishuDirectoryClient client, + FeishuDirectorySettings settings, ObjectMapper mapper) { + this.jdbc = jdbc; this.tx = new TransactionTemplate(manager); this.tx.setTimeout(30); this.users = users; this.tokens = tokens; + this.tx.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.tx.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + this.client = client; this.settings = settings; this.mapper = mapper; + } + public Run sync(String trigger) { + if (!Arrays.asList("MANUAL", "STARTUP").contains(trigger)) throw new IllegalArgumentException("Invalid trigger"); + Run run = new Run(); run.runId = UUID.randomUUID().toString(); run.trigger = trigger; run.startedAt = Instant.now().toString(); + FeishuTenantTokenService.Context context; + String runContext = null; + // Even configuration failures retain an operator-visible failed run. + acquire(run); + insertSyncRun(run); + try { + context = tx.execute(s -> { + lock(); + // Capture first so a disabled/missing integration is not mistaken for + // the separate directory-sync switch being disabled. + FeishuTenantTokenService.Context captured = tokens.capture(); + if (!tokens.syncEnabled()) throw FeishuTenantTokenService.syncDisabled(); + return captured; + }); + final String fingerprint = context.fingerprint; + runContext = fingerprint; + updateSyncRunContext(run.runId, fingerprint); + jdbc.update("UPDATE feishu_directory_state SET context=? WHERE id=1 AND owner=?", fingerprint, run.runId); + FeishuDirectoryClient.Snapshot snapshot = client.fetch(context); + // This probe must not be allowed to fail on the publication + // connection. It is deliberately performed between transactions; + // the metadata implementation also avoids a missing-table SQL + // statement. A migration racing this probe is handled atomically by + // the publication transaction below. + final boolean normalizedAvailable = normalizedSchemaAvailable(); + tx.execute(s -> { + requireOwner(run, fingerprint); + if (!fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged(); + if (!tokens.syncEnabled()) throw FeishuTenantTokenService.syncDisabled(); + apply(snapshot, run, fingerprint); + replaceNormalizedSnapshot(snapshot, run, fingerprint, normalizedAvailable); + requireOwner(run, fingerprint); + if (!fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged(); + run.state = "SUCCEEDED"; run.complete = true; run.applied = true; run.finishedAt = Instant.now().toString(); + // Encode only the allow-listed snapshot DTOs. Raw Feishu nodes + // are used above for account application, but are never persisted. + String snapshotJson = snapshotJson(snapshot); + jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=?,last_snapshot=? WHERE id=1", + json(run), run.runId, Timestamp.from(Instant.parse(run.finishedAt)), fingerprint, snapshotJson); + return null; + }); + // Run history is auxiliary telemetry. Keep its optional table + // update outside the publication transaction so a V9-only + // deployment cannot mark that transaction rollback-only. + updateSyncRun(run, fingerprint); + } catch (Exception ex) { + run.state = "FAILED"; run.complete = false; run.applied = false; run.finishedAt = Instant.now().toString(); + run.counts = new Counts(); + String diagnostic = safeDiagnostic(ex); + run.errorCode = diagnostic == null ? "DIRECTORY_SYNC_FAILED" : diagnostic; + run.errorMessage = failureMessage(diagnostic); + // Never log the exception: its cause may contain a connector detail or a + // response body. The diagnostic is constructed from numeric values only. + log.warn("Feishu directory sync failed: runId={}, errorCode={}", run.runId, run.errorCode); + updateSyncRun(run, runContext); + jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,last_run=? WHERE id=1 AND owner=?", json(run), run.runId); + } + return run; + } + + private void insertSyncRun(Run run) { + try { + jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger,state,started_at,complete,applied,departments,users_seen,eligible,excluded,created,updated,ineligible,out_of_scope,error_code,error_message,context) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + run.runId, run.trigger, run.state, Timestamp.from(Instant.parse(run.startedAt)), + run.complete, run.applied, 0, 0, 0, 0, 0, 0, 0, 0, null, null, null); + } catch (Exception ignored) { + // Run history is auxiliary observability. A transient history-table + // failure must not prevent the fenced directory sync itself. + log.warn("Feishu directory sync run could not be recorded"); + } + } + + private void updateSyncRunContext(String runId, String context) { + try { + jdbc.update("UPDATE feishu_directory_sync_run SET context=? WHERE run_id=?", context, runId); + } catch (Exception ignored) { + log.warn("Feishu directory sync run context could not be recorded"); + } + } + + private void updateSyncRun(Run run, String context) { + try { + Counts counts = run.counts == null ? new Counts() : run.counts; + jdbc.update("UPDATE feishu_directory_sync_run SET state=?,finished_at=?,complete=?,applied=?,departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,error_code=?,error_message=?,context=? WHERE run_id=?", + run.state, run.finishedAt == null ? null : Timestamp.from(Instant.parse(run.finishedAt)), + run.complete, run.applied, counts.departments, counts.usersSeen, counts.eligible, + counts.excluded, counts.created, counts.updated, counts.ineligible, counts.outOfScope, + run.errorCode, run.errorMessage, context, run.runId); + } catch (Exception ignored) { + log.warn("Feishu directory sync run result could not be recorded: state={}", run.state); + } + } + + private void replaceNormalizedSnapshot(FeishuDirectoryClient.Snapshot snapshot, Run run, String context, + boolean normalizedAvailable) { + // Keep V9 deployments operational during a rolling migration. Once + // V10 exists, any write failure below is allowed to abort publication. + if (!normalizedAvailable) return; + Timestamp observedAt = Timestamp.from(Instant.now()); + Map> 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; + }); + } + 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 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); + } + + 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; + } + + /** + * 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; } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java new file mode 100644 index 0000000..82df451 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySettings.java @@ -0,0 +1,41 @@ +package com.finance.system.adapter.feishu; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "feishu.directory") +public class FeishuDirectorySettings { + private boolean bootstrapSyncOnStartup = false; + // Increment whenever application visibility changes outside this system. + private String credentialRevision = "1"; + private long maxStatusAgeSeconds = 86400; + private int maxPages = 2000; + private int maxUsers = 50000; + private int maxDepartments = 5000; + private long maxElapsedSeconds = 120; + private String departmentIdType = "open_department_id"; + private int directoryConcurrency = 4; + private int maxRetries = 3; + private int requestsPerSecond = 45; + private int requestsPerMinute = 900; + public long statusAge() { return Math.max(1, Math.min(86400, maxStatusAgeSeconds)); } + public long elapsed() { return Math.max(1, Math.min(300, maxElapsedSeconds)); } + /** Contact v3 snapshots are keyed by the immutable open department id. */ + public String departmentIdType() { return "open_department_id"; } + public String getDepartmentIdType() { return departmentIdType(); } + public int directoryConcurrency() { return Math.max(1, Math.min(8, directoryConcurrency)); } + public int getDirectoryConcurrency() { return directoryConcurrency(); } + /** Compatibility with the original setting name; both settings control the same bound. */ + @Deprecated public int userFetchConcurrency() { return directoryConcurrency(); } + @Deprecated public int getUserFetchConcurrency() { return directoryConcurrency(); } + @Deprecated public void setUserFetchConcurrency(int value) { this.directoryConcurrency = value; } + public int maxRetries() { return Math.max(0, Math.min(5, maxRetries)); } + public int getMaxRetries() { return maxRetries(); } + public int requestsPerSecond() { return Math.max(1, Math.min(50, requestsPerSecond)); } + public int getRequestsPerSecond() { return requestsPerSecond(); } + public int requestsPerMinute() { return Math.max(1, Math.min(1000, requestsPerMinute)); } + public int getRequestsPerMinute() { return requestsPerMinute(); } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java new file mode 100644 index 0000000..7f3c5a0 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java @@ -0,0 +1,96 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.service.FeishuDirectoryLock; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.Objects; + +/** Login's commit point. Never merge an account loaded before the remote OAuth exchange. + * Only profile, a missing counterpart of an EXACT open_id binding, and last-login + * columns can be written. Role/status and directory observations are never written here. + */ +@Service +public class FeishuLoginPersistenceService { + private final JdbcTemplate jdbc; + private final EntityManager em; + private final SysUserRepository users; + private final FeishuDirectoryAccessService access; + private final TransactionTemplate tx; + public FeishuLoginPersistenceService(JdbcTemplate jdbc, EntityManager em, SysUserRepository users, + FeishuDirectoryAccessService access, FeishuTenantTokenService tokens, PlatformTransactionManager manager) { + this.jdbc = jdbc; this.em = em; this.users = users; this.access = access; + tx = new TransactionTemplate(manager); tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tx.setTimeout(30); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + /** + * Complete OAuth login without consulting the directory snapshot. The + * three-argument overload remains for callers compiled against the former + * API; its context argument is intentionally ignored. + */ + public SysUser completeOAuth(Long id, FeishuUserInfo info) { + return tx.execute(s -> { + if (info == null || info.getOpenId() == null || info.getOpenId().trim().isEmpty()) throw denied(); + String openId = info.getOpenId().trim(); + validate(openId, 100); + + // Serialize OAuth finalization with directory/configuration writes; + // the lock protects identity/profile consistency even though the + // OAuth admission decision no longer reads directory state. + FeishuDirectoryLock.acquire(jdbc); + SysUser fresh = locked(id); + // open_id is the only Feishu identity used for account matching. + // Never replace it or adopt an account using user_id alone. + if (!Objects.equals(fresh.getFeishuOpenId(), openId)) throw denied(); + + String counterpart = info.getUserId() == null ? null : info.getUserId().trim(); + if (counterpart != null && counterpart.isEmpty()) counterpart = null; + String existingUserId = fresh.getFeishuUserId(); + if (counterpart != null && existingUserId != null && !existingUserId.trim().isEmpty() + && !counterpart.equals(existingUserId)) throw denied(); + if (counterpart != null && jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE feishu_user_id=? AND id<>?", Integer.class, counterpart, id) != 0) throw denied(); + String name = info.getName() == null || info.getName().trim().isEmpty() ? fresh.getRealName() : info.getName(); + validate(name, 100); validate(info.getAvatarUrl(), 500); validate(info.getEmail(), 200); validate(info.getMobile(), 20); validate(counterpart, 100); + jdbc.update("UPDATE sys_user SET real_name=?,avatar_url=?,email=?,mobile=?,feishu_user_id=CASE WHEN feishu_user_id IS NULL OR TRIM(feishu_user_id)='' THEN ? ELSE feishu_user_id END,last_login_at=? WHERE id=?", + name, keepExisting(info.getAvatarUrl(), fresh.getAvatarUrl()), + keepExisting(info.getEmail(), fresh.getEmail()), keepExisting(info.getMobile(), fresh.getMobile()), + counterpart, Timestamp.valueOf(LocalDateTime.now()), id); + em.refresh(fresh); // return current role/status, NOT a stale pre-HTTP object + return fresh; + }); + } + + /** @deprecated Directory context is no longer part of OAuth admission. */ + @Deprecated + public SysUser completeOAuth(Long id, FeishuUserInfo info, String verifiedContext) { + return completeOAuth(id, info); + } + public SysUser completeLocal(Long id) { + return tx.execute(s -> { + FeishuDirectoryLock.acquire(jdbc); + SysUser fresh = locked(id); access.requireAllowed(fresh); + jdbc.update("UPDATE sys_user SET last_login_at=? WHERE id=?", Timestamp.valueOf(LocalDateTime.now()), id); + em.refresh(fresh); return fresh; + }); + } + private SysUser locked(Long id) { + SysUser fresh = users.findById(id).orElseThrow(FeishuLoginPersistenceService::denied); + em.refresh(fresh, LockModeType.PESSIMISTIC_WRITE); + if (!"ACTIVE".equalsIgnoreCase(fresh.getStatus())) throw denied(); + return fresh; + } + private static void validate(String value, int length) { if (value != null && value.length() > length) throw denied(); } + private static String keepExisting(String incoming, String existing) { + return incoming == null || incoming.trim().isEmpty() ? existing : incoming; + } + private static BusinessException denied() { return new BusinessException("Active Feishu identity binding required", 403); } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuMessageService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuMessageService.java new file mode 100644 index 0000000..b6a6f36 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuMessageService.java @@ -0,0 +1,121 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysUserRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +/** + * 飞书消息服务 + * 负责:发送审批待办通知、付款结果通知等消息 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class FeishuMessageService { + + private final FeishuAuthService feishuAuthService; + private final SysUserRepository sysUserRepository; + private final RestTemplate restTemplate; + + private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis"; + + /** + * 发送审批待办通知 + */ + public void sendApprovalNotification(Long approverId, String applicationNo, + String title, String applicantName, + BigDecimal amount, String detailUrl) { + SysUser approver = sysUserRepository.findById(approverId).orElse(null); + if (approver == null || approver.getFeishuOpenId() == null) { + log.warn("审批人未绑定飞书,无法发送通知: userId={}", approverId); + return; + } + + String content = buildApprovalCard(applicationNo, title, applicantName, amount, detailUrl); + sendMessage(approver.getFeishuOpenId(), "interactive", content); + } + + /** + * 发送付款结果通知 + */ + public void sendPaymentNotification(Long userId, String applicationNo, + BigDecimal amount, String paymentStatus, String detailUrl) { + SysUser user = sysUserRepository.findById(userId).orElse(null); + if (user == null || user.getFeishuOpenId() == null) { + log.warn("用户未绑定飞书,无法发送通知: userId={}", userId); + return; + } + + String content = buildPaymentCard(applicationNo, amount, paymentStatus, detailUrl); + sendMessage(user.getFeishuOpenId(), "interactive", content); + } + + /** + * 发送飞书消息 + */ + private void sendMessage(String receiveId, String msgType, String content) { + String token = feishuAuthService.getTenantAccessToken(); + String url = FEISHU_OPEN_API + "/im/v1/messages?receive_id_type=open_id"; + + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(token); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map requestBody = new HashMap<>(); + requestBody.put("receive_id", receiveId); + requestBody.put("msg_type", msgType); + requestBody.put("content", content); + + HttpEntity> request = new HttpEntity<>(requestBody, headers); + + try { + ResponseEntity response = restTemplate.exchange( + url, HttpMethod.POST, request, Map.class); + log.info("飞书消息发送成功: receiveId={}, msgType={}", receiveId, msgType); + } catch (Exception e) { + log.error("飞书消息发送失败: receiveId={}", receiveId, e); + throw new BusinessException("发送飞书消息失败"); + } + } + + /** + * 构建审批待办卡片消息 + */ + private String buildApprovalCard(String applicationNo, String title, + String applicantName, BigDecimal amount, String detailUrl) { + return String.format("{\"config\":{\"wide_screen_mode\":true}," + + "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"📋 报销审批待办\"},\"template\":\"blue\"}," + + "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您有一笔报销申请需要审批:\\n**单号**:%s\\n**标题**:%s\\n**申请人**:%s\\n**金额**:¥%.2f\"}}," + + "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"去审批\"},\"type\":\"primary\",\"multi_url\":{\"url\":\"%s\",\"pc_url\":\"\"}}]}]}", + applicationNo, title, applicantName, amount, detailUrl); + } + + /** + * 构建付款结果卡片消息 + */ + private String buildPaymentCard(String applicationNo, BigDecimal amount, + String paymentStatus, String detailUrl) { + String statusText; + switch (paymentStatus) { + case "PAID": statusText = "✅ 已付款"; break; + case "PARTIAL": statusText = "🔄 部分付款"; break; + case "FAILED": statusText = "❌ 付款失败"; break; + default: statusText = "⏳ 处理中"; + } + + return String.format("{\"config\":{\"wide_screen_mode\":true}," + + "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"💰 付款结果通知\"},\"template\":\"green\"}," + + "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您的报销申请已处理:\\n**单号**:%s\\n**金额**:¥%.2f\\n**状态**:%s\"}}," + + "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"查看详情\"},\"type\":\"default\",\"multi_url\":{\"url\":\"%s\",\"pc_url\":\"\"}}]}]}", + applicationNo, amount, statusText, detailUrl); + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java new file mode 100644 index 0000000..fc80b6b --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java @@ -0,0 +1,163 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.databind.JsonNode; +import com.finance.system.exception.BusinessException; +import com.finance.system.service.IntegrationConfigReader; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.*; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.*; + +@Service +public class FeishuTenantTokenService { + static final String API = "https://open.feishu.cn/open-apis"; + private static final BigInteger SUCCESS_CODE = BigInteger.ZERO; + private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); + private final IntegrationConfigReader config; + private final FeishuDirectorySettings settings; + private final RestTemplate http; + + @Autowired + public FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings) { + this(config, settings, httpClient()); + } + + FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings, RestTemplate http) { + this.config = config; this.settings = settings; this.http = http; + } + + private static RestTemplate httpClient() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(3000); factory.setReadTimeout(5000); + return new RestTemplate(factory); + } + + public Context capture() { + Map values; + try { + values = config.freshFeishu(); + } catch (Exception ex) { + // Configuration readers may fail while decrypting persisted secrets. Do + // not let that exception (or its message) cross the adapter boundary. + throw diagnostic("CONFIGURATION_UNAVAILABLE"); + } + if (values == null) throw diagnostic("CONFIGURATION_MISSING"); + String app = values.get("appId"), secret = values.get("appSecret"); + // A disabled integration is deliberately reported as configuration missing, + // while the independent directory-sync switch is reported as SYNC_DISABLED. + // Neither path exposes the configured values. + if (app == null || app.trim().isEmpty() || secret == null || secret.trim().isEmpty() + || !Boolean.parseBoolean(values.get(IntegrationConfigReader.INTERNAL_ENABLED_KEY))) + throw diagnostic("CONFIGURATION_MISSING"); + return new Context(app, secret, fingerprint(app + "\n" + secret + + "\nroot=0;department_id_type=" + settings.departmentIdType() + + ";employee_type=1;policy=1\n" + settings.getCredentialRevision())); + } + + public boolean syncEnabled() { + Map values; + try { values = config.freshFeishu(); } + catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); } + return values != null && Boolean.parseBoolean(values.getOrDefault("syncOrgEnabled", "true")); + } + public String getTenantAccessToken() { return token(capture()); } + + public String token(Context context) { + if (context == null) throw diagnostic("TOKEN_CONTEXT_MISSING"); + Map body = new HashMap<>(); body.put("app_id", context.app); body.put("app_secret", context.secret); + try { + JsonNode response = http.postForObject(API + "/auth/v3/tenant_access_token/internal", body, JsonNode.class); + BigInteger responseCode = responseCode(response); + if (responseCode == null) throw diagnostic("TOKEN_RESPONSE_INVALID"); + if (!SUCCESS_CODE.equals(responseCode)) { + Long code = safeCode(response); + throw code == null ? diagnostic("TOKEN_RESPONSE_INVALID") : diagnostic("FEISHU_CODE_" + code); + } + if (!response.path("tenant_access_token").isTextual() + || response.path("tenant_access_token").asText().trim().isEmpty()) + throw diagnostic("TOKEN_RESPONSE_INVALID"); + return response.path("tenant_access_token").asText(); + } catch (DiagnosticFailure ex) { + throw ex; + } catch (org.springframework.web.client.HttpStatusCodeException ex) { + JsonNode response = null; + try { response = readErrorBody(ex.getResponseBodyAsString()); } catch (Exception ignored) { } + Long code = safeCode(response); + if (code != null) throw diagnostic("FEISHU_CODE_" + code); + int status = ex.getStatusCode().value(); + if (status >= 100 && status <= 599) throw diagnostic("HTTP_STATUS_" + status); + throw diagnostic("TOKEN_REQUEST_FAILED"); + } catch (Exception ex) { + // Never carry an upstream exception across the boundary. It may contain + // credentials, response content, or an arbitrary connector message. + throw diagnostic("TOKEN_REQUEST_FAILED"); + } + } + + static DiagnosticFailure diagnostic(String code) { + return new DiagnosticFailure(isSafeDiagnostic(code) ? code : "DIRECTORY_UNAVAILABLE"); + } + + static BusinessException unavailable() { return diagnostic("DIRECTORY_UNAVAILABLE"); } + static DiagnosticFailure syncDisabled() { return diagnostic("SYNC_DISABLED"); } + static DiagnosticFailure contextChanged() { return diagnostic("DIRECTORY_CONTEXT_CHANGED"); } + static DiagnosticFailure ownershipLost() { return diagnostic("DIRECTORY_OWNERSHIP_LOST"); } + + private static JsonNode readErrorBody(String responseBody) throws java.io.IOException { + // Error text is never retained in a diagnostic. Bound parsing so a failed + // endpoint cannot make the error path consume an unbounded response. + if (responseBody == null || responseBody.length() > 16384) return null; + return new com.fasterxml.jackson.databind.ObjectMapper().readTree(responseBody); + } + + private static Long safeCode(JsonNode body) { + BigInteger code = responseCode(body); + if (code == null || code.signum() <= 0 || code.compareTo(MAX_DIAGNOSTIC_CODE) > 0) return null; + return code.longValueExact(); + } + + private static BigInteger responseCode(JsonNode body) { + if (body == null) return null; + JsonNode value = body.path("code"); + if (!value.isIntegralNumber()) return null; + try { return value.bigIntegerValue(); } + catch (RuntimeException ignored) { return null; } + } + + private static boolean isSafeDiagnostic(String code) { + return code != null && (code.matches("CONFIGURATION_MISSING|CONFIGURATION_UNAVAILABLE|SYNC_DISABLED") + || code.matches("FEISHU_CODE_[1-9][0-9]{0,8}") + || code.matches("HTTP_STATUS_[1-5][0-9]{2}") + || code.matches("(?:TOKEN|DIRECTORY)_[A-Z0-9_]{1,40}")); + } + + /** Safe, bounded diagnostic that may cross connector and worker boundaries. */ + public static class DiagnosticFailure extends BusinessException { + private final String diagnosticCode; + + DiagnosticFailure(String diagnosticCode) { + super("Feishu directory operation failed: " + diagnosticCode, 503); + this.diagnosticCode = diagnosticCode; + } + + public String getDiagnosticCode() { return diagnosticCode; } + } + + private static String fingerprint(String input) { + try { + byte[] hash = MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8)); + StringBuilder out = new StringBuilder(); for (byte b : hash) out.append(String.format("%02x", b & 255)); return out.toString(); + } catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable"); } + } + public static final class Context { + private final String app, secret; + public final String fingerprint; + Context(String app, String secret, String fingerprint) { this.app = app; this.secret = secret; this.fingerprint = fingerprint; } + // Deliberately no toString/getters for credentials. + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java new file mode 100644 index 0000000..5a07f8f --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java @@ -0,0 +1,32 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FeishuTokenResponse { + private int code; + private String msg; + private TokenData data; + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class TokenData { + @JsonProperty("access_token") + private String accessToken; + + @JsonProperty("token_type") + private String tokenType; + + @JsonProperty("expires_in") + private int expiresIn; + + @JsonProperty("refresh_token") + private String refreshToken; + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuUserInfo.java b/src/main/java/com/finance/system/adapter/feishu/FeishuUserInfo.java new file mode 100644 index 0000000..1e181ff --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuUserInfo.java @@ -0,0 +1,13 @@ +package com.finance.system.adapter.feishu; + +import lombok.Data; + +@Data +public class FeishuUserInfo { + private String openId; + private String userId; + private String name; + private String avatarUrl; + private String email; + private String mobile; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java new file mode 100644 index 0000000..9e210d9 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java @@ -0,0 +1,33 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FeishuUserResponse { + private int code; + private String msg; + private UserData data; + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class UserData { + @JsonProperty("open_id") + private String openId; + + @JsonProperty("user_id") + private String userId; + + private String name; + private String email; + private String mobile; + + @JsonProperty("avatar_url") + private String avatarUrl; + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java new file mode 100644 index 0000000..ac92d86 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java @@ -0,0 +1,206 @@ +package com.finance.system.adapter.kingdee; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.finance.system.exception.BusinessException; +import com.finance.system.service.IntegrationConfigReader; +import com.finance.system.service.IntegrationConfigService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.web.client.RestTemplate; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +@RequiredArgsConstructor +public class KingdeeClient { + + private final KingdeeConfig kingdeeConfig; + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private String sessionToken; + private long sessionExpireTime = 0; + private String sessionConfigFingerprint; + private IntegrationConfigReader integrationConfigReader; + private IntegrationConfigService integrationConfigService; + + @Autowired(required = false) + public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) { + this.integrationConfigReader = integrationConfigReader; + } + + @Autowired(required = false) + public void setIntegrationConfigService(@Lazy IntegrationConfigService integrationConfigService) { + this.integrationConfigService = integrationConfigService; + } + + public boolean isEnabled() { + return (integrationConfigReader == null ? kingdeeConfig.isEnabled() : integrationConfigReader.isEnabled("KINGDEE")) + && hasText(baseUrl()); + } + + /** + * 登录金蝶云星空,获取Session + */ + public String login() { + if (!isEnabled()) throw new BusinessException("金蝶集成未启用或配置不完整"); + String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc"; + + Map requestBody = new HashMap<>(); + requestBody.put("acctID", dbId()); + requestBody.put("username", clientId()); + requestBody.put("password", clientSecret()); + requestBody.put("lcid", 2052); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity> request = new HttpEntity<>(requestBody, headers); + + 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"); + this.sessionExpireTime = System.currentTimeMillis() + 3600000; // 1小时过期 + this.sessionConfigFingerprint = configFingerprint(); + return this.sessionToken; + } + } + throw new BusinessException("金蝶登录失败: " + (body != null ? body.get("Message") : "未知错误")); + } catch (Exception e) { + log.error("金蝶云星空登录失败", e); + throw new BusinessException("金蝶云星空连接失败"); + } + } + + /** + * 获取有效的Session + */ + private String getValidSession() { + if (!isEnabled()) throw new BusinessException("金蝶集成未启用"); + if (sessionToken == null || System.currentTimeMillis() > sessionExpireTime + || !configFingerprint().equals(sessionConfigFingerprint)) { + sessionToken = null; + return login(); + } + return sessionToken; + } + + /** + * 保存单据(创建/更新) + */ + public Map save(String formId, Map data) { + String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc"; + return executeKingdeeApi(url, formId, data); + } + + /** + * 查看单据 + */ + public Map view(String formId, String billNo) { + String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc"; + + Map data = new HashMap<>(); + data.put("FormId", formId); + data.put("Number", billNo); + + HttpHeaders headers = buildHeaders(); + HttpEntity> request = new HttpEntity<>(data, headers); + + try { + ResponseEntity response = restTemplate.postForEntity(url, request, Map.class); + return response.getBody(); + } catch (Exception e) { + log.error("金蝶查看单据失败: formId={}, billNo={}", formId, billNo, e); + throw new BusinessException("金蝶单据查询失败"); + } + } + + /** + * 查询单据列表 + */ + public List> query(String formId, String filterString) { + String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Query.common.kdsvc"; + + Map data = new HashMap<>(); + data.put("FormId", formId); + data.put("FieldKeys", "*"); + data.put("FilterString", filterString); + data.put("OrderString", "FDate DESC"); + data.put("TopRowCount", 100); + + HttpHeaders headers = buildHeaders(); + HttpEntity> 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(); + } catch (Exception e) { + log.error("金蝶查询单据失败: formId={}", formId, e); + throw new BusinessException("金蝶单据查询失败"); + } + } + + /** + * 执行金蝶API调用 + */ + private Map executeKingdeeApi(String url, String formId, Map data) { + Map requestData = new HashMap<>(data); + requestData.put("FormId", formId); + + HttpHeaders headers = buildHeaders(); + HttpEntity> request = new HttpEntity<>(requestData, headers); + + try { + 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")); + } + return body; + } catch (Exception e) { + log.error("金蝶API调用失败: formId={}", formId, e); + throw new BusinessException("金蝶云星空操作失败"); + } + } + + private HttpHeaders buildHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("SessionId", getValidSession()); + return headers; + } + + private String baseUrl() { + String raw = configured("baseUrl", kingdeeConfig.getBaseUrl()); + if (!hasText(raw)) return raw; + if (integrationConfigService == null) { + throw new BusinessException("金蝶地址校验服务未配置,拒绝发起连接"); + } + return integrationConfigService.validateAndNormalizeKingdeeBaseUrl(raw); + } + private String clientId() { return configured("clientId", kingdeeConfig.getClientId()); } + private String clientSecret() { return configured("clientSecret", kingdeeConfig.getClientSecret()); } + private String dbId() { return configured("dbId", kingdeeConfig.getDbId()); } + private String configured(String key, String fallback) { return integrationConfigReader == null ? fallback : integrationConfigReader.get("KINGDEE", key); } + private boolean hasText(String value) { return value != null && !value.trim().isEmpty(); } + private String configFingerprint() { return String.valueOf(baseUrl()) + "\u0000" + String.valueOf(clientId()) + "\u0000" + String.valueOf(clientSecret()) + "\u0000" + String.valueOf(dbId()); } +} diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeConfig.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeConfig.java new file mode 100644 index 0000000..52ea4e1 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeConfig.java @@ -0,0 +1,16 @@ +package com.finance.system.adapter.kingdee; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "kingdee") +public class KingdeeConfig { + private boolean enabled; + private String baseUrl; + private String clientId; + private String clientSecret; + private String dbId; +} diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeSyncService.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeSyncService.java new file mode 100644 index 0000000..51ce529 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeSyncService.java @@ -0,0 +1,118 @@ +package com.finance.system.adapter.kingdee; + +import com.finance.system.entity.ReimApplication; +import com.finance.system.entity.ReimPayment; +import com.finance.system.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Service +@RequiredArgsConstructor +public class KingdeeSyncService { + + private final KingdeeClient kingdeeClient; + + /** + * 同步报销单到金蝶 + */ + public void syncExpenseReimbursement(ReimApplication application) { + if (!kingdeeClient.isEnabled()) return; + try { + Map data = buildReimbursementData(application); + Map result = kingdeeClient.save("FIN_EXPENSE_REIMBURSEMENT", data); + log.info("金蝶同步报销单成功: applicationNo={}", application.getApplicationNo()); + } catch (Exception e) { + log.error("金蝶同步报销单失败: applicationNo={}", application.getApplicationNo(), e); + throw new BusinessException("金蝶同步失败: " + e.getMessage()); + } + } + + /** + * 同步付款单到金蝶 + */ + public void syncPayment(ReimPayment payment) { + if (!kingdeeClient.isEnabled()) return; + try { + Map data = buildPaymentData(payment); + Map result = kingdeeClient.save("FIN_PAYMENT", data); + log.info("金蝶同步付款单成功: paymentNo={}", payment.getPaymentNo()); + } catch (Exception e) { + log.error("金蝶同步付款单失败: paymentNo={}", payment.getPaymentNo(), e); + throw new BusinessException("金蝶同步失败: " + e.getMessage()); + } + } + + /** + * 查询金蝶报销单状态 + */ + public Map queryReimbursementStatus(String billNo) { + try { + return kingdeeClient.view("FIN_EXPENSE_REIMBURSEMENT", billNo); + } catch (Exception e) { + log.error("查询金蝶报销单状态失败: billNo={}", billNo, e); + Map result = new HashMap<>(); + result.put("error", "金蝶查询失败"); + return result; + } + } + + /** + * 构建报销单数据 + */ + private Map buildReimbursementData(ReimApplication app) { + Map data = new HashMap<>(); + data.put("NeedReturnFields", new String[]{"FBillNo"}); + data.put("FBillNo", app.getApplicationNo()); + + Map model = new HashMap<>(); + model.put("FDate", app.getSubmitTime() != null ? + app.getSubmitTime().toString() : java.time.LocalDate.now().toString()); + model.put("FBillTypeID", new MapBuilder() + .put("FNUMBER", "EXP_REIM").build()); + model.put("FApplicationAmount", app.getTotalAmount()); + model.put("FDescription", app.getDescription()); + + data.put("Model", model); + return data; + } + + /** + * 构建付款单数据 + */ + private Map buildPaymentData(ReimPayment payment) { + Map data = new HashMap<>(); + data.put("NeedReturnFields", new String[]{"FBillNo"}); + data.put("FBillNo", payment.getPaymentNo()); + + Map model = new HashMap<>(); + model.put("FDate", java.time.LocalDate.now().toString()); + model.put("FBillTypeID", new MapBuilder() + .put("FNUMBER", "PAYMENT").build()); + model.put("FPaymentAmount", payment.getPaymentAmount()); + model.put("FRemark", payment.getRemark()); + + data.put("Model", model); + return data; + } + + /** + * 简易Map构建器 + */ + private static class MapBuilder { + private final Map map = new HashMap<>(); + + public MapBuilder put(String key, Object value) { + map.put(key, value); + return this; + } + + public Map build() { + return map; + } + } +} diff --git a/src/main/java/com/finance/system/config/JwtConfig.java b/src/main/java/com/finance/system/config/JwtConfig.java new file mode 100644 index 0000000..9570594 --- /dev/null +++ b/src/main/java/com/finance/system/config/JwtConfig.java @@ -0,0 +1,167 @@ +package com.finance.system.config; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import lombok.Getter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.SecretKey; +import javax.annotation.PostConstruct; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; +import java.nio.charset.StandardCharsets; + +@Component +public class JwtConfig { + + private static final int MIN_SECRET_BYTES = 32; + + @Getter + @Value("${jwt.secret}") + private String secret; + + @Getter + @Value("${jwt.expiration}") + private long expiration; + + /** + * Time zone used to determine the next natural-day boundary for a token. + * This is deliberately a ZoneId rather than a fixed offset so that zones + * observing daylight-saving time are handled correctly. + */ + @Value("${auth.time-zone:Asia/Shanghai}") + private String timeZone = "Asia/Shanghai"; + + @PostConstruct + void validateConfiguration() { + validateSecretValue(secret); + validateExpirationValue(expiration); + getAuthZoneId(); + } + + static void validateSecretValue(String secret) { + if (!StringUtils.hasText(secret) + || secret.getBytes(StandardCharsets.UTF_8).length < MIN_SECRET_BYTES) { + throw new IllegalStateException( + "JWT_SECRET must not be blank and must contain at least 32 UTF-8 bytes"); + } + } + + static void validateExpirationValue(long expiration) { + if (expiration <= 0) { + throw new IllegalStateException("JWT_EXPIRATION must be strictly positive"); + } + } + + private SecretKey getSigningKey() { + validateSecretValue(secret); + byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8); + return Keys.hmacShaKeyFor(keyBytes); + } + + public String generateToken(Long userId, String employeeNo, String realName, String userType) { + return generateTokenWithTtl(userId, employeeNo, realName, userType).getToken(); + } + + /** + * Generates a token whose lifetime ends at the earlier of the next local + * midnight and jwt.expiration. Returning the lifetime together with the + * token keeps the API response in sync with the token that was generated. + */ + public GeneratedToken generateTokenWithTtl(Long userId, String employeeNo, + String realName, String userType) { + Instant issuedAt = Instant.now(); + long ttl = calculateTokenTtlMillis(issuedAt, getAuthZoneId(), expiration); + Instant expiresAt = issuedAt.plusMillis(ttl); + + String token = Jwts.builder() + .claim("userId", userId) + .claim("employeeNo", employeeNo) + .claim("realName", realName) + .claim("userType", userType) + .setSubject(String.valueOf(userId)) + .setIssuedAt(Date.from(issuedAt)) + .setExpiration(Date.from(expiresAt)) + .signWith(getSigningKey(), io.jsonwebtoken.SignatureAlgorithm.HS256) + .compact(); + + return new GeneratedToken(token, ttl); + } + + /** Returns the lifetime a token generated at this instant would receive. */ + public long getTokenTtlMillis() { + return calculateTokenTtlMillis(Instant.now(), getAuthZoneId(), expiration); + } + + public ZoneId getAuthZoneId() { + return ZoneId.of(timeZone); + } + + /** Visible for focused tests and kept free of wall-clock dependencies. */ + static Instant nextMidnight(Instant instant, ZoneId zoneId) { + ZonedDateTime localTime = instant.atZone(zoneId); + return localTime.toLocalDate().plusDays(1).atStartOfDay(zoneId).toInstant(); + } + + /** + * Calculates a positive TTL in milliseconds. The maximum expiration is + * retained as a hard upper bound even when the local day is longer than it. + */ + static long calculateTokenTtlMillis(Instant instant, ZoneId zoneId, long maximumExpiration) { + validateExpirationValue(maximumExpiration); + long untilMidnight = Duration.between(instant, nextMidnight(instant, zoneId)).toMillis(); + return Math.min(maximumExpiration, Math.max(1L, untilMidnight)); + } + + public static final class GeneratedToken { + private final String token; + private final long expiresIn; + + private GeneratedToken(String token, long expiresIn) { + this.token = token; + this.expiresIn = expiresIn; + } + + public String getToken() { + return token; + } + + public long getExpiresIn() { + return expiresIn; + } + } + + public Claims parseToken(String token) { + return Jwts.parserBuilder() + .setSigningKey(getSigningKey()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + public boolean validateToken(String token) { + try { + Claims claims = parseToken(token); + return !claims.getExpiration().before(new Date()); + } catch (Exception e) { + return false; + } + } + + public Long getUserIdFromToken(String token) { + Claims claims = parseToken(token); + Object value = claims.get("userId"); + return value instanceof Number ? ((Number) value).longValue() : Long.valueOf(String.valueOf(value)); + } + + public String getUserTypeFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("userType", String.class); + } +} diff --git a/src/main/java/com/finance/system/config/LocalDataInitializer.java b/src/main/java/com/finance/system/config/LocalDataInitializer.java new file mode 100644 index 0000000..f421129 --- /dev/null +++ b/src/main/java/com/finance/system/config/LocalDataInitializer.java @@ -0,0 +1,104 @@ +package com.finance.system.config; + +import com.finance.system.entity.SysApprovalNode; +import com.finance.system.entity.SysBankAccount; +import com.finance.system.entity.SysDepartment; +import com.finance.system.entity.SysExpenseType; +import com.finance.system.entity.SysUser; +import com.finance.system.repository.SysApprovalNodeRepository; +import com.finance.system.repository.SysBankAccountRepository; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.repository.SysExpenseTypeRepository; +import com.finance.system.repository.SysUserRepository; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Profile; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +/** Safe, deterministic local-only seed data. Production never runs this component. */ +@Component +@Profile("local") +public class LocalDataInitializer implements CommandLineRunner { + private final SysUserRepository users; + private final SysDepartmentRepository departments; + private final SysExpenseTypeRepository expenseTypes; + private final SysBankAccountRepository bankAccounts; + private final SysApprovalNodeRepository nodes; + private final PasswordEncoder passwordEncoder; + + public LocalDataInitializer(SysUserRepository users, SysDepartmentRepository departments, + SysExpenseTypeRepository expenseTypes, SysBankAccountRepository bankAccounts, + SysApprovalNodeRepository nodes, + PasswordEncoder passwordEncoder) { + this.users = users; + this.departments = departments; + this.expenseTypes = expenseTypes; + this.bankAccounts = bankAccounts; + this.nodes = nodes; + this.passwordEncoder = passwordEncoder; + } + + @Override + public void run(String... args) { + if (users.findByEmployeeNo("E1001") != null) return; + + SysDepartment department = new SysDepartment(); + department.setDeptCode("FIN"); + department.setDeptName("财务与行政部"); + department.setSortOrder(1); + department.setStatus("ACTIVE"); + department = departments.save(department); + + SysUser employee = user("E1001", "本地员工", "EMPLOYEE", "员工", department.getId()); + employee = users.save(employee); + users.save(user("E1002", "本地员工二", "EMPLOYEE", "员工", department.getId())); + users.save(user("F2001", "应付会计", "FINANCE", "应付会计", department.getId())); + users.save(user("M3001", "财务经理", "FINANCE", "财务经理", department.getId())); + users.save(user("A9001", "系统管理员", "ADMIN", "管理员", department.getId())); + + SysExpenseType type = new SysExpenseType(); + type.setTypeCode("TRAVEL"); + type.setTypeName("差旅费"); + type.setCategory("费用"); + type.setSortOrder(1); + type.setStatus("ACTIVE"); + expenseTypes.save(type); + + SysBankAccount bank = new SysBankAccount(); + bank.setUserId(employee.getId()); + bank.setBankName("本地测试银行"); + bank.setBranchName("测试支行"); + bank.setAccountNo("6222000000001001"); + bank.setAccountNoMask("************1001"); + bank.setAccountName(employee.getRealName()); + bank.setIsDefault(true); + bank.setStatus("ACTIVE"); + bankAccounts.save(bank); + + nodes.save(node("NODE_AP", "应付会计审核", "ACCOUNTS_PAYABLE", 1)); + nodes.save(node("NODE_MANAGER", "财务经理审批", "FINANCE_MANAGER", 2)); + } + + private SysUser user(String number, String name, String type, String position, Long departmentId) { + SysUser user = new SysUser(); + user.setEmployeeNo(number); + user.setRealName(name); + user.setUserType(type); + user.setPosition(position); + user.setDepartmentId(departmentId); + user.setPasswordHash(passwordEncoder.encode("local-password")); + user.setStatus("ACTIVE"); + return user; + } + + private SysApprovalNode node(String code, String name, String role, int order) { + SysApprovalNode node = new SysApprovalNode(); + node.setNodeCode(code); + node.setNodeName(name); + node.setApproverType("ROLE"); + node.setApproverRole(role); + node.setSortOrder(order); + node.setStatus("ACTIVE"); + return node; + } +} diff --git a/src/main/java/com/finance/system/config/SecurityConfig.java b/src/main/java/com/finance/system/config/SecurityConfig.java new file mode 100644 index 0000000..437e440 --- /dev/null +++ b/src/main/java/com/finance/system/config/SecurityConfig.java @@ -0,0 +1,76 @@ +package com.finance.system.config; + +import com.finance.system.security.JwtAuthenticationFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +import javax.servlet.http.HttpServletResponse; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final JwtAuthenticationFilter jwtAuthenticationFilter; + private final Environment environment; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http, com.fasterxml.jackson.databind.ObjectMapper mapper) throws Exception { + http + .csrf(AbstractHttpConfigurer::disable) + .cors(cors -> {}) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> { + if (isLocalProfile()) { + auth.antMatchers("/api/auth/login").permitAll(); + } + auth + .antMatchers("/api/auth/feishu-login").permitAll() + .antMatchers("/api/feishu/auth-url", "/api/feishu/callback", "/api/feishu/webhook", "/api/feishu/login").permitAll() + .antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll() + .antMatchers("/actuator/health").permitAll() + .antMatchers("/h2-console/**").permitAll() + .antMatchers("/api/**").authenticated() + .anyRequest().permitAll(); + }) + .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint( + (request, response, exception) -> { + if (request.getServletPath().startsWith("/api/feishu/directory/")) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType("application/json;charset=UTF-8"); + mapper.writeValue(response.getOutputStream(), com.finance.system.dto.ApiResponse.error(401, "Authentication required")); + } else response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录或登录已过期"); + } + )) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); + + return http.build(); + } + + private boolean isLocalProfile() { + for (String profile : environment.getActiveProfiles()) { + if ("local".equalsIgnoreCase(profile)) { + return true; + } + } + return false; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/com/finance/system/config/WebConfig.java b/src/main/java/com/finance/system/config/WebConfig.java new file mode 100644 index 0000000..18beb36 --- /dev/null +++ b/src/main/java/com/finance/system/config/WebConfig.java @@ -0,0 +1,49 @@ +package com.finance.system.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.client.RestTemplate; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.Arrays; +import java.util.Collections; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Value("${app.frontend-url:http://localhost:5173}") + private String frontendUrl; + + @Bean + public CorsFilter corsFilter() { + CorsConfiguration config = new CorsConfiguration(); + if (frontendUrl != null && !frontendUrl.trim().isEmpty()) { + config.setAllowedOrigins(Collections.singletonList(frontendUrl.trim())); + } else { + // An empty origin configuration disables cross-origin requests; + // never weaken this to a wildcard when credentials are enabled. + config.setAllowedOrigins(Collections.emptyList()); + } + config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); + config.setAllowedHeaders(Arrays.asList("*")); + config.setAllowCredentials(true); + config.setMaxAge(3600L); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/api/**", config); + return new CorsFilter(source); + } + + @Bean + public RestTemplate restTemplate() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(5000); + factory.setReadTimeout(10000); + return new RestTemplate(factory); + } +} diff --git a/src/main/java/com/finance/system/controller/AccountsPayableController.java b/src/main/java/com/finance/system/controller/AccountsPayableController.java new file mode 100644 index 0000000..7cd36f4 --- /dev/null +++ b/src/main/java/com/finance/system/controller/AccountsPayableController.java @@ -0,0 +1,64 @@ +package com.finance.system.controller; + +import com.finance.system.dto.*; +import com.finance.system.service.ReimApplicationService; +import com.finance.system.service.ReimApprovalService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/accounts-payable") +@RequiredArgsConstructor +@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") +public class AccountsPayableController { + + private final ReimApplicationService reimApplicationService; + private final ReimApprovalService reimApprovalService; + + @GetMapping("/tasks") + public ResponseEntity>> getTasks( + @RequestParam(defaultValue = "PENDING") String status, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + Pageable pageable = PageRequest.of(page, size); + Page tasks = reimApplicationService.getAccountsPayableTasks(status, pageable); + return ResponseEntity.ok(ApiResponse.success(PageResponse.of( + tasks.getContent(), tasks.getTotalElements(), page, size))); + } + + @GetMapping("/tasks/{id}") + public ResponseEntity> getTaskDetail(@PathVariable Long id) { + ReimApplicationDetail detail = reimApplicationService.getApplicationDetail(id, AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @PostMapping("/approve") + public ResponseEntity> approve(@RequestBody ApprovalActionRequest request) { + Long userId = AuditUtil.getCurrentUserId(); + reimApprovalService.approve(request.getApplicationId(), userId, request.getComment()); + return ResponseEntity.ok(ApiResponse.success()); + } + + @PostMapping("/reject") + public ResponseEntity> reject(@RequestBody ApprovalActionRequest request) { + Long userId = AuditUtil.getCurrentUserId(); + reimApprovalService.reject(request.getApplicationId(), userId, + request.getComment(), request.getReturnReason()); + return ResponseEntity.ok(ApiResponse.success()); + } + + @GetMapping("/history") + public ResponseEntity>> getHistory() { + Long userId = AuditUtil.getCurrentUserId(); + List history = reimApprovalService.getApprovalHistoryByUser(userId); + return ResponseEntity.ok(ApiResponse.success(history)); + } +} diff --git a/src/main/java/com/finance/system/controller/ApplicationController.java b/src/main/java/com/finance/system/controller/ApplicationController.java new file mode 100644 index 0000000..2bd764a --- /dev/null +++ b/src/main/java/com/finance/system/controller/ApplicationController.java @@ -0,0 +1,268 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.*; + +@Slf4j +@RestController +@RequestMapping("/api/applications") +@RequiredArgsConstructor +public class ApplicationController { + + /** + * Mock数据 - 付款申请列表 + * 对应原型中的员工报销数据(员工报销类) + */ + private static final List> MOCK_APPLICATIONS = new ArrayList<>(); + + static { + Map a1 = new LinkedHashMap<>(); + a1.put("id", 1L); + a1.put("applicationNo", "BX20260812001"); + a1.put("date", "2026-08-12"); + a1.put("title", "上海客户现场技术交流差旅"); + a1.put("type", "费用报销"); + a1.put("subtype", "差旅交通"); + a1.put("payee", "李志豪"); + a1.put("amount", new BigDecimal("3286.50")); + a1.put("owner", "李志豪"); + a1.put("department", "销售中心"); + a1.put("applicationStatus", "退回"); + a1.put("receiptStatus", "未触发"); + a1.put("paymentStatus", "未付款"); + a1.put("budgetStatus", "已占用"); + a1.put("approvalNode", "申请人补充材料"); + a1.put("approver", "李志豪"); + a1.put("expenseType", "员工报销类"); + MOCK_APPLICATIONS.add(a1); + + Map a2 = new LinkedHashMap<>(); + a2.put("id", 2L); + a2.put("applicationNo", "BX20260809003"); + a2.put("date", "2026-08-09"); + a2.put("title", "八月客户拜访交通费"); + a2.put("type", "费用报销"); + a2.put("subtype", "交通费"); + a2.put("payee", "李志豪"); + a2.put("amount", new BigDecimal("1260.00")); + a2.put("owner", "李志豪"); + a2.put("department", "销售中心"); + a2.put("applicationStatus", "审批中"); + a2.put("receiptStatus", "未触发"); + a2.put("paymentStatus", "未付款"); + a2.put("budgetStatus", "已占用"); + a2.put("approvalNode", "应付会计审核"); + a2.put("approver", "刘雅"); + a2.put("expenseType", "员工报销类"); + MOCK_APPLICATIONS.add(a2); + + Map a3 = new LinkedHashMap<>(); + a3.put("id", 3L); + a3.put("applicationNo", "BX20260808006"); + a3.put("date", "2026-08-08"); + a3.put("title", "研发现场餐费报销"); + a3.put("type", "费用报销"); + a3.put("subtype", "业务招待"); + a3.put("payee", "王忠辉"); + a3.put("amount", new BigDecimal("680.00")); + a3.put("owner", "王忠辉"); + a3.put("department", "数字化中心"); + a3.put("applicationStatus", "审批中"); + a3.put("receiptStatus", "未触发"); + a3.put("paymentStatus", "未付款"); + a3.put("budgetStatus", "已占用"); + a3.put("approvalNode", "财务经理审批"); + a3.put("approver", "周岚"); + a3.put("expenseType", "员工报销类"); + MOCK_APPLICATIONS.add(a3); + + Map a4 = new LinkedHashMap<>(); + a4.put("id", 4L); + a4.put("applicationNo", "BX20260802011"); + a4.put("date", "2026-08-02"); + a4.put("title", "苏州园区客户拜访费用"); + a4.put("type", "费用报销"); + a4.put("subtype", "交通费"); + a4.put("payee", "赵海峰"); + a4.put("amount", new BigDecimal("2180.00")); + a4.put("owner", "赵海峰"); + a4.put("department", "供应链中心"); + a4.put("applicationStatus", "审批通过"); + a4.put("receiptStatus", "待收单"); + a4.put("paymentStatus", "未付款"); + a4.put("budgetStatus", "已转执行"); + a4.put("approvalNode", "流程已完成"); + a4.put("approver", "—"); + a4.put("expenseType", "员工报销类"); + MOCK_APPLICATIONS.add(a4); + + Map a5 = new LinkedHashMap<>(); + a5.put("id", 5L); + a5.put("applicationNo", "BX20260801009"); + a5.put("date", "2026-08-01"); + a5.put("title", "七月云资源差旅补贴"); + a5.put("type", "费用报销"); + a5.put("subtype", "差旅补贴"); + a5.put("payee", "王忠辉"); + a5.put("amount", new BigDecimal("3200.00")); + a5.put("owner", "王忠辉"); + a5.put("department", "数字化中心"); + a5.put("applicationStatus", "审批通过"); + a5.put("receiptStatus", "已收单"); + a5.put("paymentStatus", "未付款"); + a5.put("budgetStatus", "已转执行"); + a5.put("approvalNode", "流程已完成"); + a5.put("approver", "—"); + a5.put("expenseType", "员工报销类"); + MOCK_APPLICATIONS.add(a5); + + Map a6 = new LinkedHashMap<>(); + a6.put("id", 6L); + a6.put("applicationNo", "BX20260728004"); + a6.put("date", "2026-07-28"); + a6.put("title", "上海项目住宿费"); + a6.put("type", "费用报销"); + a6.put("subtype", "住宿费"); + a6.put("payee", "赵海峰"); + a6.put("amount", new BigDecimal("4100.00")); + a6.put("owner", "赵海峰"); + a6.put("department", "供应链中心"); + a6.put("applicationStatus", "审批通过"); + a6.put("receiptStatus", "已收单"); + a6.put("paymentStatus", "部分付款"); + a6.put("budgetStatus", "已转执行"); + a6.put("approvalNode", "流程已完成"); + a6.put("approver", "—"); + a6.put("expenseType", "员工报销类"); + MOCK_APPLICATIONS.add(a6); + } + + /** + * 获取付款申请列表(应付会计B视图,过滤 expenseType=员工报销类) + */ + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity>>> listApplications( + @RequestParam(required = false) String status, + @RequestParam(required = false) String expenseType) { + try { + List> result = new ArrayList<>(MOCK_APPLICATIONS); + + // 默认过滤 expenseType=员工报销类 + if (expenseType != null && !expenseType.isEmpty()) { + result.removeIf(app -> !expenseType.equals(app.get("expenseType"))); + } else { + result.removeIf(app -> !"员工报销类".equals(app.get("expenseType"))); + } + + // 按状态过滤 + if (status != null && !status.isEmpty()) { + result.removeIf(app -> !status.equals(app.get("applicationStatus"))); + } + + return ResponseEntity.ok(ApiResponse.success(result)); + } catch (Exception e) { + log.error("获取付款申请列表失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "获取付款申请列表失败: " + e.getMessage())); + } + } + + /** + * 获取付款申请详情 + */ + @GetMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity>> getApplicationDetail(@PathVariable Long id) { + try { + Map application = MOCK_APPLICATIONS.stream() + .filter(a -> id.equals(a.get("id"))) + .findFirst() + .orElse(null); + + if (application == null) { + return ResponseEntity.status(404) + .body(ApiResponse.error(404, "申请单不存在: " + id)); + } + + // 追加详细信息 + Map detail = new LinkedHashMap<>(application); + detail.put("bankName", "中国工商银行苏州新区支行"); + detail.put("bankAccount", "6222 **** 0086 0728"); + detail.put("description", getDescriptionById(id)); + detail.put("invoices", getInvoicesById(id)); + detail.put("attachments", getAttachmentsById(id)); + detail.put("returnReason", getReturnReasonById(id)); + detail.put("lastUpdated", "2026-08-12 10:24"); + + return ResponseEntity.ok(ApiResponse.success(detail)); + } catch (Exception e) { + log.error("获取申请详情失败: id={}", id, e); + return ResponseEntity.ok(ApiResponse.error(500, "获取申请详情失败: " + e.getMessage())); + } + } + + private String getDescriptionById(Long id) { + if (id == 1L) return "上海客户现场技术交流产生的交通及住宿费用。"; + if (id == 2L) return "客户拜访交通费用。"; + if (id == 3L) return "研发现场支持期间的工作餐费用。"; + if (id == 4L) return "园区客户拜访交通与停车费用。"; + if (id == 5L) return "七月现场支持差旅补贴。"; + if (id == 6L) return "上海项目住宿费用。"; + return ""; + } + + private List> getInvoicesById(Long id) { + List> invoices = new ArrayList<>(); + if (id == 2L) { + Map inv = new LinkedHashMap<>(); + inv.put("number", "03300260011142888901"); + inv.put("amount", new BigDecimal("1260.00")); + inv.put("file", "出租车发票_08月.pdf"); + invoices.add(inv); + } + if (id == 4L) { + Map inv = new LinkedHashMap<>(); + inv.put("number", "03300260011142887771"); + inv.put("amount", new BigDecimal("2180.00")); + inv.put("file", "停车及交通发票.pdf"); + invoices.add(inv); + } + if (id == 6L) { + Map inv = new LinkedHashMap<>(); + inv.put("number", "03300260011142885550"); + inv.put("amount", new BigDecimal("4100.00")); + inv.put("file", "住宿发票.pdf"); + invoices.add(inv); + } + return invoices; + } + + private List> getAttachmentsById(Long id) { + List> attachments = new ArrayList<>(); + if (id == 1L) { + Map att1 = new LinkedHashMap<>(); + att1.put("type", "出差申请"); + att1.put("name", "出差申请_上海客户现场.pdf"); + attachments.add(att1); + Map att2 = new LinkedHashMap<>(); + att2.put("type", "行程证明"); + att2.put("name", "高铁行程单.pdf"); + attachments.add(att2); + } + return attachments; + } + + private String getReturnReasonById(Long id) { + if (id == 1L) return "请补充住宿发票影像,并说明住宿日期。"; + return null; + } +} diff --git a/src/main/java/com/finance/system/controller/AuthController.java b/src/main/java/com/finance/system/controller/AuthController.java new file mode 100644 index 0000000..9d063cb --- /dev/null +++ b/src/main/java/com/finance/system/controller/AuthController.java @@ -0,0 +1,332 @@ +package com.finance.system.controller; + +import com.finance.system.adapter.feishu.FeishuAuthService; +import com.finance.system.adapter.feishu.FeishuTokenResponse; +import com.finance.system.adapter.feishu.FeishuUserInfo; +import com.finance.system.config.JwtConfig; +import com.finance.system.dto.*; +import com.finance.system.entity.SysUser; +import com.finance.system.entity.SysDepartment; +import com.finance.system.enums.UserType; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.security.UserPrincipal; +import com.finance.system.service.RoleService; +import com.finance.system.util.AuditUtil; +import javax.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/api/auth") +@RequiredArgsConstructor +public class AuthController { + + private final SysUserRepository sysUserRepository; + private final SysDepartmentRepository sysDepartmentRepository; + private final JwtConfig jwtConfig; + private final FeishuAuthService feishuAuthService; + private final Environment environment; + private final PasswordEncoder passwordEncoder; + private RoleService roleService; + @Autowired + private com.finance.system.adapter.feishu.FeishuDirectoryAccessService directoryAccess; + @Autowired + private com.finance.system.adapter.feishu.FeishuLoginPersistenceService loginPersistence; + + @Autowired(required = false) + public void setRoleService(RoleService roleService) { + this.roleService = roleService; + } + + @PostMapping("/login") + public ResponseEntity> login(@Valid @RequestBody LoginRequest request) { + if (!isLocalProfile()) { + return ResponseEntity.status(403) + .body(ApiResponse.error(403, "生产环境必须使用飞书登录,密码登录仅允许 local 环境")); + } + + SysUser user = sysUserRepository.findByEmployeeNo(request.getEmployeeNo()); + if (user == null) { + return ResponseEntity.status(401) + .body(ApiResponse.error(401, "用户不存在")); + } + + if (request.getPassword() == null || request.getPassword().trim().isEmpty() + || user.getPasswordHash() == null + || user.getPasswordHash().trim().isEmpty() + || !passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) { + return ResponseEntity.status(401) + .body(ApiResponse.error(401, "员工编号或密码错误")); + } + + if (!"ACTIVE".equalsIgnoreCase(user.getStatus())) { + return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); + } + + directoryAccess.requireAllowed(user); + + user = loginPersistence.completeLocal(user.getId()); + + JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( + user.getId(), user.getEmployeeNo(), + user.getRealName(), RoleService.normalize(user.getUserType())); + + UserProfile profile = buildUserProfile(user); + + LoginResponse loginResponse = LoginResponse.builder() + .token(generatedToken.getToken()) + .tokenType("Bearer") + .expiresIn(generatedToken.getExpiresIn()) + .user(profile) + .build(); + + return ResponseEntity.ok(ApiResponse.success(loginResponse)); + } + + private boolean isLocalProfile() { + for (String profile : environment.getActiveProfiles()) { + if ("local".equalsIgnoreCase(profile)) return true; + } + return false; + } + + @PostMapping("/feishu-login") + public ResponseEntity> feishuLogin( + @RequestBody Map request, + @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { + String code = request.get("code"); + String state = request.get("state"); + if (code == null || code.isEmpty()) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "授权码不能为空")); + } + + feishuAuthService.validateCallbackState(state, browserState, true); + + FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code); + FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo( + tokenResponse.getData().getAccessToken()); + + SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo); + if (!isActive(user)) { + return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); + } + + JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( + user.getId(), user.getEmployeeNo(), + user.getRealName(), RoleService.normalize(user.getUserType())); + + UserProfile profile = buildUserProfile(user); + + LoginResponse loginResponse = LoginResponse.builder() + .token(generatedToken.getToken()) + .tokenType("Bearer") + .expiresIn(generatedToken.getExpiresIn()) + .user(profile) + .build(); + + return ResponseEntity.ok(ApiResponse.success(loginResponse)); + } + + @GetMapping("/me") + public ResponseEntity> getCurrentUser() { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null) { + return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录")); + } + + SysUser user = sysUserRepository.findById(principal.getId()) + .orElse(null); + if (user == null) { + return ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在")); + } + + return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user))); + } + + @PostMapping("/refresh") + public ResponseEntity> refreshToken() { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null) { + return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录")); + } + + SysUser user = sysUserRepository.findById(principal.getId()).orElse(null); + if (user == null) { + return ResponseEntity.status(401).body(ApiResponse.error(401, "用户不存在")); + } + if (!isActive(user)) { + return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); + } + JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( + user.getId(), user.getEmployeeNo(), + user.getRealName(), RoleService.normalize(user.getUserType())); + + LoginResponse loginResponse = LoginResponse.builder() + .token(generatedToken.getToken()) + .tokenType("Bearer") + .expiresIn(generatedToken.getExpiresIn()) + .user(buildUserProfile(user)) + .build(); + + return ResponseEntity.ok(ApiResponse.success(loginResponse)); + } + + @PostMapping("/logout") + public ResponseEntity> logout() { + return ResponseEntity.ok(ApiResponse.success()); + } + + /** + * 获取所有用户列表 + */ + @GetMapping("/users") + @PreAuthorize("@permissionChecker.has(authentication, 'system:user:view')") + public ResponseEntity>> listUsers() { + List users = sysUserRepository.findAll(); + List profiles = users.stream() + .map(this::buildUserProfile) + .collect(Collectors.toList()); + return ResponseEntity.ok(ApiResponse.success(profiles)); + } + + /** + * 更新用户角色 + */ + @PutMapping("/users/{id}/role") + @PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')") + public ResponseEntity> 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))); + } + + /** + * 切换用户状态 + */ + @PutMapping("/users/{id}/status") + @PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')") + public ResponseEntity> toggleUserStatus( + @PathVariable Long id, + @RequestBody Map request) { + String newStatus = request.get("status"); + if (newStatus == null || newStatus.trim().isEmpty()) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "状态不能为空")); + } + + String normalizedStatus = newStatus.trim().toUpperCase(Locale.ROOT); + if (!"ACTIVE".equals(normalizedStatus) && !"INACTIVE".equals(normalizedStatus)) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "状态必须是 ACTIVE 或 INACTIVE")); + } + if (id.equals(AuditUtil.getCurrentUserId()) && "INACTIVE".equals(normalizedStatus)) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "不能停用当前登录账号")); + } + + SysUser user = sysUserRepository.findById(id).orElse(null); + if (user == null) { + return ResponseEntity.status(404) + .body(ApiResponse.error(404, "用户不存在")); + } + + user.setStatus(normalizedStatus); + sysUserRepository.save(user); + + return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user))); + } + + /** Replaces direct role assignments; groups are intentionally managed by the group API. */ + @PutMapping("/users/{id}/roles") + @PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')") + public ResponseEntity> 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))); + } + + private UserProfile buildUserProfile(SysUser user) { + String deptName = null; + if (user.getDepartmentId() != null) { + SysDepartment dept = sysDepartmentRepository.findById(user.getDepartmentId()).orElse(null); + if (dept != null) { + deptName = dept.getDeptName(); + } + } + + return UserProfile.builder() + .id(user.getId()) + .employeeNo(user.getEmployeeNo()) + .realName(user.getRealName()) + .avatarUrl(user.getAvatarUrl()) + .email(user.getEmail()) + .departmentName(deptName) + .position(user.getPosition()) + .userType(RoleService.normalize(user.getUserType())) + .status(user.getStatus()) + .feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定") + .lastLoginAt(user.getLastLoginAt() != null ? user.getLastLoginAt().toString().replace("T", " ") : null) + .roleCodes(roleService == null ? Collections.singletonList(RoleService.normalize(user.getUserType())) : roleService.userRoleCodes(user.getId())) + .groupNames(roleService == null ? Collections.emptyList() : roleService.userGroupNames(user.getId())) + .build(); + } + + private boolean isActive(SysUser user) { + return user != null && "ACTIVE".equalsIgnoreCase(user.getStatus()); + } +} diff --git a/src/main/java/com/finance/system/controller/CashierController.java b/src/main/java/com/finance/system/controller/CashierController.java new file mode 100644 index 0000000..8374a9b --- /dev/null +++ b/src/main/java/com/finance/system/controller/CashierController.java @@ -0,0 +1,93 @@ +package com.finance.system.controller; + +import com.finance.system.dto.*; +import com.finance.system.exception.BusinessException; +import com.finance.system.service.ReimPaymentService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/v1/cashier") +@RequiredArgsConstructor +@PreAuthorize("@permissionChecker.has(authentication, 'payment:register')") +public class CashierController { + + private final ReimPaymentService reimPaymentService; + + @GetMapping("/tasks") + public ResponseEntity>> getTasks( + @RequestParam(defaultValue = "UNPAID") String status, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + Long userId = AuditUtil.getCurrentUserId(); + Pageable pageable = PageRequest.of(page, size); + Page tasks = reimPaymentService.getPendingPayments(userId, pageable); + return ResponseEntity.ok(ApiResponse.success(PageResponse.of( + tasks.getContent(), tasks.getTotalElements(), page, size))); + } + + @GetMapping("/tasks/{id}") + public ResponseEntity> getTaskDetail(@PathVariable Long id) { + PaymentDetailDto detail = reimPaymentService.getPaymentDetail(id, AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @PostMapping("/pay") + public ResponseEntity> executePayment( + @RequestBody CreatePaymentRequest request, + @RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) { + Long userId = AuditUtil.getCurrentUserId(); + String resolvedIdempotencyKey = resolveIdempotencyKey(idempotencyKey, request.getIdempotencyKey()); + PaymentResultDto result = reimPaymentService.executePayment(request.getApplicationId(), + request.getPaymentAmount(), userId, request.getPaymentMethod(), request.getReferenceNo(), + request.getRemark(), resolvedIdempotencyKey); + return ResponseEntity.ok(ApiResponse.success(result)); + } + + @PostMapping("/partial-pay") + public ResponseEntity> processPartialPayment( + @RequestBody CreatePaymentRequest request, + @RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) { + Long applicationId = request.getApplicationId(); + BigDecimal amount = request.getPaymentAmount(); + Long userId = AuditUtil.getCurrentUserId(); + String resolvedIdempotencyKey = resolveIdempotencyKey(idempotencyKey, request.getIdempotencyKey()); + PaymentResultDto result = reimPaymentService.processPartialPayment(applicationId, amount, userId, + request.getPaymentMethod(), request.getReferenceNo(), request.getRemark(), resolvedIdempotencyKey); + return ResponseEntity.ok(ApiResponse.success(result)); + } + + @GetMapping("/history") + public ResponseEntity>> getPaymentHistory() { + Long userId = AuditUtil.getCurrentUserId(); + List history = reimPaymentService.getPaymentHistoryByOperator(userId); + return ResponseEntity.ok(ApiResponse.success(history)); + } + + @GetMapping("/payments/{paymentNo}") + 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())) { + throw new BusinessException("Header 与 body 的幂等键不一致", 409); + } + if (hasHeader) return headerValue.trim(); + return hasBody ? bodyValue.trim() : null; + } +} diff --git a/src/main/java/com/finance/system/controller/DashboardController.java b/src/main/java/com/finance/system/controller/DashboardController.java new file mode 100644 index 0000000..3acd851 --- /dev/null +++ b/src/main/java/com/finance/system/controller/DashboardController.java @@ -0,0 +1,38 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.dto.DashboardStats; +import com.finance.system.dto.ReimApplicationSummary; +import com.finance.system.service.DashboardService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/dashboard") +@RequiredArgsConstructor +public class DashboardController { + + private final DashboardService dashboardService; + + @GetMapping("/stats") + @PreAuthorize("@permissionChecker.has(authentication, 'dashboard')") + public ResponseEntity> getStats() { + Long userId = AuditUtil.getCurrentUserId(); + DashboardStats stats = dashboardService.getDashboardStats(userId); + return ResponseEntity.ok(ApiResponse.success(stats)); + } + + @GetMapping("/recent") + @PreAuthorize("@permissionChecker.has(authentication, 'dashboard')") + public ResponseEntity>> getRecent( + @RequestParam(defaultValue = "5") int limit) { + Long userId = AuditUtil.getCurrentUserId(); + List recent = dashboardService.getRecentApplications(userId, limit); + return ResponseEntity.ok(ApiResponse.success(recent)); + } +} diff --git a/src/main/java/com/finance/system/controller/FeishuAuthController.java b/src/main/java/com/finance/system/controller/FeishuAuthController.java new file mode 100644 index 0000000..9a8bdd9 --- /dev/null +++ b/src/main/java/com/finance/system/controller/FeishuAuthController.java @@ -0,0 +1,298 @@ +package com.finance.system.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.finance.system.adapter.feishu.FeishuApprovalService; +import com.finance.system.adapter.feishu.FeishuAuthService; +import com.finance.system.adapter.feishu.FeishuApprovalResponse; +import com.finance.system.dto.ApiResponse; +import com.finance.system.entity.SysWebhookEvent; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysWebhookEventRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.security.access.prepost.PreAuthorize; +import javax.servlet.http.HttpServletRequest; + +import java.net.URI; +import java.net.URLEncoder; +import java.util.Map; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Optional; +import java.time.Instant; + +@Slf4j +@RestController +@RequestMapping("/api/feishu") +@RequiredArgsConstructor +public class FeishuAuthController { + + private final FeishuAuthService feishuAuthService; + private final FeishuApprovalService feishuApprovalService; + private final ObjectMapper objectMapper; + private final SysWebhookEventRepository webhookEventRepository; + + @Value("${app.frontend-url:http://localhost:5173}") + private String frontendUrl; + + @GetMapping("/auth-url") + public ResponseEntity>> getAuthUrl(HttpServletRequest request) { + FeishuAuthService.AuthUrl auth = feishuAuthService.buildAuthUrlWithState(); + Map result = new HashMap<>(); + result.put("authUrl", auth.getAuthUrl()); + String state = auth.getState(); + String cookie = "FEISHU_OAUTH_STATE=" + state + + "; Max-Age=300; Path=/api; HttpOnly; SameSite=Lax" + + (request.isSecure() ? "; Secure" : ""); + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.SET_COOKIE, cookie); + return new ResponseEntity<>(ApiResponse.success(result), headers, HttpStatus.OK); + } + + /** + * 飞书OAuth回调。 + * 只转交一次性授权码,JWT 在后端的登录接口中生成,避免把 bearer token 放进 URL。 + */ + @GetMapping("/callback") + public ResponseEntity callback( + @RequestParam("code") String code, + @RequestParam(value = "state", required = false) String state) { + log.info("收到飞书OAuth回调"); + + try { + feishuAuthService.validateCallbackState(state); + String redirectUrl = frontendUrl + "/login?code=" + encodeUrl(code) + + "&state=" + encodeUrl(state); + HttpHeaders headers = new HttpHeaders(); + headers.setLocation(URI.create(redirectUrl)); + return new ResponseEntity<>(headers, HttpStatus.FOUND); + + } catch (BusinessException e) { + log.warn("飞书登录失败: {}", e.getMessage()); + String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败: " + e.getMessage()); + HttpHeaders headers = new HttpHeaders(); + headers.setLocation(URI.create(errorUrl)); + return new ResponseEntity<>(headers, HttpStatus.FOUND); + } catch (Exception e) { + log.error("飞书登录失败", e); + String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败: " + e.getMessage()); + HttpHeaders headers = new HttpHeaders(); + headers.setLocation(URI.create(errorUrl)); + return new ResponseEntity<>(headers, HttpStatus.FOUND); + } + } + + private String encodeUrl(String value) { + try { + return URLEncoder.encode(value, "UTF-8"); + } catch (Exception e) { + return value; + } + } + + /** + * 飞书审批回调Webhook + * 处理审批实例状态变更、审批任务变更等事件 + */ + @PostMapping("/webhook") + @Transactional + public ResponseEntity> handleWebhook( + @RequestBody String rawBody, + @RequestHeader(value = "X-Lark-Signature", required = false) String signature, + @RequestHeader(value = "X-Lark-Request-Timestamp", required = false) String timestamp, + @RequestHeader(value = "X-Lark-Request-Nonce", required = false) String nonce) { + Map body; + try { + body = objectMapper.readValue(rawBody, Map.class); + } catch (Exception e) { + return ResponseEntity.badRequest().body(responseMap(1, "invalid webhook body")); + } + + log.info("收到飞书Webhook请求: eventType={}", body.get("event_type")); + + if (!feishuAuthService.isWebhookAuthorized(body, signature, timestamp, nonce, rawBody)) { + return ResponseEntity.status(401).body(responseMap(1, "invalid webhook signature")); + } + + // 处理URL验证(飞书首次配置事件订阅时会发送验证请求) + if (body.containsKey("challenge")) { + String challenge = (String) body.get("challenge"); + log.info("飞书Webhook URL验证: challenge={}", challenge); + Map result = new HashMap<>(); + result.put("challenge", challenge); + return ResponseEntity.ok(result); + } + + if (!isFreshTimestamp(timestamp)) { + return ResponseEntity.badRequest().body(responseMap(1, "invalid webhook timestamp")); + } + + // Feishu v2 wraps the event in event/header. Flatten only the + // compatibility fields consumed by the existing approval adapter; + // the raw body is still used for signature verification above. + Map normalized = normalizeEvent(body); + + // 处理审批事件 + String eventId = eventId(normalized); + if (eventId == null) { + return ResponseEntity.badRequest().body(responseMap(1, "event_id is required")); + } + return processWebhookEvent(eventId, normalized); + } + + private boolean isFreshTimestamp(String value) { + if (value == null || value.trim().isEmpty()) return false; + try { + long supplied = Long.parseLong(value.trim()); + long now = Instant.now().getEpochSecond(); + return Math.abs(now - supplied) <= 300L; + } catch (Exception e) { + return false; + } + } + + @SuppressWarnings("unchecked") + private Map normalizeEvent(Map body) { + Map normalized = new LinkedHashMap<>(body); + Object eventValue = body.get("event"); + if (eventValue instanceof Map) { + Map event = (Map) eventValue; + for (Map.Entry entry : event.entrySet()) { + if (!normalized.containsKey(entry.getKey())) normalized.put(entry.getKey(), entry.getValue()); + } + if (!normalized.containsKey("event_id") && event.get("event_id") != null) { + normalized.put("event_id", event.get("event_id")); + } + if (!normalized.containsKey("event_type") && event.get("event_type") != null) { + normalized.put("event_type", event.get("event_type")); + } + } + Object headerValue = body.get("header"); + if (headerValue instanceof Map) { + Map header = (Map) headerValue; + if (!normalized.containsKey("event_id") && header.get("event_id") != null) { + normalized.put("event_id", header.get("event_id")); + } + if (!normalized.containsKey("event_type") && header.get("event_type") != null) { + normalized.put("event_type", header.get("event_type")); + } + } + return normalized; + } + + private String eventId(Map body) { + Object value = body.get("event_id"); + if ((value == null || String.valueOf(value).trim().isEmpty()) && body.get("event") instanceof Map) { + value = ((Map) body.get("event")).get("event_id"); + } + if ((value == null || String.valueOf(value).trim().isEmpty()) && body.get("header") instanceof Map) { + value = ((Map) body.get("header")).get("event_id"); + } + return value == null || String.valueOf(value).trim().isEmpty() ? null : String.valueOf(value).trim(); + } + + private ResponseEntity> processWebhookEvent( + String eventId, Map body) { + SysWebhookEvent event = null; + try { + webhookEventRepository.insertIfAbsent(eventId); + Optional locked = webhookEventRepository.findById(eventId); + if (!locked.isPresent()) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(responseMap(1, "webhook inbox unavailable")); + } + + event = locked.get(); + if (SysWebhookEvent.PROCESSED.equals(event.getStatus())) { + return ResponseEntity.ok(responseMap(0, "success")); + } + + event.setStatus(SysWebhookEvent.PROCESSING); + feishuApprovalService.handleApprovalEvent(body); + event.setStatus(SysWebhookEvent.PROCESSED); + return ResponseEntity.ok(responseMap(0, "success")); + } catch (Exception e) { + if (event != null) { + event.setStatus(SysWebhookEvent.FAILED); + } + log.error("处理飞书Webhook失败: eventId={}", eventId, e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(responseMap(1, "webhook processing failed")); + } + } + + private Map responseMap(int code, String message) { + Map result = new HashMap<>(); + result.put("code", code); + result.put("msg", message); + return result; + } + + /** + * 获取审批定义(审批节点信息) + */ + @GetMapping("/approval/definition") + @PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") + 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())); + } + } + + /** + * 获取审批节点列表 + */ + @GetMapping("/approval/nodes") + @PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") + 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())); + } + } + + /** + * 获取审批实例进度 + */ + @GetMapping("/approval/instance/{instanceCode}") + @PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") + public ResponseEntity> getApprovalInstanceDetail( + @PathVariable String instanceCode) { + try { + FeishuApprovalResponse detail = feishuApprovalService.getApprovalInstanceDetail(instanceCode); + return ResponseEntity.ok(ApiResponse.success(detail)); + } catch (Exception e) { + log.error("获取审批实例详情失败: instanceCode={}", instanceCode, e); + return ResponseEntity.ok(ApiResponse.error(500, e.getMessage())); + } + } + + /** + * 根据报销单ID获取审批进度 + */ + @GetMapping("/approval/application/{applicationId}") + @PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") + public ResponseEntity> getApprovalTimelineByApplication( + @PathVariable Long applicationId) { + 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())); + } + } +} diff --git a/src/main/java/com/finance/system/controller/FeishuCallbackController.java b/src/main/java/com/finance/system/controller/FeishuCallbackController.java new file mode 100644 index 0000000..53152d4 --- /dev/null +++ b/src/main/java/com/finance/system/controller/FeishuCallbackController.java @@ -0,0 +1,175 @@ +package com.finance.system.controller; + +import com.finance.system.adapter.feishu.FeishuAuthService; +import com.finance.system.adapter.feishu.FeishuTokenResponse; +import com.finance.system.adapter.feishu.FeishuUserInfo; +import com.finance.system.config.JwtConfig; +import com.finance.system.dto.ApiResponse; +import com.finance.system.dto.LoginResponse; +import com.finance.system.dto.UserProfile; +import com.finance.system.entity.SysDepartment; +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.service.RoleService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/api/feishu") +@RequiredArgsConstructor +public class FeishuCallbackController { + + private final FeishuAuthService feishuAuthService; + private final JwtConfig jwtConfig; + private final SysUserRepository sysUserRepository; + private final SysDepartmentRepository sysDepartmentRepository; + + /** + * 飞书登录接口 - 返回JSON而非重定向 + * 前端先获取authUrl,用户授权后回调到前端,前端再调用此接口交换token + */ + @PostMapping("/login") + public ResponseEntity> feishuLogin( + @RequestBody Map request, + @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { + String code = request.get("code"); + String state = request.get("state"); + if (code == null || code.trim().isEmpty()) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "授权码不能为空")); + } + + try { + feishuAuthService.validateCallbackState(state, browserState, true); + // 1. 交换access_token + FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code); + String accessToken = tokenResponse.getData().getAccessToken(); + log.info("飞书access_token获取成功"); + + // 2. 获取用户信息 + FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken); + log.info("飞书用户信息获取成功: name={}, openId={}", feishuUserInfo.getName(), feishuUserInfo.getOpenId()); + + // 3. 查找已绑定的本地用户 + SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo); + log.info("用户绑定成功: userId={}, realName={}", user.getId(), user.getRealName()); + if (!isActive(user)) { + return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); + } + + // 4. 生成JWT token + JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( + user.getId(), + user.getEmployeeNo(), + user.getRealName(), + RoleService.normalize(user.getUserType())); + + // Profile/binding/lastLogin were committed by the shared locked login finalizer. + + // 6. 构建用户档案 + UserProfile profile = buildUserProfile(user); + + LoginResponse loginResponse = LoginResponse.builder() + .token(generatedToken.getToken()) + .tokenType("Bearer") + .expiresIn(generatedToken.getExpiresIn()) + .user(profile) + .build(); + + return ResponseEntity.ok(ApiResponse.success(loginResponse)); + + } catch (BusinessException e) { + log.warn("飞书登录失败: {}", e.getMessage()); + return ResponseEntity.status(e.getStatusCode()) + .body(ApiResponse.error(e.getStatusCode(), e.getMessage())); + } catch (Exception e) { + log.error("飞书登录失败", e); + return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试")); + } + } + + /** + * GET方式也支持(通过查询参数传递code) + */ + @GetMapping("/login") + public ResponseEntity> feishuLoginGet( + @RequestParam("code") String code, + @RequestParam("state") String state, + @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { + if (code == null || code.trim().isEmpty()) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "授权码不能为空")); + } + + try { + feishuAuthService.validateCallbackState(state, browserState, true); + FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code); + String accessToken = tokenResponse.getData().getAccessToken(); + FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken); + SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo); + if (!isActive(user)) { + return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); + } + + JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( + user.getId(), + user.getEmployeeNo(), + user.getRealName(), + RoleService.normalize(user.getUserType())); + + UserProfile profile = buildUserProfile(user); + + LoginResponse loginResponse = LoginResponse.builder() + .token(generatedToken.getToken()) + .tokenType("Bearer") + .expiresIn(generatedToken.getExpiresIn()) + .user(profile) + .build(); + + return ResponseEntity.ok(ApiResponse.success(loginResponse)); + + } catch (BusinessException e) { + log.warn("飞书登录失败: {}", e.getMessage()); + return ResponseEntity.status(e.getStatusCode()) + .body(ApiResponse.error(e.getStatusCode(), e.getMessage())); + } catch (Exception e) { + log.error("飞书登录失败", e); + return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试")); + } + } + + private UserProfile buildUserProfile(SysUser user) { + String deptName = null; + if (user.getDepartmentId() != null) { + SysDepartment dept = sysDepartmentRepository.findById(user.getDepartmentId()).orElse(null); + if (dept != null) { + deptName = dept.getDeptName(); + } + } + + return UserProfile.builder() + .id(user.getId()) + .employeeNo(user.getEmployeeNo()) + .realName(user.getRealName()) + .avatarUrl(user.getAvatarUrl()) + .email(user.getEmail()) + .departmentName(deptName) + .position(user.getPosition()) + .userType(RoleService.normalize(user.getUserType())) + .status(user.getStatus()) + .feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定") + .lastLoginAt(user.getLastLoginAt() != null ? user.getLastLoginAt().toString().replace("T", " ") : null) + .build(); + } + + private boolean isActive(SysUser user) { + return user != null && "ACTIVE".equalsIgnoreCase(user.getStatus()); + } +} diff --git a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java new file mode 100644 index 0000000..7f0db76 --- /dev/null +++ b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java @@ -0,0 +1,32 @@ +package com.finance.system.controller; + +import com.finance.system.adapter.feishu.FeishuDirectoryService; +import com.finance.system.dto.ApiResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/feishu/directory") +public class FeishuDirectoryController { + private final FeishuDirectoryService directory; + @PostMapping("/sync") + @PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync')") + public ResponseEntity> sync() { + FeishuDirectoryService.Run run = directory.sync("MANUAL"); + return ResponseEntity.status(run.isApplied() ? 200 : 503).body(run.isApplied() ? ApiResponse.success(run) + : ApiResponse.error(503, run.getErrorMessage(), run)); + } + @GetMapping("/status") + @PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync') or @permissionChecker.has(authentication, 'system:feishu:bind')") + public ApiResponse> status() { return ApiResponse.success(directory.status()); } + + @GetMapping("/organization") + @PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync') or @permissionChecker.has(authentication, 'system:feishu:bind')") + 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 new file mode 100644 index 0000000..f8b08ad --- /dev/null +++ b/src/main/java/com/finance/system/controller/IntegrationConfigController.java @@ -0,0 +1,31 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.service.IntegrationConfigService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/api/integrations/config") +@RequiredArgsConstructor +public class IntegrationConfigController { + private final IntegrationConfigService service; + + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'system:integration:view')") + public ResponseEntity>> get() { return ResponseEntity.ok(ApiResponse.success(service.view())); } + + @PutMapping + @PreAuthorize("@permissionChecker.has(authentication, 'system:integration:manage')") + public ResponseEntity> put(@RequestBody Map body) { service.update(body); return ResponseEntity.ok(ApiResponse.success()); } + + @PostMapping("/test") + @PreAuthorize("@permissionChecker.has(authentication, 'system:integration: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/LogController.java b/src/main/java/com/finance/system/controller/LogController.java new file mode 100644 index 0000000..5f94c55 --- /dev/null +++ b/src/main/java/com/finance/system/controller/LogController.java @@ -0,0 +1,98 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.*; + +@Slf4j +@RestController +@RequestMapping("/api/logs") +@RequiredArgsConstructor +public class LogController { + + /** + * Mock数据 - 操作日志 + */ + private static final List> MOCK_LOGS = new ArrayList<>(); + + static { + addLog("系统", "飞书审批同步", "审批实例 20260801001 同步完成", "审批同步"); + addLog("李志豪", "提交报销", "报销单 BX20260812001 已提交审批", "报销申请"); + addLog("刘雅", "应付会计审核", "报销单 BX20260809003 审核通过", "审批操作"); + addLog("周岚", "财务经理审批", "报销单 BX20260808006 审批通过", "审批操作"); + addLog("周敏", "登记付款", "报销单 BX20260728004 登记付款 ¥1,800.00", "付款操作"); + addLog("系统", "金蝶同步", "来源单据 TRIP2026072804 同步完成", "数据同步"); + addLog("李志豪", "补充材料", "报销单 BX20260812001 补充材料并重新提交", "报销申请"); + addLog("刘雅", "收单确认", "报销单 BX20260801009 财务收单完成", "收单操作"); + } + + private static void addLog(String operator, String action, String detail, String category) { + Map logEntry = new LinkedHashMap<>(); + logEntry.put("id", (long) (MOCK_LOGS.size() + 1)); + logEntry.put("operator", operator); + logEntry.put("action", action); + logEntry.put("detail", detail); + logEntry.put("category", category); + logEntry.put("time", getLogTime(MOCK_LOGS.size())); + MOCK_LOGS.add(logEntry); + } + + private static String getLogTime(int index) { + String[] times = { + "2026-08-12 14:30:00", + "2026-08-12 10:24:00", + "2026-08-10 09:16:00", + "2026-08-09 14:08:00", + "2026-08-03 15:24:00", + "2026-08-03 14:00:00", + "2026-08-01 09:42:00", + "2026-07-28 16:00:00" + }; + return index < times.length ? times[index] : java.time.LocalDateTime.now().toString().replace("T", " "); + } + + /** + * 获取操作日志列表 + */ + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'approval:view')") + public ResponseEntity>>> listLogs( + @RequestParam(required = false) String category, + @RequestParam(required = false) String operator, + @RequestParam(defaultValue = "50") int limit) { + try { + List> result = new ArrayList<>(MOCK_LOGS); + + if (category != null && !category.isEmpty()) { + result.removeIf(log -> !category.equals(log.get("category"))); + } + if (operator != null && !operator.isEmpty()) { + result.removeIf(log -> !operator.equals(log.get("operator"))); + } + + // 按时间倒序排列 + result.sort((a, b) -> { + String timeA = (String) a.get("time"); + String timeB = (String) b.get("time"); + return timeB.compareTo(timeA); + }); + + // 限制数量 + if (result.size() > limit) { + result = result.subList(0, limit); + } + + return ResponseEntity.ok(ApiResponse.success(result)); + } catch (Exception e) { + log.error("获取操作日志列表失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "获取操作日志列表失败: " + e.getMessage())); + } + } +} diff --git a/src/main/java/com/finance/system/controller/MetadataController.java b/src/main/java/com/finance/system/controller/MetadataController.java new file mode 100644 index 0000000..421ac2e --- /dev/null +++ b/src/main/java/com/finance/system/controller/MetadataController.java @@ -0,0 +1,158 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@RestController +@RequestMapping("/api/metadata") +@RequiredArgsConstructor +public class MetadataController { + + /** + * Mock数据 - 费用类型 + */ + private static final List> EXPENSE_TYPES = new ArrayList<>(); + + static { + Map et1 = new LinkedHashMap<>(); + et1.put("id", 1); + et1.put("code", "EMPLOYEE_REIMBURSEMENT"); + et1.put("name", "员工报销类"); + et1.put("category", "员工报销"); + et1.put("description", "员工因公产生的差旅、交通、招待等费用报销"); + EXPENSE_TYPES.add(et1); + + Map et2 = new LinkedHashMap<>(); + et2.put("id", 2); + et2.put("code", "TRAVEL_TRANSPORTATION"); + et2.put("name", "差旅交通"); + et2.put("category", "差旅交通"); + et2.put("description", "出差期间产生的交通费用"); + EXPENSE_TYPES.add(et2); + + Map et3 = new LinkedHashMap<>(); + et3.put("id", 3); + et3.put("code", "ACCOMMODATION"); + et3.put("name", "住宿费"); + et3.put("category", "住宿费"); + et3.put("description", "出差期间住宿费用"); + EXPENSE_TYPES.add(et3); + + Map et4 = new LinkedHashMap<>(); + et4.put("id", 4); + et4.put("code", "BUSINESS_ENTERTAINMENT"); + et4.put("name", "业务招待"); + et4.put("category", "业务招待"); + et4.put("description", "客户招待、商务用餐等费用"); + EXPENSE_TYPES.add(et4); + + Map et5 = new LinkedHashMap<>(); + et5.put("id", 5); + et5.put("code", "TRAVEL_ALLOWANCE"); + et5.put("name", "差旅补贴"); + et5.put("category", "差旅补贴"); + et5.put("description", "出差补贴费用"); + EXPENSE_TYPES.add(et5); + + Map et6 = new LinkedHashMap<>(); + et6.put("id", 6); + et6.put("code", "OFFICE_EXPENSE"); + et6.put("name", "办公费用"); + et6.put("category", "办公费用"); + et6.put("description", "办公用品、耗材等费用"); + EXPENSE_TYPES.add(et6); + } + + /** + * Mock数据 - 收款人 + */ + private static final List> PAYEES = new ArrayList<>(); + + static { + Map p1 = new LinkedHashMap<>(); + p1.put("id", 1); + p1.put("name", "李志豪"); + p1.put("employeeNo", "EMP000086"); + p1.put("department", "销售中心"); + p1.put("bankName", "中国工商银行苏州新区支行"); + p1.put("bankAccount", "6222 0200 0086 0728"); + PAYEES.add(p1); + + Map p2 = new LinkedHashMap<>(); + p2.put("id", 2); + p2.put("name", "王忠辉"); + p2.put("employeeNo", "EMP000087"); + p2.put("department", "数字化中心"); + p2.put("bankName", "招商银行苏州分行"); + p2.put("bankAccount", "6222 **** 3402"); + PAYEES.add(p2); + + Map p3 = new LinkedHashMap<>(); + p3.put("id", 3); + p3.put("name", "赵海峰"); + p3.put("employeeNo", "EMP000088"); + p3.put("department", "供应链中心"); + p3.put("bankName", "招商银行苏州工业园区支行"); + p3.put("bankAccount", "6214 **** 8001"); + PAYEES.add(p3); + } + + /** + * 获取费用类型列表 + */ + @GetMapping("/expense-types") + public ResponseEntity>>> getExpenseTypes() { + try { + return ResponseEntity.ok(ApiResponse.success(EXPENSE_TYPES)); + } catch (Exception e) { + log.error("获取费用类型列表失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "获取费用类型列表失败: " + e.getMessage())); + } + } + + /** + * 获取收款人列表 + */ + @GetMapping("/payees") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity>>> getPayees( + @RequestParam(required = false) String keyword) { + try { + List> result = PAYEES.stream().map(payee -> { + Map safe = new LinkedHashMap<>(payee); + Object rawAccount = safe.remove("bankAccount"); + if (rawAccount != null) safe.put("bankAccountMask", maskAccount(String.valueOf(rawAccount))); + return safe; + }).collect(Collectors.toList()); + + if (keyword != null && !keyword.isEmpty()) { + String lowerKeyword = keyword.toLowerCase(); + result.removeIf(p -> { + String name = (String) p.get("name"); + String empNo = (String) p.get("employeeNo"); + return !(name != null && name.toLowerCase().contains(lowerKeyword)) + && !(empNo != null && empNo.toLowerCase().contains(lowerKeyword)); + }); + } + + return ResponseEntity.ok(ApiResponse.success(result)); + } catch (Exception e) { + log.error("获取收款人列表失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "获取收款人列表失败: " + e.getMessage())); + } + } + + private static String maskAccount(String value) { + String digits = value.replaceAll("\\s+", ""); + if (digits.length() <= 4) return "已脱敏"; + return "**** " + digits.substring(digits.length() - 4); + } +} diff --git a/src/main/java/com/finance/system/controller/PaymentController.java b/src/main/java/com/finance/system/controller/PaymentController.java new file mode 100644 index 0000000..69e9bbb --- /dev/null +++ b/src/main/java/com/finance/system/controller/PaymentController.java @@ -0,0 +1,200 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.*; + +@Slf4j +@RestController +@RequestMapping("/api/payments") +@RequiredArgsConstructor +public class PaymentController { + + /** + * Mock数据 - 付款记录 + */ + private static final List> MOCK_PAYMENTS = new ArrayList<>(); + + static { + Map p1 = new LinkedHashMap<>(); + p1.put("id", "PAY-20260803-01"); + p1.put("applicationId", "BX20260728004"); + p1.put("applicationNo", "BX20260728004"); + p1.put("title", "上海项目住宿费"); + p1.put("payee", "赵海峰"); + p1.put("amount", new BigDecimal("1800.00")); + p1.put("paidAmount", new BigDecimal("1800.00")); + p1.put("unpaidAmount", new BigDecimal("2300.00")); + p1.put("time", "2026-08-03 15:24"); + p1.put("method", "银行转账"); + p1.put("account", "招商银行 · 9032"); + p1.put("reference", "FLOW202608030883"); + p1.put("operator", "周敏"); + p1.put("status", "有效"); + p1.put("expenseType", "员工报销类"); + MOCK_PAYMENTS.add(p1); + } + + /** + * Mock数据 - 付款申请列表(带付款信息) + */ + private static final List> MOCK_PAYMENT_APPLICATIONS = new ArrayList<>(); + + static { + Map a1 = new LinkedHashMap<>(); + a1.put("id", "BX20260728004"); + a1.put("date", "2026-07-28"); + a1.put("title", "上海项目住宿费"); + a1.put("payee", "赵海峰"); + a1.put("owner", "赵海峰"); + a1.put("department", "供应链中心"); + a1.put("amount", new BigDecimal("4100.00")); + a1.put("paidAmount", new BigDecimal("1800.00")); + a1.put("unpaidAmount", new BigDecimal("2300.00")); + a1.put("receiptStatus", "已收单"); + a1.put("paymentStatus", "部分付款"); + a1.put("expenseType", "员工报销类"); + MOCK_PAYMENT_APPLICATIONS.add(a1); + + Map a2 = new LinkedHashMap<>(); + a2.put("id", "BX20260801009"); + a2.put("date", "2026-08-01"); + a2.put("title", "七月云资源差旅补贴"); + a2.put("payee", "王忠辉"); + a2.put("owner", "王忠辉"); + a2.put("department", "数字化中心"); + a2.put("amount", new BigDecimal("3200.00")); + a2.put("paidAmount", new BigDecimal("0.00")); + a2.put("unpaidAmount", new BigDecimal("3200.00")); + a2.put("receiptStatus", "已收单"); + a2.put("paymentStatus", "未付款"); + a2.put("expenseType", "员工报销类"); + MOCK_PAYMENT_APPLICATIONS.add(a2); + + Map a3 = new LinkedHashMap<>(); + a3.put("id", "BX20260802011"); + a3.put("date", "2026-08-02"); + a3.put("title", "苏州园区客户拜访费用"); + a3.put("payee", "赵海峰"); + a3.put("owner", "赵海峰"); + a3.put("department", "供应链中心"); + a3.put("amount", new BigDecimal("2180.00")); + a3.put("paidAmount", new BigDecimal("0.00")); + a3.put("unpaidAmount", new BigDecimal("2180.00")); + a3.put("receiptStatus", "待收单"); + a3.put("paymentStatus", "未付款"); + a3.put("expenseType", "员工报销类"); + MOCK_PAYMENT_APPLICATIONS.add(a3); + + Map a4 = new LinkedHashMap<>(); + a4.put("id", "BX20260809003"); + a4.put("date", "2026-08-09"); + a4.put("title", "八月客户拜访交通费"); + a4.put("payee", "李志豪"); + a4.put("owner", "李志豪"); + a4.put("department", "销售中心"); + a4.put("amount", new BigDecimal("1260.00")); + a4.put("paidAmount", new BigDecimal("0.00")); + a4.put("unpaidAmount", new BigDecimal("1260.00")); + a4.put("receiptStatus", "未触发"); + a4.put("paymentStatus", "未付款"); + a4.put("expenseType", "员工报销类"); + MOCK_PAYMENT_APPLICATIONS.add(a4); + } + + /** + * 获取付款列表(资金出纳B视图,过滤 expenseType=员工报销类) + */ + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'payment:register')") + public ResponseEntity>> listPayments( + @RequestParam(required = false) String status, + @RequestParam(required = false) String expenseType) { + try { + List> applications = new ArrayList<>(MOCK_PAYMENT_APPLICATIONS); + + // 默认过滤 expenseType=员工报销类 + if (expenseType != null && !expenseType.isEmpty()) { + applications.removeIf(app -> !expenseType.equals(app.get("expenseType"))); + } else { + applications.removeIf(app -> !"员工报销类".equals(app.get("expenseType"))); + } + + // 按付款状态过滤 + if (status != null && !status.isEmpty()) { + applications.removeIf(app -> !status.equals(app.get("paymentStatus"))); + } + + Map result = new LinkedHashMap<>(); + result.put("applications", applications); + result.put("payments", new ArrayList<>(MOCK_PAYMENTS)); + result.put("total", applications.size()); + + return ResponseEntity.ok(ApiResponse.success(result)); + } catch (Exception e) { + log.error("获取付款列表失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "获取付款列表失败: " + e.getMessage())); + } + } + + /** + * 登记付款 + */ + @PostMapping("/register") + @PreAuthorize("@permissionChecker.has(authentication, 'payment:register')") + public ResponseEntity>> registerPayment(@RequestBody Map request) { + try { + UserPrincipal principal = AuditUtil.getCurrentUser(); + String applicationNo = (String) request.get("applicationNo"); + Object amountObj = request.get("amount"); + BigDecimal amount; + if (amountObj instanceof Number) { + amount = new BigDecimal(((Number) amountObj).toString()); + } else { + amount = new BigDecimal(String.valueOf(amountObj)); + } + String method = (String) request.getOrDefault("method", "银行转账"); + String account = (String) request.getOrDefault("account", "招商银行 · 9032"); + String reference = (String) request.getOrDefault("reference", "FLOW-" + System.currentTimeMillis()); + + if (applicationNo == null || applicationNo.trim().isEmpty()) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "申请单号不能为空")); + } + if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(400, "付款金额必须大于0")); + } + + // 创建付款记录 + Map payment = new LinkedHashMap<>(); + payment.put("id", "PAY-" + java.time.LocalDate.now().toString().replace("-", "") + "-" + String.format("%02d", MOCK_PAYMENTS.size() + 1)); + payment.put("applicationNo", applicationNo); + payment.put("amount", amount); + payment.put("time", java.time.LocalDateTime.now().toString().replace("T", " ")); + payment.put("method", method); + payment.put("account", account); + payment.put("reference", reference); + payment.put("operator", principal != null ? principal.getRealName() : "系统"); + payment.put("status", "有效"); + + // 添加到mock列表 + MOCK_PAYMENTS.add(payment); + + log.info("付款登记成功: applicationNo={}, amount={}", applicationNo, amount); + + return ResponseEntity.ok(ApiResponse.success(payment)); + } catch (Exception e) { + log.error("登记付款失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "登记付款失败: " + e.getMessage())); + } + } +} diff --git a/src/main/java/com/finance/system/controller/ReimApplicationController.java b/src/main/java/com/finance/system/controller/ReimApplicationController.java new file mode 100644 index 0000000..9ed6566 --- /dev/null +++ b/src/main/java/com/finance/system/controller/ReimApplicationController.java @@ -0,0 +1,102 @@ +package com.finance.system.controller; + +import com.finance.system.dto.*; +import com.finance.system.service.ReimApplicationService; +import com.finance.system.util.AuditUtil; +import javax.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/v1/reimbursements") +@RequiredArgsConstructor +public class ReimApplicationController { + + private final ReimApplicationService reimApplicationService; + + @GetMapping("/workbench") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own')") + public ResponseEntity> getWorkbench() { + Long userId = AuditUtil.getCurrentUserId(); + WorkbenchDto workbench = reimApplicationService.getWorkbench(userId); + return ResponseEntity.ok(ApiResponse.success(workbench)); + } + + @GetMapping("/my") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own')") + public ResponseEntity>> getMyApplications( + @RequestParam(required = false) String status, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + Long userId = AuditUtil.getCurrentUserId(); + Pageable pageable = PageRequest.of(page, size); + Page applications = reimApplicationService.getMyApplications(userId, status, pageable); + return ResponseEntity.ok(ApiResponse.success(PageResponse.of( + applications.getContent(), applications.getTotalElements(), page, size))); + } + + @GetMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own') || @permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity> getDetail(@PathVariable Long id) { + Long userId = AuditUtil.getCurrentUserId(); + ReimApplicationDetail detail = reimApplicationService.getApplicationDetail(id, userId); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @GetMapping("/no/{applicationNo}") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own') || @permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity> getByApplicationNo( + @PathVariable String applicationNo) { + Long userId = AuditUtil.getCurrentUserId(); + ReimApplicationDetail detail = reimApplicationService.getByApplicationNo(applicationNo, userId); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @PostMapping + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')") + public ResponseEntity> create( + @Valid @RequestBody CreateApplicationRequest request) { + Long userId = AuditUtil.getCurrentUserId(); + ReimApplicationDetail detail = reimApplicationService.createApplication(request, userId); + return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(detail)); + } + + @PutMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')") + public ResponseEntity> update( + @PathVariable Long id, + @RequestBody CreateApplicationRequest request) { + Long userId = AuditUtil.getCurrentUserId(); + ReimApplicationDetail detail = reimApplicationService.updateApplication(id, request, userId); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @PostMapping("/{id}/submit") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')") + public ResponseEntity> submit(@PathVariable Long id) { + Long userId = AuditUtil.getCurrentUserId(); + ReimApplicationDetail detail = reimApplicationService.submitApplication(id, userId); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @PostMapping("/{id}/receive") + @PreAuthorize("@permissionChecker.has(authentication, 'receipt:manage')") + public ResponseEntity> receive(@PathVariable Long id) { + Long operatorId = AuditUtil.getCurrentUserId(); + ReimApplicationDetail detail = reimApplicationService.receiveApplication(id, operatorId); + return ResponseEntity.ok(ApiResponse.success(detail)); + } + + @DeleteMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')") + public ResponseEntity> 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 new file mode 100644 index 0000000..2407143 --- /dev/null +++ b/src/main/java/com/finance/system/controller/RoleController.java @@ -0,0 +1,104 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.entity.SysRole; +import com.finance.system.entity.SysUser; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.security.UserPrincipal; +import com.finance.system.service.RoleService; +import com.finance.system.util.AuditUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.*; + +@RestController +@RequestMapping("/api/roles") +public class RoleController { + private final SysUserRepository sysUserRepository; + private RoleService roleService; + + public RoleController(SysUserRepository sysUserRepository) { this.sysUserRepository = sysUserRepository; } + @Autowired(required = false) + public void setRoleService(RoleService roleService) { this.roleService = roleService; } + + private static final List> ROLE_PROFILES = new ArrayList<>(); + static { + ROLE_PROFILES.add(profile(1, "SUPER_ADMIN", "超级管理员", "历史兼容角色 - 全功能访问", "*")); + ROLE_PROFILES.add(profile(2, "FINANCE", "财务人员", "财务人员 - 收单管理、付款登记、审批查看、基础数据", + "reimbursement:view-all", "receipt:manage", "payment:register", "approval:view", "master-data:manage")); + ROLE_PROFILES.add(profile(3, "EMPLOYEE", "员工", "普通员工 - 发起报销、查看个人报销进度", + "reimbursement:create", "reimbursement:view-own")); + } + + private static Map profile(int id, String code, String name, String description, String... permissions) { + Map value = new LinkedHashMap<>(); value.put("id", id); value.put("code", code); + value.put("name", name); value.put("description", description); value.put("permissions", Arrays.asList(permissions)); return value; + } + + /** Kept for the existing login page contract. */ + @GetMapping("/profiles") + public ResponseEntity>>> getRoleProfiles() { return ResponseEntity.ok(ApiResponse.success(ROLE_PROFILES)); } + + /** Kept for the existing role drawer contract. */ + @GetMapping("/current") + public ResponseEntity>> getCurrentRole() { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null) return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录")); + SysUser user = sysUserRepository.findById(principal.getId()).orElse(null); + if (user == null) return ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在")); + String userType = RoleService.normalize(user.getUserType()); + Map 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")); + return ResponseEntity.ok(ApiResponse.success(result)); + } + + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')") + public ResponseEntity>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listRoles())); } + + @PostMapping + @PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')") + 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')") + 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')") + public ResponseEntity> delete(@PathVariable Long id) { roleService.deleteRole(id); return ResponseEntity.ok(ApiResponse.success()); } + + @GetMapping("/permissions") + @PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')") + public ResponseEntity>>> catalog() { return ResponseEntity.ok(ApiResponse.success(roleService.permissionCatalog())); } + + @GetMapping("/{id}/permissions") + @PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')") + public ResponseEntity>> getPermissions(@PathVariable Long id) { return ResponseEntity.ok(ApiResponse.success(roleService.rolePermissions(id))); } + + @PutMapping("/{id}/permissions") + @PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')") + public ResponseEntity> setPermissions(@PathVariable Long id, @RequestBody Map body) { + roleService.replaceRolePermissions(id, body, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); + } + + @GetMapping("/current-permissions") + public ResponseEntity>> currentPermissions() { + Long userId = AuditUtil.getCurrentUserId(); if (userId == null) return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录")); + return ResponseEntity.ok(ApiResponse.success(roleService.currentPermissionsMap(userId))); + } + + private Map 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/SourceDocumentController.java b/src/main/java/com/finance/system/controller/SourceDocumentController.java new file mode 100644 index 0000000..bbf425b --- /dev/null +++ b/src/main/java/com/finance/system/controller/SourceDocumentController.java @@ -0,0 +1,203 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.*; + +@Slf4j +@RestController +@RequestMapping("/api/sources") +@RequiredArgsConstructor +public class SourceDocumentController { + + /** + * Mock数据 - 业务单据(来源单据) + */ + private static final List> MOCK_SOURCES = new ArrayList<>(); + + static { + Map s1 = new LinkedHashMap<>(); + s1.put("id", 1L); + s1.put("sourceDocNo", "TRIP2026072804"); + s1.put("sourceDocType", "费用报销单"); + s1.put("sourceSystem", "金蝶 ERP"); + s1.put("sourceDate", "2026-07-28"); + s1.put("sourceStatus", "已同步"); + s1.put("title", "上海项目住宿费"); + s1.put("amount", new BigDecimal("4100.00")); + s1.put("payee", "赵海峰"); + s1.put("department", "供应链中心"); + s1.put("bankName", "招商银行苏州工业园区支行"); + s1.put("bankAccount", "6214 **** 8001"); + s1.put("description", "上海项目住宿费用。"); + s1.put("lastSyncTime", "2026-08-03 15:24"); + MOCK_SOURCES.add(s1); + + Map s2 = new LinkedHashMap<>(); + s2.put("id", 2L); + s2.put("sourceDocNo", "TRIP2026080106"); + s2.put("sourceDocType", "费用报销单"); + s2.put("sourceSystem", "金蝶 ERP"); + s2.put("sourceDate", "2026-08-01"); + s2.put("sourceStatus", "已同步"); + s2.put("title", "苏州园区客户拜访费用"); + s2.put("amount", new BigDecimal("2180.00")); + s2.put("payee", "赵海峰"); + s2.put("department", "供应链中心"); + s2.put("bankName", "招商银行苏州工业园区支行"); + s2.put("bankAccount", "6214 **** 8001"); + s2.put("description", "园区客户拜访交通与停车费用。"); + s2.put("lastSyncTime", "2026-08-03 15:24"); + MOCK_SOURCES.add(s2); + + Map s3 = new LinkedHashMap<>(); + s3.put("id", 3L); + s3.put("sourceDocNo", "TRIP2026073108"); + s3.put("sourceDocType", "费用报销单"); + s3.put("sourceSystem", "金蝶 ERP"); + s3.put("sourceDate", "2026-07-31"); + s3.put("sourceStatus", "已同步"); + s3.put("title", "七月云资源差旅补贴"); + s3.put("amount", new BigDecimal("3200.00")); + s3.put("payee", "王忠辉"); + s3.put("department", "数字化中心"); + s3.put("bankName", "招商银行苏州分行"); + s3.put("bankAccount", "6222 **** 3402"); + s3.put("description", "七月现场支持差旅补贴。"); + s3.put("lastSyncTime", "2026-08-03 15:24"); + MOCK_SOURCES.add(s3); + + Map s4 = new LinkedHashMap<>(); + s4.put("id", 4L); + s4.put("sourceDocNo", "TRIP2026080903"); + s4.put("sourceDocType", "费用报销单"); + s4.put("sourceSystem", "金蝶 ERP"); + s4.put("sourceDate", "2026-08-09"); + s4.put("sourceStatus", "已同步"); + s4.put("title", "八月客户拜访交通费"); + s4.put("amount", new BigDecimal("1260.00")); + s4.put("payee", "李志豪"); + s4.put("department", "销售中心"); + s4.put("bankName", "中国工商银行苏州新区支行"); + s4.put("bankAccount", "6222 0200 0086 0728"); + s4.put("description", "客户拜访交通费用。"); + s4.put("lastSyncTime", "2026-08-10 09:16"); + MOCK_SOURCES.add(s4); + + Map s5 = new LinkedHashMap<>(); + s5.put("id", 5L); + s5.put("sourceDocNo", "TRIP2026072602"); + s5.put("sourceDocType", "费用报销单"); + s5.put("sourceSystem", "金蝶 ERP"); + s5.put("sourceDate", "2026-07-26"); + s5.put("sourceStatus", "已同步"); + s5.put("title", "上海项目住宿费"); + s5.put("amount", new BigDecimal("4100.00")); + s5.put("payee", "赵海峰"); + s5.put("department", "供应链中心"); + s5.put("bankName", "招商银行苏州工业园区支行"); + s5.put("bankAccount", "6214 **** 8001"); + s5.put("description", "上海项目住宿费用。"); + s5.put("lastSyncTime", "2026-08-03 15:24"); + MOCK_SOURCES.add(s5); + + Map s6 = new LinkedHashMap<>(); + s6.put("id", 6L); + s6.put("sourceDocNo", "TRIP2026072804"); + s6.put("sourceDocType", "费用报销单"); + s6.put("sourceSystem", "金蝶 ERP"); + s6.put("sourceDate", "2026-07-28"); + s6.put("sourceStatus", "已同步"); + s6.put("title", "上海客户现场技术交流差旅"); + s6.put("amount", new BigDecimal("3286.50")); + s6.put("payee", "李志豪"); + s6.put("department", "销售中心"); + s6.put("bankName", "中国工商银行苏州新区支行"); + s6.put("bankAccount", "6222 0200 0086 0728"); + s6.put("description", "上海客户现场技术交流产生的交通及住宿费用。"); + s6.put("lastSyncTime", "2026-08-12 10:24"); + MOCK_SOURCES.add(s6); + } + + /** + * 获取业务单据列表 + */ + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity>>> listSources( + @RequestParam(required = false) String sourceSystem, + @RequestParam(required = false) String sourceStatus) { + try { + List> result = MOCK_SOURCES.stream() + .map(this::safeSource) + .collect(java.util.stream.Collectors.toList()); + + if (sourceSystem != null && !sourceSystem.isEmpty()) { + result.removeIf(s -> !sourceSystem.equals(s.get("sourceSystem"))); + } + if (sourceStatus != null && !sourceStatus.isEmpty()) { + result.removeIf(s -> !sourceStatus.equals(s.get("sourceStatus"))); + } + + return ResponseEntity.ok(ApiResponse.success(result)); + } catch (Exception e) { + log.error("获取业务单据列表失败", e); + return ResponseEntity.ok(ApiResponse.error(500, "获取业务单据列表失败: " + e.getMessage())); + } + } + + /** + * 获取业务单据详情 + */ + @GetMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')") + public ResponseEntity>> getSourceDetail(@PathVariable Long id) { + try { + Map source = MOCK_SOURCES.stream() + .filter(s -> id.equals(s.get("id"))) + .findFirst() + .orElse(null); + + if (source == null) { + return ResponseEntity.status(404) + .body(ApiResponse.error(404, "业务单据不存在: " + id)); + } + + // 追加详细信息 + Map detail = safeSource(source); + detail.put("remarks", "金蝶来源单据由外部系统同步,平台不允许修改抬头、收款账户或来源金额。"); + detail.put("syncStatus", "已同步"); + detail.put("relatedApplications", getRelatedApplications((String) source.get("sourceDocNo"))); + + return ResponseEntity.ok(ApiResponse.success(detail)); + } catch (Exception e) { + log.error("获取业务单据详情失败: id={}", id, e); + return ResponseEntity.ok(ApiResponse.error(500, "获取业务单据详情失败: " + e.getMessage())); + } + } + + private List> getRelatedApplications(String sourceDocNo) { + List> related = new ArrayList<>(); + Map app = new LinkedHashMap<>(); + app.put("applicationNo", "BX20260728004"); + app.put("title", "上海项目住宿费"); + related.add(app); + return related; + } + + private Map safeSource(Map source) { + Map safe = new LinkedHashMap<>(source); + Object rawAccount = safe.remove("bankAccount"); + if (rawAccount != null) { + String digits = String.valueOf(rawAccount).replaceAll("\\s+", ""); + safe.put("bankAccountMask", digits.length() > 4 ? "**** " + digits.substring(digits.length() - 4) : "已脱敏"); + } + return safe; + } +} diff --git a/src/main/java/com/finance/system/controller/UserGroupController.java b/src/main/java/com/finance/system/controller/UserGroupController.java new file mode 100644 index 0000000..fa0c039 --- /dev/null +++ b/src/main/java/com/finance/system/controller/UserGroupController.java @@ -0,0 +1,79 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.entity.SysUserGroup; +import com.finance.system.service.RoleService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.*; + +@RestController +@RequestMapping("/api/user-groups") +@RequiredArgsConstructor +public class UserGroupController { + private final RoleService roleService; + + @GetMapping + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')") + public ResponseEntity>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listGroups())); } + + @PostMapping + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')") + public ResponseEntity>> create(@RequestBody Map body) { + return ResponseEntity.status(201).body(ApiResponse.success(groupMap(roleService.saveGroup(null, body)))); + } + + @PutMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')") + public ResponseEntity>> update(@PathVariable Long id, @RequestBody Map body) { + return ResponseEntity.ok(ApiResponse.success(groupMap(roleService.saveGroup(id, body)))); + } + + @DeleteMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')") + public ResponseEntity> delete(@PathVariable Long id) { roleService.deleteGroup(id); return ResponseEntity.ok(ApiResponse.success()); } + + @GetMapping("/{id}/roles") + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')") + 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')") + public ResponseEntity> setRoles(@PathVariable Long id, @RequestBody Map body) { + roleService.replaceGroupRoles(id, requiredList(body, "roleIds"), AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); + } + + @GetMapping("/{id}/members") + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')") + public ResponseEntity>> members(@PathVariable Long id) { + Map result = new LinkedHashMap<>(); result.put("userIds", roleService.groupMemberIds(id)); return ResponseEntity.ok(ApiResponse.success(result)); + } + + @PutMapping("/{id}/members") + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')") + public ResponseEntity> setMembers(@PathVariable Long id, @RequestBody Map body) { + roleService.replaceGroupMembers(id, requiredList(body, "userIds"), AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); + } + + @GetMapping("/candidates") + @PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')") + public ResponseEntity>>> candidates() { return ResponseEntity.ok(ApiResponse.success(roleService.candidates())); } + + @SuppressWarnings("unchecked") + private List requiredList(Map body, String key) { + Object value = body == null ? null : body.get(key); + if (!(value instanceof List)) throw new com.finance.system.exception.BadRequestException(key + " 必须是数组"); + return (List) value; + } + + private Map 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; + } +} diff --git a/src/main/java/com/finance/system/dto/ApiResponse.java b/src/main/java/com/finance/system/dto/ApiResponse.java new file mode 100644 index 0000000..e9abecc --- /dev/null +++ b/src/main/java/com/finance/system/dto/ApiResponse.java @@ -0,0 +1,56 @@ +package com.finance.system.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ApiResponse { + + private int code; + private String message; + private T data; + private LocalDateTime timestamp; + + public static ApiResponse success(T data) { + return ApiResponse.builder() + .code(200) + .message("success") + .data(data) + .timestamp(LocalDateTime.now()) + .build(); + } + + public static ApiResponse success() { + return ApiResponse.builder() + .code(200) + .message("success") + .timestamp(LocalDateTime.now()) + .build(); + } + + public static ApiResponse error(int code, String message) { + return ApiResponse.builder() + .code(code) + .message(message) + .timestamp(LocalDateTime.now()) + .build(); + } + + public static ApiResponse error(int code, String message, T data) { + return ApiResponse.builder() + .code(code) + .message(message) + .data(data) + .timestamp(LocalDateTime.now()) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/ApprovalActionRequest.java b/src/main/java/com/finance/system/dto/ApprovalActionRequest.java new file mode 100644 index 0000000..a158eec --- /dev/null +++ b/src/main/java/com/finance/system/dto/ApprovalActionRequest.java @@ -0,0 +1,10 @@ +package com.finance.system.dto; + +import lombok.Data; + +@Data +public class ApprovalActionRequest { + private Long applicationId; + private String comment; + private String returnReason; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/ApprovalRecordDto.java b/src/main/java/com/finance/system/dto/ApprovalRecordDto.java new file mode 100644 index 0000000..01e6d9f --- /dev/null +++ b/src/main/java/com/finance/system/dto/ApprovalRecordDto.java @@ -0,0 +1,20 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ApprovalRecordDto { + private Long id; + private String nodeName; + private String approverName; + private String action; + private String comment; + private LocalDateTime actionTime; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/AttachmentDto.java b/src/main/java/com/finance/system/dto/AttachmentDto.java new file mode 100644 index 0000000..8958d93 --- /dev/null +++ b/src/main/java/com/finance/system/dto/AttachmentDto.java @@ -0,0 +1,17 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AttachmentDto { + private Long id; + private String fileName; + private String fileType; + private String fileUrl; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/CreateApplicationRequest.java b/src/main/java/com/finance/system/dto/CreateApplicationRequest.java new file mode 100644 index 0000000..93597ed --- /dev/null +++ b/src/main/java/com/finance/system/dto/CreateApplicationRequest.java @@ -0,0 +1,18 @@ +package com.finance.system.dto; + +import lombok.Data; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; + +@Data +public class CreateApplicationRequest { + private String title; + private Long expenseTypeId; + private String category; + private BigDecimal totalAmount; + private String description; + private String payeeName; + private Long payeeBankId; + private List items; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/CreatePaymentRequest.java b/src/main/java/com/finance/system/dto/CreatePaymentRequest.java new file mode 100644 index 0000000..21852cf --- /dev/null +++ b/src/main/java/com/finance/system/dto/CreatePaymentRequest.java @@ -0,0 +1,16 @@ +package com.finance.system.dto; + +import lombok.Data; +import java.math.BigDecimal; + +@Data +public class CreatePaymentRequest { + private Long applicationId; + private BigDecimal paymentAmount; + private String paymentMethod; + private String bankAccountNo; + private String referenceNo; + /** Optional body fallback; the HTTP Idempotency-Key header takes precedence. */ + private String idempotencyKey; + private String remark; +} diff --git a/src/main/java/com/finance/system/dto/DashboardStats.java b/src/main/java/com/finance/system/dto/DashboardStats.java new file mode 100644 index 0000000..bf16e8b --- /dev/null +++ b/src/main/java/com/finance/system/dto/DashboardStats.java @@ -0,0 +1,24 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class DashboardStats { + private long totalApplications; + private long pendingApproval; + private long approved; + private long rejected; + private long pendingPayment; + private long unpaid; + private BigDecimal totalAmount; + private BigDecimal paidAmount; + private BigDecimal pendingAmount; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/ExpenseItemDto.java b/src/main/java/com/finance/system/dto/ExpenseItemDto.java new file mode 100644 index 0000000..b6ca4a2 --- /dev/null +++ b/src/main/java/com/finance/system/dto/ExpenseItemDto.java @@ -0,0 +1,21 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.time.LocalDate; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ExpenseItemDto { + private Long id; + private Integer seqNo; + private LocalDate expenseDate; + private String category; + private String description; + private BigDecimal amount; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/InvoiceDto.java b/src/main/java/com/finance/system/dto/InvoiceDto.java new file mode 100644 index 0000000..0653688 --- /dev/null +++ b/src/main/java/com/finance/system/dto/InvoiceDto.java @@ -0,0 +1,22 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.time.LocalDate; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class InvoiceDto { + private Long id; + private String invoiceNo; + private String invoiceType; + private LocalDate issueDate; + private BigDecimal amount; + private String sellerName; + private String verifyStatus; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/LoginRequest.java b/src/main/java/com/finance/system/dto/LoginRequest.java new file mode 100644 index 0000000..0115bac --- /dev/null +++ b/src/main/java/com/finance/system/dto/LoginRequest.java @@ -0,0 +1,11 @@ +package com.finance.system.dto; + +import javax.validation.constraints.NotBlank; +import lombok.Data; + +@Data +public class LoginRequest { + @NotBlank(message = "员工编号不能为空") + private String employeeNo; + private String password; +} diff --git a/src/main/java/com/finance/system/dto/LoginResponse.java b/src/main/java/com/finance/system/dto/LoginResponse.java new file mode 100644 index 0000000..ba4b36e --- /dev/null +++ b/src/main/java/com/finance/system/dto/LoginResponse.java @@ -0,0 +1,17 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class LoginResponse { + private String token; + private String tokenType; + private long expiresIn; + private UserProfile user; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/PageResponse.java b/src/main/java/com/finance/system/dto/PageResponse.java new file mode 100644 index 0000000..1b640fa --- /dev/null +++ b/src/main/java/com/finance/system/dto/PageResponse.java @@ -0,0 +1,31 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PageResponse { + + private List content; + private long totalElements; + private int totalPages; + private int currentPage; + private int pageSize; + + public static PageResponse of(List content, long totalElements, int currentPage, int pageSize) { + return PageResponse.builder() + .content(content) + .totalElements(totalElements) + .totalPages((int) Math.ceil((double) totalElements / pageSize)) + .currentPage(currentPage) + .pageSize(pageSize) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/PaymentDetailDto.java b/src/main/java/com/finance/system/dto/PaymentDetailDto.java new file mode 100644 index 0000000..31bcf97 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PaymentDetailDto.java @@ -0,0 +1,30 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PaymentDetailDto { + private Long id; + private String applicationNo; + private String title; + private String payeeName; + private String departmentName; + private BigDecimal totalAmount; + private BigDecimal paidAmount; + private BigDecimal remainingAmount; + private String paymentStatus; + private String bankName; + private String branchName; + private String bankAccountMask; + private String accountName; + private List paymentHistory; + private List approvalRecords; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/PaymentRecordDto.java b/src/main/java/com/finance/system/dto/PaymentRecordDto.java new file mode 100644 index 0000000..d4f0bcf --- /dev/null +++ b/src/main/java/com/finance/system/dto/PaymentRecordDto.java @@ -0,0 +1,27 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PaymentRecordDto { + private Long id; + private String paymentNo; + private BigDecimal paymentAmount; + private BigDecimal totalAmount; + private BigDecimal paidAmount; + private BigDecimal remainingAmount; + private String paymentMethod; + private String referenceNo; + private String paymentStatus; + private String operatorName; + private LocalDateTime paymentTime; + private String remark; +} diff --git a/src/main/java/com/finance/system/dto/PaymentResultDto.java b/src/main/java/com/finance/system/dto/PaymentResultDto.java new file mode 100644 index 0000000..cbdd983 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PaymentResultDto.java @@ -0,0 +1,18 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PaymentResultDto { + private String paymentNo; + private BigDecimal amount; + private String paymentStatus; + private String message; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/PaymentTaskDto.java b/src/main/java/com/finance/system/dto/PaymentTaskDto.java new file mode 100644 index 0000000..fa1b122 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PaymentTaskDto.java @@ -0,0 +1,32 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PaymentTaskDto { + private Long id; + private String applicationNo; + private String title; + private String payeeName; + private String departmentName; + private String expenseTypeName; + private BigDecimal totalAmount; + private BigDecimal paidAmount; + private BigDecimal remainingAmount; + private String paymentStatus; + private String receiptStatus; + private String approvalStatus; + private String bankName; + private String bankAccountMask; + private LocalDateTime submitTime; + private LocalDateTime createdAt; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/ReimApplicationDetail.java b/src/main/java/com/finance/system/dto/ReimApplicationDetail.java new file mode 100644 index 0000000..a8aa94e --- /dev/null +++ b/src/main/java/com/finance/system/dto/ReimApplicationDetail.java @@ -0,0 +1,57 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ReimApplicationDetail { + private Long id; + private String applicationNo; + private String title; + private Long applicantId; + private String applicantName; + private String applicantEmployeeNo; + private Long departmentId; + private String departmentName; + private Long expenseTypeId; + private String expenseTypeName; + private String category; + private BigDecimal totalAmount; + private String description; + private String applicationStatus; + private String approvalStatus; + private String currentApprovalNode; + private Long currentApproverId; + private String currentApproverName; + private String receiptStatus; + private String paymentStatus; + private String budgetStatus; + private String sourceDocNo; + private String sourceDocType; + private String sourceSystem; + private LocalDate sourceDocDate; + private String sourceStatus; + private String payeeName; + private Long payeeBankId; + private String bankName; + private String bankAccountMask; + private String returnReason; + private LocalDateTime submitTime; + private LocalDateTime approveTime; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + private List expenseItems; + private List invoices; + private List attachments; + private List approvalRecords; + private List payments; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/ReimApplicationSummary.java b/src/main/java/com/finance/system/dto/ReimApplicationSummary.java new file mode 100644 index 0000000..c4d6fb8 --- /dev/null +++ b/src/main/java/com/finance/system/dto/ReimApplicationSummary.java @@ -0,0 +1,34 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ReimApplicationSummary { + private Long id; + private String applicationNo; + private String title; + private String applicantName; + private String departmentName; + private String expenseTypeName; + private String category; + private BigDecimal totalAmount; + private String applicationStatus; + private String approvalStatus; + private String currentApprovalNode; + private String receiptStatus; + private String paymentStatus; + private String budgetStatus; + private String sourceDocNo; + private String sourceStatus; + private String returnReason; + private LocalDateTime submitTime; + private LocalDateTime createdAt; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/dto/UserProfile.java b/src/main/java/com/finance/system/dto/UserProfile.java new file mode 100644 index 0000000..3c38bb0 --- /dev/null +++ b/src/main/java/com/finance/system/dto/UserProfile.java @@ -0,0 +1,28 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class UserProfile { + private Long id; + private String employeeNo; + private String realName; + private String avatarUrl; + private String email; + private String departmentName; + private String position; + private String userType; + private String status; + private String feishuStatus; + private String lastLoginAt; + private List roleCodes; + private List groupNames; +} diff --git a/src/main/java/com/finance/system/dto/WorkbenchDto.java b/src/main/java/com/finance/system/dto/WorkbenchDto.java new file mode 100644 index 0000000..28c7ed4 --- /dev/null +++ b/src/main/java/com/finance/system/dto/WorkbenchDto.java @@ -0,0 +1,18 @@ +package com.finance.system.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class WorkbenchDto { + private UserProfile user; + private List reimbursements; + private List payments; + private DashboardStats stats; +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/entity/FeishuDirectoryState.java b/src/main/java/com/finance/system/entity/FeishuDirectoryState.java new file mode 100644 index 0000000..8994ad7 --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuDirectoryState.java @@ -0,0 +1,22 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import java.time.Instant; + +/** Mapping also supports the explicitly local Hibernate-created database. Mutated with fenced SQL. */ +@Entity +@Table(name = "feishu_directory_state") +public class FeishuDirectoryState { + @Id private Integer id; + @Column(length = 36) private String owner; + private Instant leaseUntil; + @Column(length = 64) private String context; + @Column(columnDefinition = "TEXT") private String lastRun; + @Column(length = 36) private String lastSuccessfulRunId; + private Instant lastSuccessfulAt; + @Column(length = 64) private String successfulContext; + @Column(name = "last_snapshot", columnDefinition = "TEXT") private String lastSnapshot; + + public String getLastSnapshot() { return lastSnapshot; } + public void setLastSnapshot(String lastSnapshot) { this.lastSnapshot = lastSnapshot; } +} diff --git a/src/main/java/com/finance/system/entity/IntFeishuApproval.java b/src/main/java/com/finance/system/entity/IntFeishuApproval.java new file mode 100644 index 0000000..c6cbd74 --- /dev/null +++ b/src/main/java/com/finance/system/entity/IntFeishuApproval.java @@ -0,0 +1,52 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; + +import java.time.LocalDateTime; + +/** + * 飞书审批同步表 + * 记录审批实例与报销单的关联关系 + */ +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "int_feishu_approval") +public class IntFeishuApproval { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** 关联报销申请ID */ + @Column(name = "application_id", nullable = false) + private Long applicationId; + + /** 飞书审批实例编码 */ + @Column(name = "feishu_instance_code", length = 200) + private String feishuInstanceCode; + + /** 飞书审批定义编码 */ + @Column(name = "feishu_approval_code", length = 200) + private String feishuApprovalCode; + + /** 审批状态: PENDING / APPROVED / REJECTED / CANCELLED */ + @Column(name = "status", length = 30) + private String status = "PENDING"; + + /** 回调数据(原始JSON) */ + @Column(name = "callback_data", columnDefinition = "TEXT") + private String callbackData; + + /** 最后同步时间 */ + @Column(name = "synced_at") + private LocalDateTime syncedAt; + + /** 创建时间 */ + @Column(name = "created_at") + private LocalDateTime createdAt; +} diff --git a/src/main/java/com/finance/system/entity/ReimApplication.java b/src/main/java/com/finance/system/entity/ReimApplication.java new file mode 100644 index 0000000..4ccd2d6 --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimApplication.java @@ -0,0 +1,126 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import org.hibernate.annotations.Where; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_application") +@Where(clause = "deleted = false") +public class ReimApplication { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "application_no", length = 50, nullable = false, unique = true) + private String applicationNo; + + @Column(length = 500, nullable = false) + private String title; + + @Column(name = "applicant_id", nullable = false) + private Long applicantId; + + @Column(name = "department_id", nullable = false) + private Long departmentId; + + @Column(name = "expense_type_id", nullable = false) + private Long expenseTypeId; + + @Column(length = 100) + private String category; + + @Column(name = "total_amount", nullable = false, precision = 18, scale = 2) + private BigDecimal totalAmount; + + @Column(columnDefinition = "TEXT") + private String description; + + @Column(name = "application_status", length = 30, nullable = false) + private String applicationStatus; + + @Column(name = "approval_status", length = 30) + private String approvalStatus; + + @Column(name = "current_approval_node", length = 100) + private String currentApprovalNode; + + @Column(name = "current_approver_id") + private Long currentApproverId; + + @Column(name = "receipt_status", length = 30) + private String receiptStatus; + + @Column(name = "payment_status", length = 30) + private String paymentStatus; + + @Column(name = "budget_status", length = 30) + private String budgetStatus; + + @Column(name = "source_doc_no", length = 100) + private String sourceDocNo; + + @Column(name = "source_doc_type", length = 100) + private String sourceDocType; + + @Column(name = "source_system", length = 50) + private String sourceSystem; + + @Column(name = "source_doc_date") + private LocalDate sourceDocDate; + + @Column(name = "source_status", length = 30) + private String sourceStatus; + + @Column(name = "payee_name", length = 200) + private String payeeName; + + @Column(name = "payee_bank_id") + private Long payeeBankId; + + @Column(name = "return_reason", columnDefinition = "TEXT") + private String returnReason; + + @Column(name = "submit_time") + private LocalDateTime submitTime; + + @Column(name = "approve_time") + private LocalDateTime approveTime; + + @Version + private Integer version; + + @Builder.Default + @Column(nullable = false) + private Boolean deleted = false; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/ReimApprovalRecord.java b/src/main/java/com/finance/system/entity/ReimApprovalRecord.java new file mode 100644 index 0000000..4c51c5f --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimApprovalRecord.java @@ -0,0 +1,51 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_approval_record") +public class ReimApprovalRecord { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "application_id", nullable = false) + private Long applicationId; + + @Column(name = "node_name", length = 200, nullable = false) + private String nodeName; + + @Column(name = "approver_id", nullable = false) + private Long approverId; + + @Column(length = 30, nullable = false) + private String action; + + @Column(columnDefinition = "TEXT") + private String comment; + + @Column(length = 500) + private String signature; + + @Column(name = "action_time") + private LocalDateTime actionTime; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/ReimAttachment.java b/src/main/java/com/finance/system/entity/ReimAttachment.java new file mode 100644 index 0000000..4ae96be --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimAttachment.java @@ -0,0 +1,51 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_attachment") +public class ReimAttachment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "application_id", nullable = false) + private Long applicationId; + + @Column(name = "file_name", length = 500, nullable = false) + private String fileName; + + @Column(name = "file_type", length = 100) + private String fileType; + + @Column(name = "file_url", length = 500, nullable = false) + private String fileUrl; + + @Column(name = "file_size") + private Long fileSize; + + @Column(name = "content_type", length = 100) + private String contentType; + + @Column(name = "uploader_id", nullable = false) + private Long uploaderId; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/ReimExpenseItem.java b/src/main/java/com/finance/system/entity/ReimExpenseItem.java new file mode 100644 index 0000000..c8b3f54 --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimExpenseItem.java @@ -0,0 +1,56 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_expense_item") +public class ReimExpenseItem { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "application_id", nullable = false) + private Long applicationId; + + @Column(name = "seq_no", nullable = false) + private Integer seqNo; + + @Column(name = "expense_date", nullable = false) + private LocalDate expenseDate; + + @Column(length = 100, nullable = false) + private String category; + + @Column(length = 500) + private String description; + + @Column(nullable = false, precision = 18, scale = 2) + private BigDecimal amount; + + @Column(length = 10) + private String currency; + + @Column(name = "invoice_count") + private Integer invoiceCount; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/ReimInvoice.java b/src/main/java/com/finance/system/entity/ReimInvoice.java new file mode 100644 index 0000000..dda21fc --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimInvoice.java @@ -0,0 +1,71 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_invoice") +public class ReimInvoice { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "application_id", nullable = false) + private Long applicationId; + + @Column(name = "expense_item_id") + private Long expenseItemId; + + @Column(name = "invoice_no", length = 100, nullable = false) + private String invoiceNo; + + @Column(name = "invoice_code", length = 100) + private String invoiceCode; + + @Column(name = "invoice_type", length = 50) + private String invoiceType; + + @Column(name = "issue_date") + private LocalDate issueDate; + + @Column(precision = 18, scale = 2) + private BigDecimal amount; + + @Column(name = "tax_amount", precision = 18, scale = 2) + private BigDecimal taxAmount; + + @Column(name = "seller_name", length = 500) + private String sellerName; + + @Column(name = "seller_tax_no", length = 100) + private String sellerTaxNo; + + @Column(name = "file_url", length = 500) + private String fileUrl; + + @Column(name = "ocr_result", columnDefinition = "TEXT") + private String ocrResult; + + @Column(name = "verify_status", length = 30) + private String verifyStatus; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/ReimPayment.java b/src/main/java/com/finance/system/entity/ReimPayment.java new file mode 100644 index 0000000..aa30665 --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimPayment.java @@ -0,0 +1,98 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_payment") +public class ReimPayment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "payment_no", length = 50, nullable = false, unique = true) + private String paymentNo; + + @Column(name = "application_id", nullable = false) + private Long applicationId; + + @Column(name = "payee_id", nullable = false) + private Long payeeId; + + @Column(name = "payee_bank_id") + private Long payeeBankId; + + @Column(name = "total_amount", nullable = false, precision = 18, scale = 2) + private BigDecimal totalAmount; + + @Column(name = "payment_amount", nullable = false, precision = 18, scale = 2) + private BigDecimal paymentAmount; + + @Column(name = "paid_amount", precision = 18, scale = 2) + private BigDecimal paidAmount; + + @Column(name = "remaining_amount", precision = 18, scale = 2) + private BigDecimal remainingAmount; + + @Column(name = "payment_method", length = 50) + private String paymentMethod; + + @Column(name = "bank_account_no", length = 100) + private String bankAccountNo; + + @Column(name = "bank_account_name", length = 200) + private String bankAccountName; + + @Column(name = "reference_no", length = 100) + private String referenceNo; + + @Column(name = "operator_id", nullable = false) + private Long operatorId; + + @Column(name = "payment_status", length = 30) + private String paymentStatus; + + @Column(name = "payment_time") + private LocalDateTime paymentTime; + + @Column(name = "idempotency_key", length = 100, unique = true) + private String idempotencyKey; + + @Column(columnDefinition = "TEXT") + private String remark; + + @Version + private Integer version; + + @Builder.Default + @Column(nullable = false) + private Boolean deleted = false; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/ReimPaymentInstallment.java b/src/main/java/com/finance/system/entity/ReimPaymentInstallment.java new file mode 100644 index 0000000..9d1a852 --- /dev/null +++ b/src/main/java/com/finance/system/entity/ReimPaymentInstallment.java @@ -0,0 +1,58 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "reim_payment_installment") +public class ReimPaymentInstallment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "payment_id", nullable = false) + private Long paymentId; + + @Column(name = "seq_no", nullable = false) + private Integer seqNo; + + @Column(nullable = false, precision = 18, scale = 2) + private BigDecimal amount; + + @Column(name = "payment_method", length = 50) + private String paymentMethod; + + @Column(name = "reference_no", length = 100) + private String referenceNo; + + @Column(length = 30) + private String status; + + @Column(name = "operated_by") + private Long operatedBy; + + @Column(name = "operated_at") + private LocalDateTime operatedAt; + + @Column(length = 500) + private String remark; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysApprovalNode.java b/src/main/java/com/finance/system/entity/SysApprovalNode.java new file mode 100644 index 0000000..562054a --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysApprovalNode.java @@ -0,0 +1,63 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_approval_node") +public class SysApprovalNode { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "node_code", length = 50, nullable = false, unique = true) + private String nodeCode; + + @Column(name = "node_name", length = 200, nullable = false) + private String nodeName; + + @Column(name = "approver_type", length = 50, nullable = false) + private String approverType; + + @Column(name = "approver_id") + private Long approverId; + + @Column(name = "approver_role", length = 50) + private String approverRole; + + @Column(name = "sort_order", nullable = false) + private Integer sortOrder; + + @Column(name = "timeout_hours") + private Integer timeoutHours; + + @Column(length = 20) + private String status; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysBankAccount.java b/src/main/java/com/finance/system/entity/SysBankAccount.java new file mode 100644 index 0000000..866f619 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysBankAccount.java @@ -0,0 +1,64 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_bank_account") +public class SysBankAccount { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id", nullable = false) + private Long userId; + + @Column(name = "bank_name", length = 200, nullable = false) + private String bankName; + + @Column(name = "branch_name", length = 200) + private String branchName; + + @Column(name = "account_no", length = 100, nullable = false) + private String accountNo; + + @Column(name = "account_no_mask", length = 50) + private String accountNoMask; + + @Column(name = "account_name", length = 200, nullable = false) + private String accountName; + + @Column(name = "is_default") + private Boolean isDefault; + + @Column(length = 20) + private String status; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysBudget.java b/src/main/java/com/finance/system/entity/SysBudget.java new file mode 100644 index 0000000..ccebaa6 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysBudget.java @@ -0,0 +1,64 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_budget") +public class SysBudget { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "dept_id", nullable = false) + private Long deptId; + + @Column(name = "expense_type_id", nullable = false) + private Long expenseTypeId; + + @Column(name = "fiscal_year", nullable = false) + private Integer fiscalYear; + + @Column(name = "fiscal_month") + private Integer fiscalMonth; + + @Column(name = "total_amount", nullable = false, precision = 18, scale = 2) + private BigDecimal totalAmount; + + @Column(name = "used_amount", nullable = false, precision = 18, scale = 2) + private BigDecimal usedAmount; + + @Column(name = "frozen_amount", nullable = false, precision = 18, scale = 2) + private BigDecimal frozenAmount; + + @Column(length = 20) + private String status; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysDepartment.java b/src/main/java/com/finance/system/entity/SysDepartment.java new file mode 100644 index 0000000..b3d804c --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysDepartment.java @@ -0,0 +1,54 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_department") +public class SysDepartment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "dept_code", length = 50, nullable = false, unique = true) + private String deptCode; + + @Column(name = "dept_name", length = 200, nullable = false) + private String deptName; + + @Column(name = "parent_id") + private Long parentId; + + @Column(name = "sort_order") + private Integer sortOrder; + + @Column(length = 20) + private String status; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysExpenseType.java b/src/main/java/com/finance/system/entity/SysExpenseType.java new file mode 100644 index 0000000..1cc9211 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysExpenseType.java @@ -0,0 +1,60 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_expense_type") +public class SysExpenseType { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "type_code", length = 50, nullable = false, unique = true) + private String typeCode; + + @Column(name = "type_name", length = 200, nullable = false) + private String typeName; + + @Column(length = 50, nullable = false) + private String category; + + @Column(name = "parent_id") + private Long parentId; + + @Column(name = "sort_order") + private Integer sortOrder; + + @Column(length = 20) + private String status; + + @Column(name = "kingdee_form_id", length = 100) + private String kingdeeFormId; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysIntegrationConfig.java b/src/main/java/com/finance/system/entity/SysIntegrationConfig.java new file mode 100644 index 0000000..4c8d823 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysIntegrationConfig.java @@ -0,0 +1,25 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data @Builder @NoArgsConstructor @AllArgsConstructor +@Entity +@Table(name = "sys_integration_config", uniqueConstraints = @UniqueConstraint(columnNames = {"provider", "config_key"})) +public class SysIntegrationConfig { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(nullable = false, length = 20) private String provider; + @Column(name = "config_key", nullable = false, length = 80) private String configKey; + @Column(name = "config_value", length = 2000) private String configValue; + @Column(nullable = false) private Boolean secret; + @Column(nullable = false) private Boolean enabled; + @Column(name = "created_at") private LocalDateTime createdAt; + @Column(name = "updated_at") private LocalDateTime updatedAt; + @PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } + @PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); } +} diff --git a/src/main/java/com/finance/system/entity/SysOauthState.java b/src/main/java/com/finance/system/entity/SysOauthState.java new file mode 100644 index 0000000..c2acff7 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysOauthState.java @@ -0,0 +1,26 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +/** A short-lived, one-time Feishu OAuth state shared by all application instances. */ +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_oauth_state") +public class SysOauthState { + + @Id + @Column(name = "state", length = 128, nullable = false) + private String state; + + @Column(name = "expires_at", nullable = false) + private Long expiresAt; +} diff --git a/src/main/java/com/finance/system/entity/SysPermission.java b/src/main/java/com/finance/system/entity/SysPermission.java new file mode 100644 index 0000000..1005ed8 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysPermission.java @@ -0,0 +1,42 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_permission") +public class SysPermission { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "permission_code", nullable = false, length = 120, unique = true) + private String permissionCode; + @Column(name = "permission_name", nullable = false, length = 200) + private String permissionName; + @Column(name = "permission_type", nullable = false, length = 20) + private String permissionType; + @Column(name = "parent_code", length = 120) + private String parentCode; + @Column(length = 200) + private String resource; + @Column(name = "default_access", length = 20) + private String defaultAccess; + @Column(name = "created_at") + private LocalDateTime createdAt; + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } + @PreUpdate + protected void onUpdate() { updatedAt = LocalDateTime.now(); } +} diff --git a/src/main/java/com/finance/system/entity/SysRole.java b/src/main/java/com/finance/system/entity/SysRole.java new file mode 100644 index 0000000..2b82e24 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysRole.java @@ -0,0 +1,41 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_role") +public class SysRole { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "role_code", nullable = false, length = 80, unique = true) + private String roleCode; + @Column(name = "role_name", nullable = false, length = 200) + private String roleName; + @Column(length = 500) + private String description; + @Column(length = 20) + private String status; + @Column(name = "built_in", nullable = false) + private Boolean builtIn; + @Column(name = "created_at") + private LocalDateTime createdAt; + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } + @PreUpdate + protected void onUpdate() { updatedAt = LocalDateTime.now(); } +} diff --git a/src/main/java/com/finance/system/entity/SysRolePermission.java b/src/main/java/com/finance/system/entity/SysRolePermission.java new file mode 100644 index 0000000..382868e --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysRolePermission.java @@ -0,0 +1,33 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_role_permission", uniqueConstraints = @UniqueConstraint(columnNames = {"role_id", "permission_id"})) +public class SysRolePermission { + @EmbeddedId + private SysRolePermissionId id; + @Column(name = "access_level", nullable = false, length = 20) + private String accessLevel; + + public SysRolePermission(Long roleId, Long permissionId, String accessLevel) { + this.id = new SysRolePermissionId(roleId, permissionId); + this.accessLevel = accessLevel; + } + + @Embeddable + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class SysRolePermissionId implements java.io.Serializable { + @Column(name = "role_id") private Long roleId; + @Column(name = "permission_id") private Long permissionId; + } +} diff --git a/src/main/java/com/finance/system/entity/SysUser.java b/src/main/java/com/finance/system/entity/SysUser.java new file mode 100644 index 0000000..a9f9fda --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysUser.java @@ -0,0 +1,90 @@ +package com.finance.system.entity; + +import javax.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_user") +@org.hibernate.annotations.DynamicUpdate +public class SysUser { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "feishu_open_id", length = 100, unique = true) + private String feishuOpenId; + + @Column(name = "feishu_user_id", length = 100, unique = true) + private String feishuUserId; + + @Column(name = "employee_no", length = 50, unique = true) + private String employeeNo; + + @Column(name = "real_name", length = 100, nullable = false) + private String realName; + + @Column(name = "avatar_url", length = 500) + private String avatarUrl; + + @Column(length = 200) + private String email; + + @Column(length = 20) + private String mobile; + + @Column(name = "department_id") + private Long departmentId; + + @Column(length = 200) + private String position; + + @Column(name = "user_type", length = 30) + private String userType; + + /** Only used by the explicitly local password-login flow. */ + @Column(name = "password_hash", length = 100) + private String passwordHash; + + @Column(length = 20) + private String status; + + @Builder.Default + @Column(name = "directory_status", nullable = false, length = 20, updatable = false) + private String directoryStatus = "UNKNOWN"; + @Column(name = "directory_context", length = 64, updatable = false) + private String directoryContext; + @Column(name = "directory_verified_at", updatable = false) + private java.time.Instant directoryVerifiedAt; + @Column(name = "directory_last_seen_run_id", length = 36, updatable = false) + private String directoryLastSeenRunId; + + @Column(name = "last_login_at") + private LocalDateTime lastLoginAt; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysUserGroup.java b/src/main/java/com/finance/system/entity/SysUserGroup.java new file mode 100644 index 0000000..4e92a8e --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysUserGroup.java @@ -0,0 +1,30 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_user_group") +public class SysUserGroup { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "group_code", nullable = false, length = 80, unique = true) + private String groupCode; + @Column(name = "group_name", nullable = false, length = 200) + private String groupName; + @Column(length = 500) private String description; + @Column(length = 20) private String status; + @Column(name = "created_at") private LocalDateTime createdAt; + @Column(name = "updated_at") private LocalDateTime updatedAt; + @PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } + @PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); } +} diff --git a/src/main/java/com/finance/system/entity/SysUserGroupMember.java b/src/main/java/com/finance/system/entity/SysUserGroupMember.java new file mode 100644 index 0000000..c977d2d --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysUserGroupMember.java @@ -0,0 +1,22 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_user_group_member", uniqueConstraints = @UniqueConstraint(columnNames = {"group_id", "user_id"})) +public class SysUserGroupMember { + @EmbeddedId private SysUserGroupMemberId id; + public SysUserGroupMember(Long groupId, Long userId) { this.id = new SysUserGroupMemberId(groupId, userId); } + @Embeddable @Data @NoArgsConstructor @AllArgsConstructor + public static class SysUserGroupMemberId implements java.io.Serializable { + @Column(name = "group_id") private Long groupId; + @Column(name = "user_id") private Long userId; + } +} diff --git a/src/main/java/com/finance/system/entity/SysUserGroupRole.java b/src/main/java/com/finance/system/entity/SysUserGroupRole.java new file mode 100644 index 0000000..9a79242 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysUserGroupRole.java @@ -0,0 +1,22 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_user_group_role", uniqueConstraints = @UniqueConstraint(columnNames = {"group_id", "role_id"})) +public class SysUserGroupRole { + @EmbeddedId private SysUserGroupRoleId id; + public SysUserGroupRole(Long groupId, Long roleId) { this.id = new SysUserGroupRoleId(groupId, roleId); } + @Embeddable @Data @NoArgsConstructor @AllArgsConstructor + public static class SysUserGroupRoleId implements java.io.Serializable { + @Column(name = "group_id") private Long groupId; + @Column(name = "role_id") private Long roleId; + } +} diff --git a/src/main/java/com/finance/system/entity/SysUserRole.java b/src/main/java/com/finance/system/entity/SysUserRole.java new file mode 100644 index 0000000..42a9235 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysUserRole.java @@ -0,0 +1,28 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_user_role", uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "role_id"})) +public class SysUserRole { + @EmbeddedId + private SysUserRoleId id; + + public SysUserRole(Long userId, Long roleId) { this.id = new SysUserRoleId(userId, roleId); } + + @Embeddable + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class SysUserRoleId implements java.io.Serializable { + @Column(name = "user_id") private Long userId; + @Column(name = "role_id") private Long roleId; + } +} diff --git a/src/main/java/com/finance/system/entity/SysWebhookEvent.java b/src/main/java/com/finance/system/entity/SysWebhookEvent.java new file mode 100644 index 0000000..8b6fb48 --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysWebhookEvent.java @@ -0,0 +1,42 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.PrePersist; +import javax.persistence.Table; +import java.time.LocalDateTime; + +/** Shared inbox record used to make Feishu webhook delivery idempotent. */ +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_webhook_event") +public class SysWebhookEvent { + + public static final String PROCESSING = "PROCESSING"; + public static final String PROCESSED = "PROCESSED"; + public static final String FAILED = "FAILED"; + + @Id + @Column(name = "event_id", length = 200, nullable = false) + private String eventId; + + @Column(name = "status", length = 20, nullable = false) + private String status; + + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @PrePersist + protected void onCreate() { + if (createdAt == null) { + createdAt = LocalDateTime.now(); + } + } +} diff --git a/src/main/java/com/finance/system/enums/ApplicationStatus.java b/src/main/java/com/finance/system/enums/ApplicationStatus.java new file mode 100644 index 0000000..9169475 --- /dev/null +++ b/src/main/java/com/finance/system/enums/ApplicationStatus.java @@ -0,0 +1,6 @@ +package com.finance.system.enums; + +public enum ApplicationStatus { + DRAFT, + SUBMITTED +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/ApprovalAction.java b/src/main/java/com/finance/system/enums/ApprovalAction.java new file mode 100644 index 0000000..3ac0561 --- /dev/null +++ b/src/main/java/com/finance/system/enums/ApprovalAction.java @@ -0,0 +1,8 @@ +package com.finance.system.enums; + +public enum ApprovalAction { + APPROVE, + REJECT, + TRANSFER, + ADD_SIGN +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/ApprovalStatus.java b/src/main/java/com/finance/system/enums/ApprovalStatus.java new file mode 100644 index 0000000..de1a626 --- /dev/null +++ b/src/main/java/com/finance/system/enums/ApprovalStatus.java @@ -0,0 +1,8 @@ +package com.finance.system.enums; + +public enum ApprovalStatus { + PENDING, + APPROVED, + REJECTED, + CANCELLED +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/BudgetStatus.java b/src/main/java/com/finance/system/enums/BudgetStatus.java new file mode 100644 index 0000000..dd291a5 --- /dev/null +++ b/src/main/java/com/finance/system/enums/BudgetStatus.java @@ -0,0 +1,7 @@ +package com.finance.system.enums; + +public enum BudgetStatus { + PENDING, + OCCUPIED, + EXECUTED +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/PaymentStatus.java b/src/main/java/com/finance/system/enums/PaymentStatus.java new file mode 100644 index 0000000..3bf9d3e --- /dev/null +++ b/src/main/java/com/finance/system/enums/PaymentStatus.java @@ -0,0 +1,7 @@ +package com.finance.system.enums; + +public enum PaymentStatus { + UNPAID, + PARTIAL, + PAID +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/ReceiptStatus.java b/src/main/java/com/finance/system/enums/ReceiptStatus.java new file mode 100644 index 0000000..3c7662b --- /dev/null +++ b/src/main/java/com/finance/system/enums/ReceiptStatus.java @@ -0,0 +1,6 @@ +package com.finance.system.enums; + +public enum ReceiptStatus { + UNRECEIVED, + RECEIVED +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/SyncStatus.java b/src/main/java/com/finance/system/enums/SyncStatus.java new file mode 100644 index 0000000..0d852ea --- /dev/null +++ b/src/main/java/com/finance/system/enums/SyncStatus.java @@ -0,0 +1,7 @@ +package com.finance.system.enums; + +public enum SyncStatus { + PENDING, + SYNCED, + FAILED +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/enums/UserType.java b/src/main/java/com/finance/system/enums/UserType.java new file mode 100644 index 0000000..ffbdd87 --- /dev/null +++ b/src/main/java/com/finance/system/enums/UserType.java @@ -0,0 +1,7 @@ +package com.finance.system.enums; + +public enum UserType { + EMPLOYEE, + FINANCE, + ADMIN +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/exception/BadRequestException.java b/src/main/java/com/finance/system/exception/BadRequestException.java new file mode 100644 index 0000000..62aaa1d --- /dev/null +++ b/src/main/java/com/finance/system/exception/BadRequestException.java @@ -0,0 +1,7 @@ +package com.finance.system.exception; + +public class BadRequestException extends RuntimeException { + public BadRequestException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/exception/BusinessException.java b/src/main/java/com/finance/system/exception/BusinessException.java new file mode 100644 index 0000000..6dcbfa8 --- /dev/null +++ b/src/main/java/com/finance/system/exception/BusinessException.java @@ -0,0 +1,18 @@ +package com.finance.system.exception; + +public class BusinessException extends RuntimeException { + private final int statusCode; + + public BusinessException(String message) { + this(message, 409); + } + + public BusinessException(String message, int statusCode) { + super(message); + this.statusCode = statusCode; + } + + public int getStatusCode() { + return statusCode; + } +} diff --git a/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java b/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..edd1aae --- /dev/null +++ b/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java @@ -0,0 +1,75 @@ +package com.finance.system.exception; + +import com.finance.system.dto.ApiResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity> handleResourceNotFound(ResourceNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(ApiResponse.error(404, e.getMessage())); + } + + @ExceptionHandler(BadRequestException.class) + public ResponseEntity> handleBadRequest(BadRequestException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(400, e.getMessage())); + } + + @ExceptionHandler(UnauthorizedException.class) + public ResponseEntity> handleUnauthorized(UnauthorizedException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(ApiResponse.error(401, e.getMessage())); + } + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity> handleAccessDenied(AccessDeniedException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(ApiResponse.error(403, "权限不足,无法访问")); + } + + @ExceptionHandler(BusinessException.class) + public ResponseEntity> handleBusiness(BusinessException e) { + int statusCode = e.getStatusCode(); + HttpStatus status = HttpStatus.resolve(statusCode); + if (status == null) { + status = HttpStatus.CONFLICT; + statusCode = status.value(); + } + return ResponseEntity.status(status) + .body(ApiResponse.error(statusCode, e.getMessage())); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleValidation( + MethodArgumentNotValidException e) { + Map errors = new HashMap<>(); + e.getBindingResult().getAllErrors().forEach(error -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(400, "参数校验失败", errors)); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGeneral(Exception e) { + log.error("Unexpected error", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(ApiResponse.error(500, "服务器内部错误")); + } +} diff --git a/src/main/java/com/finance/system/exception/ResourceNotFoundException.java b/src/main/java/com/finance/system/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..59bd69f --- /dev/null +++ b/src/main/java/com/finance/system/exception/ResourceNotFoundException.java @@ -0,0 +1,7 @@ +package com.finance.system.exception; + +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/exception/UnauthorizedException.java b/src/main/java/com/finance/system/exception/UnauthorizedException.java new file mode 100644 index 0000000..b2de375 --- /dev/null +++ b/src/main/java/com/finance/system/exception/UnauthorizedException.java @@ -0,0 +1,7 @@ +package com.finance.system.exception; + +public class UnauthorizedException extends RuntimeException { + public UnauthorizedException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java b/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java new file mode 100644 index 0000000..bb48ce9 --- /dev/null +++ b/src/main/java/com/finance/system/repository/IntFeishuApprovalRepository.java @@ -0,0 +1,22 @@ +package com.finance.system.repository; + +import com.finance.system.entity.IntFeishuApproval; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface IntFeishuApprovalRepository extends JpaRepository { + + Optional findByFeishuInstanceCode(String feishuInstanceCode); + + @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("select a from IntFeishuApproval a where a.feishuInstanceCode = :instanceCode") + Optional findByFeishuInstanceCodeForUpdate(@Param("instanceCode") String instanceCode); + + Optional findByApplicationId(Long applicationId); +} diff --git a/src/main/java/com/finance/system/repository/ReimApplicationRepository.java b/src/main/java/com/finance/system/repository/ReimApplicationRepository.java new file mode 100644 index 0000000..e941d25 --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimApplicationRepository.java @@ -0,0 +1,49 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimApplication; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.data.jpa.repository.Lock; +import javax.persistence.LockModeType; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +@Repository +public interface ReimApplicationRepository extends JpaRepository { + + ReimApplication findByApplicationNo(String applicationNo); + + List findByApplicantIdOrderByCreatedAtDesc(Long applicantId); + + Page findByApplicantIdOrderByCreatedAtDesc(Long applicantId, Pageable pageable); + + Page findByApplicantIdAndApprovalStatus(Long applicantId, String approvalStatus, Pageable pageable); + + Page findByApplicantIdAndApplicationStatus(Long applicantId, String applicationStatus, Pageable pageable); + + Page findByApplicationStatus(String applicationStatus, Pageable pageable); + + Page findByApplicationStatusAndApprovalStatus(String applicationStatus, String approvalStatus, Pageable pageable); + + Page findByApprovalStatus(String approvalStatus, Pageable pageable); + + Page findByApprovalStatusAndPaymentStatus(String approvalStatus, String paymentStatus, Pageable pageable); + + Page findByApprovalStatusAndPaymentStatusIn(String approvalStatus, List paymentStatuses, Pageable pageable); + + Page findByCurrentApproverIdAndApprovalStatus(Long currentApproverId, String approvalStatus, Pageable pageable); + + List findBySourceDocNoAndSourceSystem(String sourceDocNo, String sourceSystem); + + List findTopByApplicationNoStartingWithOrderByApplicationNoDesc(String prefix); + + List findFirst10ByApplicantIdOrderByCreatedAtDesc(Long applicantId); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select a from ReimApplication a where a.id = :id and a.deleted = false") + java.util.Optional findByIdForUpdate(@Param("id") Long id); +} diff --git a/src/main/java/com/finance/system/repository/ReimApprovalRecordRepository.java b/src/main/java/com/finance/system/repository/ReimApprovalRecordRepository.java new file mode 100644 index 0000000..2210667 --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimApprovalRecordRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimApprovalRecord; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ReimApprovalRecordRepository extends JpaRepository { + + List findByApplicationIdOrderByActionTimeAsc(Long applicationId); + + List findByApproverId(Long approverId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java b/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java new file mode 100644 index 0000000..4243e56 --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java @@ -0,0 +1,13 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimAttachment; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ReimAttachmentRepository extends JpaRepository { + + List findByApplicationId(Long applicationId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/ReimExpenseItemRepository.java b/src/main/java/com/finance/system/repository/ReimExpenseItemRepository.java new file mode 100644 index 0000000..5b44781 --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimExpenseItemRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimExpenseItem; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ReimExpenseItemRepository extends JpaRepository { + + List findByApplicationId(Long applicationId); + + void deleteByApplicationId(Long applicationId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/ReimInvoiceRepository.java b/src/main/java/com/finance/system/repository/ReimInvoiceRepository.java new file mode 100644 index 0000000..6a0595a --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimInvoiceRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimInvoice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ReimInvoiceRepository extends JpaRepository { + + List findByApplicationId(Long applicationId); + + ReimInvoice findByInvoiceNo(String invoiceNo); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/ReimPaymentInstallmentRepository.java b/src/main/java/com/finance/system/repository/ReimPaymentInstallmentRepository.java new file mode 100644 index 0000000..fcf9368 --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimPaymentInstallmentRepository.java @@ -0,0 +1,13 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimPaymentInstallment; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ReimPaymentInstallmentRepository extends JpaRepository { + + List findByPaymentId(Long paymentId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/ReimPaymentRepository.java b/src/main/java/com/finance/system/repository/ReimPaymentRepository.java new file mode 100644 index 0000000..bd535df --- /dev/null +++ b/src/main/java/com/finance/system/repository/ReimPaymentRepository.java @@ -0,0 +1,25 @@ +package com.finance.system.repository; + +import com.finance.system.entity.ReimPayment; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ReimPaymentRepository extends JpaRepository { + + List findByApplicationId(Long applicationId); + + List findByPayeeId(Long payeeId); + + ReimPayment findByPaymentNo(String paymentNo); + + ReimPayment findByIdempotencyKey(String idempotencyKey); + + List findByOperatorId(Long operatorId); + + List findByPaymentStatus(String paymentStatus); + + List findTopByPaymentNoStartingWithOrderByPaymentNoDesc(String prefix); +} diff --git a/src/main/java/com/finance/system/repository/SysApprovalNodeRepository.java b/src/main/java/com/finance/system/repository/SysApprovalNodeRepository.java new file mode 100644 index 0000000..616963f --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysApprovalNodeRepository.java @@ -0,0 +1,19 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysApprovalNode; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysApprovalNodeRepository extends JpaRepository { + + List findByApproverRoleOrderBySortOrder(String approverRole); + + SysApprovalNode findByNodeCode(String nodeCode); + + SysApprovalNode findByNodeName(String nodeName); + + List findAllByOrderBySortOrder(); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysBankAccountRepository.java b/src/main/java/com/finance/system/repository/SysBankAccountRepository.java new file mode 100644 index 0000000..b166877 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysBankAccountRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysBankAccount; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysBankAccountRepository extends JpaRepository { + + List findByUserId(Long userId); + + SysBankAccount findByUserIdAndIsDefaultTrue(Long userId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysBudgetRepository.java b/src/main/java/com/finance/system/repository/SysBudgetRepository.java new file mode 100644 index 0000000..96c38cb --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysBudgetRepository.java @@ -0,0 +1,17 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysBudget; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysBudgetRepository extends JpaRepository { + + SysBudget findByDeptIdAndExpenseTypeIdAndFiscalYear(Long deptId, Long expenseTypeId, Integer fiscalYear); + + List findByDeptId(Long deptId); + + List findByExpenseTypeId(Long expenseTypeId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysDepartmentRepository.java b/src/main/java/com/finance/system/repository/SysDepartmentRepository.java new file mode 100644 index 0000000..f41cc48 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysDepartmentRepository.java @@ -0,0 +1,17 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysDepartment; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysDepartmentRepository extends JpaRepository { + + SysDepartment findByDeptCode(String deptCode); + + List findByParentId(Long parentId); + + List findByStatus(String status); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysExpenseTypeRepository.java b/src/main/java/com/finance/system/repository/SysExpenseTypeRepository.java new file mode 100644 index 0000000..78bcde1 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysExpenseTypeRepository.java @@ -0,0 +1,17 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysExpenseType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysExpenseTypeRepository extends JpaRepository { + + SysExpenseType findByTypeCode(String typeCode); + + List findByCategory(String category); + + List findByStatus(String status); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java b/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java new file mode 100644 index 0000000..3abeca0 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java @@ -0,0 +1,14 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysIntegrationConfig; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface SysIntegrationConfigRepository extends JpaRepository { + Optional findByProviderAndConfigKey(String provider, String configKey); + List findByProviderOrderByConfigKeyAsc(String provider); +} diff --git a/src/main/java/com/finance/system/repository/SysOauthStateRepository.java b/src/main/java/com/finance/system/repository/SysOauthStateRepository.java new file mode 100644 index 0000000..ba9b1b9 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysOauthStateRepository.java @@ -0,0 +1,28 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysOauthState; +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.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface SysOauthStateRepository extends JpaRepository { + + Optional findByStateAndExpiresAtGreaterThan(String state, Long now); + + @Modifying + @Query("delete from SysOauthState s where s.expiresAt <= :now") + int deleteExpired(@Param("now") Long now); + + /** + * The expiry predicate is part of the delete so two nodes cannot consume + * the same valid state, and an expired state cannot be consumed. + */ + @Modifying + @Query("delete from SysOauthState s where s.state = :state and s.expiresAt > :now") + int consumeIfValid(@Param("state") String state, @Param("now") Long now); +} diff --git a/src/main/java/com/finance/system/repository/SysPermissionRepository.java b/src/main/java/com/finance/system/repository/SysPermissionRepository.java new file mode 100644 index 0000000..5fa073f --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysPermissionRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysPermission; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +@Repository +public interface SysPermissionRepository extends JpaRepository { + Optional findByPermissionCode(String permissionCode); + List findByPermissionCodeIn(Collection codes); +} diff --git a/src/main/java/com/finance/system/repository/SysRolePermissionRepository.java b/src/main/java/com/finance/system/repository/SysRolePermissionRepository.java new file mode 100644 index 0000000..71e7c79 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysRolePermissionRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysRolePermission; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysRolePermissionRepository extends JpaRepository { + List findByIdRoleId(Long roleId); + List findByIdRoleIdIn(Iterable roleIds); + void deleteByIdRoleId(Long roleId); + long countByIdRoleId(Long roleId); +} diff --git a/src/main/java/com/finance/system/repository/SysRoleRepository.java b/src/main/java/com/finance/system/repository/SysRoleRepository.java new file mode 100644 index 0000000..431f96a --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysRoleRepository.java @@ -0,0 +1,13 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface SysRoleRepository extends JpaRepository { + Optional findByRoleCode(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 new file mode 100644 index 0000000..f4087ec --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysUserGroupMemberRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysUserGroupMember; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysUserGroupMemberRepository extends JpaRepository { + List findByIdGroupId(Long groupId); + List findByIdUserId(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 new file mode 100644 index 0000000..17ad7d6 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysUserGroupRepository.java @@ -0,0 +1,13 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysUserGroup; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface SysUserGroupRepository extends JpaRepository { + Optional findByGroupCode(String groupCode); + boolean existsByGroupCode(String groupCode); +} diff --git a/src/main/java/com/finance/system/repository/SysUserGroupRoleRepository.java b/src/main/java/com/finance/system/repository/SysUserGroupRoleRepository.java new file mode 100644 index 0000000..6dca99a --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysUserGroupRoleRepository.java @@ -0,0 +1,16 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysUserGroupRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysUserGroupRoleRepository extends JpaRepository { + List findByIdGroupId(Long groupId); + List findByIdRoleId(Long roleId); + void deleteByIdGroupId(Long groupId); + void deleteByIdRoleId(Long roleId); + long countByIdRoleId(Long roleId); +} diff --git a/src/main/java/com/finance/system/repository/SysUserRepository.java b/src/main/java/com/finance/system/repository/SysUserRepository.java new file mode 100644 index 0000000..b8c35d8 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysUserRepository.java @@ -0,0 +1,19 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysUserRepository extends JpaRepository { + + SysUser findByFeishuOpenId(String feishuOpenId); + + SysUser findByFeishuUserId(String feishuUserId); + + SysUser findByEmployeeNo(String employeeNo); + + List findByUserType(String userType); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysUserRoleRepository.java b/src/main/java/com/finance/system/repository/SysUserRoleRepository.java new file mode 100644 index 0000000..0e0b59a --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysUserRoleRepository.java @@ -0,0 +1,16 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysUserRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysUserRoleRepository extends JpaRepository { + List findByIdUserId(Long userId); + List findByIdRoleId(Long roleId); + void deleteByIdUserId(Long userId); + void deleteByIdRoleId(Long roleId); + long countByIdRoleId(Long roleId); +} diff --git a/src/main/java/com/finance/system/repository/SysWebhookEventRepository.java b/src/main/java/com/finance/system/repository/SysWebhookEventRepository.java new file mode 100644 index 0000000..6b8f28e --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysWebhookEventRepository.java @@ -0,0 +1,21 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysWebhookEvent; +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 javax.persistence.LockModeType; +import java.util.Optional; + +@Repository +public interface SysWebhookEventRepository extends JpaRepository, + SysWebhookEventRepositoryCustom { + + @Override + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select e from SysWebhookEvent e where e.eventId = :eventId") + Optional findById(@Param("eventId") String eventId); +} diff --git a/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryCustom.java b/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryCustom.java new file mode 100644 index 0000000..4101653 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryCustom.java @@ -0,0 +1,9 @@ +package com.finance.system.repository; + +import org.springframework.transaction.annotation.Transactional; + +public interface SysWebhookEventRepositoryCustom { + + @Transactional + int insertIfAbsent(String eventId); +} diff --git a/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java b/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java new file mode 100644 index 0000000..f400947 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysWebhookEventRepositoryImpl.java @@ -0,0 +1,58 @@ +package com.finance.system.repository; + +import org.hibernate.Session; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +/** Database-specific implementation of the inbox insert-if-absent operation. */ +public class SysWebhookEventRepositoryImpl implements SysWebhookEventRepositoryCustom { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public int insertIfAbsent(final String eventId) { + Session session = entityManager.unwrap(Session.class); + return session.doReturningWork(connection -> executeInsertIfAbsent(connection, eventId)); + } + + private int executeInsertIfAbsent(Connection connection, String eventId) { + boolean h2 = isH2(connection); + 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"; + + try (PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setString(1, eventId); + if (h2) { + statement.setString(2, eventId); + } + 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())) { + return 0; + } + throw new PersistenceException("Unable to insert webhook inbox event", e); + } + } + + private boolean isH2(Connection connection) { + try { + return "H2".equalsIgnoreCase(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 new file mode 100644 index 0000000..d22d70b --- /dev/null +++ b/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java @@ -0,0 +1,108 @@ +package com.finance.system.security; + +import com.finance.system.config.JwtConfig; +import com.finance.system.entity.SysUser; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.service.RoleService; +import io.jsonwebtoken.Claims; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +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; + +@Component +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtConfig jwtConfig; + private final SysUserRepository sysUserRepository; + @org.springframework.beans.factory.annotation.Autowired + private com.finance.system.adapter.feishu.FeishuDirectoryAccessService directoryAccess; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + String token = extractToken(request); + SecurityContextHolder.clearContext(); + + if (StringUtils.hasText(token)) { + try { + // Parsing validates the signature and exp. No user data or role + // is trusted from claims after this point. + Claims claims = jwtConfig.parseToken(token); + Long userId = extractUserId(claims); + if (userId != null) { + SysUser user = sysUserRepository.findById(userId).orElse(null); + if (user != null && "ACTIVE".equalsIgnoreCase(user.getStatus())) { + // Feishu OAuth is identity-only. Directory snapshots are + // operational data and must not invalidate an otherwise + // valid active-user JWT on every request. + setAuthentication(user); + } + } + } catch (Exception ignored) { + // Invalid/expired tokens remain anonymous and are handled by + // Spring Security's normal authentication entry point. + } + } + + filterChain.doFilter(request, response); + } + + private String extractToken(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } + + private Long extractUserId(Claims claims) { + Object value = claims.get("userId"); + if (value instanceof Number) { + return ((Number) value).longValue(); + } + if (value instanceof String && StringUtils.hasText((String) value)) { + return Long.valueOf((String) value); + } + return null; + } + + private void setAuthentication(SysUser user) { + String userType = RoleService.normalize(user.getUserType()); + UserPrincipal userPrincipal = UserPrincipal.builder() + .id(user.getId()) + .employeeNo(user.getEmployeeNo()) + .realName(user.getRealName()) + .userType(userType) + .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); + 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 new file mode 100644 index 0000000..f556063 --- /dev/null +++ b/src/main/java/com/finance/system/security/PermissionChecker.java @@ -0,0 +1,19 @@ +package com.finance.system.security; + +import com.finance.system.service.RoleService; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +/** Evaluates permissions from the database on every authorization decision. */ +@Component("permissionChecker") +public class PermissionChecker { + private final RoleService roleService; + public PermissionChecker(RoleService roleService) { this.roleService = roleService; } + + public boolean has(Authentication authentication, String permissionCode) { + 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); + } +} diff --git a/src/main/java/com/finance/system/security/UserPrincipal.java b/src/main/java/com/finance/system/security/UserPrincipal.java new file mode 100644 index 0000000..a3be5bc --- /dev/null +++ b/src/main/java/com/finance/system/security/UserPrincipal.java @@ -0,0 +1,61 @@ +package com.finance.system.security; + +import lombok.AllArgsConstructor; +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 +@NoArgsConstructor +@AllArgsConstructor +public class UserPrincipal implements UserDetails { + + private Long id; + private String employeeNo; + private String realName; + private String userType; + private String feishuOpenId; + + @Override + public Collection getAuthorities() { + return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + RoleService.normalize(userType))); + } + + @Override + public String getPassword() { + return null; + } + + @Override + public String getUsername() { + return employeeNo; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/src/main/java/com/finance/system/service/DashboardService.java b/src/main/java/com/finance/system/service/DashboardService.java new file mode 100644 index 0000000..8a270e1 --- /dev/null +++ b/src/main/java/com/finance/system/service/DashboardService.java @@ -0,0 +1,13 @@ +package com.finance.system.service; + +import com.finance.system.dto.DashboardStats; +import com.finance.system.dto.ReimApplicationSummary; + +import java.util.List; + +public interface DashboardService { + + DashboardStats getDashboardStats(Long userId); + + List getRecentApplications(Long userId, int limit); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/service/FeishuDirectoryLock.java b/src/main/java/com/finance/system/service/FeishuDirectoryLock.java new file mode 100644 index 0000000..85c1fa7 --- /dev/null +++ b/src/main/java/com/finance/system/service/FeishuDirectoryLock.java @@ -0,0 +1,15 @@ +package com.finance.system.service; + +import org.springframework.jdbc.core.JdbcTemplate; +import java.util.Map; + +/** Shared database mutex. Call inside a short transaction, BEFORE config/user reads. + * Lock order: directory singleton -> integration config/user rows. Never hold across HTTP. + * No service dependencies: config writes cannot introduce an OAuth/directory bean cycle. + */ +public final class FeishuDirectoryLock { + private FeishuDirectoryLock() { } + public static Map acquire(JdbcTemplate jdbc) { + return jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1 FOR UPDATE"); + } +} diff --git a/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java b/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java new file mode 100644 index 0000000..4187458 --- /dev/null +++ b/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java @@ -0,0 +1,97 @@ +package com.finance.system.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; + +/** Encrypts persisted integration secrets without ever logging their values. */ +@Component +public class IntegrationConfigCrypto { + public static final String PREFIX = "ENC[v1]:"; + private static final String CIPHER = "AES/GCM/NoPadding"; + private static final int NONCE_BYTES = 12; + private static final int TAG_BITS = 128; + + private final String encryptionKey; + private final SecureRandom secureRandom = new SecureRandom(); + + @Autowired + public IntegrationConfigCrypto( + @Value("${app.integration-encryption-key:${APP_INTEGRATION_ENCRYPTION_KEY:}}") String encryptionKey) { + this.encryptionKey = encryptionKey; + } + + public String encrypt(String plaintext) { + assertConfigured(); + if (plaintext == null) return null; + byte[] nonce = new byte[NONCE_BYTES]; + secureRandom.nextBytes(nonce); + try { + Cipher cipher = Cipher.getInstance(CIPHER); + cipher.init(Cipher.ENCRYPT_MODE, key(), new GCMParameterSpec(TAG_BITS, nonce)); + byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); + return PREFIX + Base64.getEncoder().encodeToString( + ByteBuffer.allocate(nonce.length + encrypted.length).put(nonce).put(encrypted).array()); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("集成配置加密失败", e); + } + } + + /** + * Reads both the current encrypted representation and legacy plaintext + * values. Legacy values are intentionally returned as-is for compatibility; + * callers must not persist them again without going through encrypt(). + */ + public String decrypt(String storedValue) { + if (!isEncrypted(storedValue)) return storedValue; + assertConfigured(); + try { + byte[] payload = Base64.getDecoder().decode(storedValue.substring(PREFIX.length())); + if (payload.length <= NONCE_BYTES) throw new IllegalArgumentException(); + byte[] nonce = new byte[NONCE_BYTES]; + byte[] encrypted = new byte[payload.length - NONCE_BYTES]; + System.arraycopy(payload, 0, nonce, 0, NONCE_BYTES); + System.arraycopy(payload, NONCE_BYTES, encrypted, 0, encrypted.length); + Cipher cipher = Cipher.getInstance(CIPHER); + cipher.init(Cipher.DECRYPT_MODE, key(), new GCMParameterSpec(TAG_BITS, nonce)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (Exception e) { + throw new IllegalStateException("集成配置密文无效", e); + } + } + + public static boolean isEncrypted(String value) { + return value != null && value.startsWith(PREFIX); + } + + public void assertConfigured() { + requireKey(); + } + + private SecretKeySpec key() { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(encryptionKey.getBytes(StandardCharsets.UTF_8)); + return new SecretKeySpec(digest, "AES"); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("集成配置加密密钥初始化失败", e); + } + } + + private void requireKey() { + if (!StringUtils.hasText(encryptionKey)) { + throw new IllegalStateException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能读写加密集成配置"); + } + } +} diff --git a/src/main/java/com/finance/system/service/IntegrationConfigReader.java b/src/main/java/com/finance/system/service/IntegrationConfigReader.java new file mode 100644 index 0000000..04df6b1 --- /dev/null +++ b/src/main/java/com/finance/system/service/IntegrationConfigReader.java @@ -0,0 +1,117 @@ +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.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +/** Read-through DB configuration with environment-property fallback. */ +@Component +public class IntegrationConfigReader { + /** Internal persistence key; it is never part of the public allow-list. */ + public static final String INTERNAL_ENABLED_KEY = "__enabled"; + private final SysIntegrationConfigRepository repository; + private final FeishuConfig feishuConfig; + private final KingdeeConfig kingdeeConfig; + private IntegrationConfigCrypto integrationConfigCrypto; + @Autowired private org.springframework.jdbc.core.JdbcTemplate jdbc; + + /** One database statement, bypassing the JPA first-level cache. Call under the + * directory mutex when using the result for a publication/login write. + * The result is internal credential material: never log or serialize it. + */ + public java.util.Map freshFeishu() { + List rows = jdbc.query("SELECT config_key,config_value,secret,enabled FROM sys_integration_config WHERE provider='FEISHU'", (rs, n) -> { + SysIntegrationConfig row = new SysIntegrationConfig(); row.setConfigKey(rs.getString("config_key")); + row.setConfigValue(rs.getString("config_value")); row.setSecret(rs.getBoolean("secret")); row.setEnabled(rs.getBoolean("enabled")); return row; + }); + java.util.Map result = new java.util.HashMap<>(); + result.put("appId", feishuConfig.getAppId()); result.put("appSecret", feishuConfig.getAppSecret()); + boolean anyEnabled = false; + for (SysIntegrationConfig row : rows) { + anyEnabled |= Boolean.TRUE.equals(row.getEnabled()); + if (StringUtils.hasText(row.getConfigValue())) result.put(row.getConfigKey(), storedValue(row)); + } + if (!result.containsKey(INTERNAL_ENABLED_KEY)) result.put(INTERNAL_ENABLED_KEY, + String.valueOf(rows.isEmpty() ? StringUtils.hasText(result.get("appId")) && StringUtils.hasText(result.get("appSecret")) : anyEnabled)); + return result; + } + + public IntegrationConfigReader(SysIntegrationConfigRepository repository, + FeishuConfig feishuConfig, KingdeeConfig kingdeeConfig) { + this.repository = repository; + this.feishuConfig = feishuConfig; + this.kingdeeConfig = kingdeeConfig; + } + + @Autowired(required = false) + public void setIntegrationConfigCrypto(IntegrationConfigCrypto integrationConfigCrypto) { + this.integrationConfigCrypto = integrationConfigCrypto; + } + + public String get(String provider, String key) { + String normalized = normalize(provider); + Optional stored = repository.findByProviderAndConfigKey(normalized, key); + if (stored.isPresent() && StringUtils.hasText(stored.get().getConfigValue())) { + return storedValue(stored.get()); + } + return environmentValue(normalized, key); + } + + public boolean getBoolean(String provider, String key, boolean defaultValue) { + String value = get(provider, key); + return StringUtils.hasText(value) ? Boolean.parseBoolean(value.trim()) : defaultValue; + } + + /** A persisted enable flag is authoritative, including persisted false. */ + public boolean isEnabled(String provider) { + String normalized = normalize(provider); + List stored = repository.findByProviderOrderByConfigKeyAsc(normalized); + Optional explicitEnabled = repository.findByProviderAndConfigKey(normalized, INTERNAL_ENABLED_KEY); + if (explicitEnabled.isPresent() && StringUtils.hasText(explicitEnabled.get().getConfigValue())) { + return Boolean.parseBoolean(explicitEnabled.get().getConfigValue().trim()); + } + if (stored != null && !stored.isEmpty()) return stored.stream().anyMatch(x -> Boolean.TRUE.equals(x.getEnabled())); + if ("KINGDEE".equals(normalized)) return kingdeeConfig.isEnabled(); + return StringUtils.hasText(get("FEISHU", "appId")) && StringUtils.hasText(get("FEISHU", "appSecret")); + } + + private String environmentValue(String provider, String key) { + if ("FEISHU".equals(provider)) { + if ("appId".equals(key)) return feishuConfig.getAppId(); + if ("appSecret".equals(key)) return feishuConfig.getAppSecret(); + if ("redirectUri".equals(key)) return feishuConfig.getRedirectUri(); + FeishuConfig.Approval approval = feishuConfig.getApproval(); + if (approval == null) return null; + if ("approvalCode".equals(key)) return approval.getApprovalCode(); + if ("verificationToken".equals(key)) return approval.getVerificationToken(); + if ("encryptKey".equals(key)) return approval.getEncryptKey(); + } else if ("KINGDEE".equals(provider)) { + if ("enabled".equals(key)) return String.valueOf(kingdeeConfig.isEnabled()); + if ("baseUrl".equals(key)) return kingdeeConfig.getBaseUrl(); + if ("clientId".equals(key)) return kingdeeConfig.getClientId(); + if ("clientSecret".equals(key)) return kingdeeConfig.getClientSecret(); + if ("dbId".equals(key)) return kingdeeConfig.getDbId(); + } + return null; + } + + private String storedValue(SysIntegrationConfig config) { + if (!Boolean.TRUE.equals(config.getSecret())) return config.getConfigValue(); + if (integrationConfigCrypto == null && IntegrationConfigCrypto.isEncrypted(config.getConfigValue())) { + throw new IllegalStateException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能读取加密集成配置"); + } + // Non-ENC values are legacy data and remain readable for compatibility. + return integrationConfigCrypto == null ? config.getConfigValue() + : integrationConfigCrypto.decrypt(config.getConfigValue()); + } + + private String normalize(String provider) { return provider == null ? "" : provider.trim().toUpperCase(Locale.ROOT); } +} diff --git a/src/main/java/com/finance/system/service/IntegrationConfigService.java b/src/main/java/com/finance/system/service/IntegrationConfigService.java new file mode 100644 index 0000000..ec93488 --- /dev/null +++ b/src/main/java/com/finance/system/service/IntegrationConfigService.java @@ -0,0 +1,290 @@ +package com.finance.system.service; + +import com.finance.system.adapter.feishu.FeishuAuthService; +import com.finance.system.adapter.kingdee.KingdeeClient; +import com.finance.system.entity.SysIntegrationConfig; +import com.finance.system.exception.BadRequestException; +import com.finance.system.repository.SysIntegrationConfigRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +/** + * Allow-listed integration settings. Secrets are write-only from the API. + * Runtime property based clients remain the safe default when DB settings are absent; + * this service never logs a setting value. + */ +@Service +public class IntegrationConfigService { + private static final String DEFAULT_KINGDEE_HOST = "app.kingdee.com"; + private static final Map> FIELDS = new LinkedHashMap<>(); + static { + FIELDS.put("FEISHU", Arrays.asList( + new Field("appId", "App ID", false), new Field("appSecret", "App Secret", true), + new Field("redirectUri", "Redirect URI", false), new Field("approvalCode", "审批定义编码", false), + new Field("verificationToken", "Verification Token", true), new Field("encryptKey", "Encrypt Key", true), + new Field("syncOrgEnabled", "同步组织架构", false), new Field("syncApprovalEnabled", "同步审批", false))); + FIELDS.put("KINGDEE", Arrays.asList( + new Field("enabled", "启用金蝶", false), new Field("baseUrl", "Base URL", false), + new Field("clientId", "Client ID", true), new Field("clientSecret", "Client Secret", true), + new Field("dbId", "账套 ID", false), new Field("syncEnabled", "启用同步", false), + new Field("syncIntervalMinutes", "同步间隔(分钟)", false))); + } + + private final SysIntegrationConfigRepository repository; + private FeishuAuthService feishuAuthService; + private KingdeeClient kingdeeClient; + private IntegrationConfigReader integrationConfigReader; + private IntegrationConfigCrypto integrationConfigCrypto; + @Autowired private org.springframework.jdbc.core.JdbcTemplate jdbc; + @javax.persistence.PersistenceContext private javax.persistence.EntityManager entityManager; + @Value("${kingdee.allowed-hosts:app.kingdee.com}") + private String kingdeeAllowedHosts; + + public IntegrationConfigService(SysIntegrationConfigRepository repository) { this.repository = repository; } + @Autowired(required = false) public void setFeishuAuthService(FeishuAuthService value) { this.feishuAuthService = value; } + @Autowired(required = false) public void setKingdeeClient(KingdeeClient value) { this.kingdeeClient = value; } + @Autowired(required = false) public void setIntegrationConfigReader(IntegrationConfigReader value) { this.integrationConfigReader = value; } + @Autowired(required = false) public void setIntegrationConfigCrypto(IntegrationConfigCrypto value) { this.integrationConfigCrypto = value; } + + @Transactional(readOnly = true) + public Map view() { + Map result = new LinkedHashMap<>(); + result.put("feishu", providerView("FEISHU")); result.put("kingdee", providerView("KINGDEE")); return result; + } + + @Transactional(propagation = org.springframework.transaction.annotation.Propagation.REQUIRES_NEW, + isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED, timeout = 30) + public void update(Map body) { + String provider = provider(body == null ? null : body.get("provider")); + // Publication uses this same singleton and holds it through commit. + if ("FEISHU".equals(provider)) FeishuDirectoryLock.acquire(jdbc); + Map values = body == null || !(body.get("values") instanceof Map) ? Collections.emptyMap() : (Map) body.get("values"); + Map allowList = new HashMap<>(); for (Field field : FIELDS.get(provider)) allowList.put(field.key, field); + Boolean enabled = booleanValue(body == null ? null : body.get("enabled"), false); + for (Object rawKey : values.keySet()) { + String key = String.valueOf(rawKey); + if (!allowList.containsKey(key)) throw new BadRequestException("不支持的集成配置项: " + key); + Field field = allowList.get(key); + if (field.secret && values.get(rawKey) != null + && StringUtils.hasText(String.valueOf(values.get(rawKey)))) { + if (integrationConfigCrypto == null) { + throw new BadRequestException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能保存敏感集成配置"); + } + integrationConfigCrypto.assertConfigured(); + } + } + Object baseUrl = values.get("baseUrl"); + if ("KINGDEE".equals(provider) && baseUrl != null && StringUtils.hasText(String.valueOf(baseUrl))) { + validateKingdeeBaseUrl(String.valueOf(baseUrl)); + } + // Persist the provider switch even when the user has not entered any + // provider fields. This explicit value must override environment + // configuration, including an explicit false. + SysIntegrationConfig switchConfig = repository + .findByProviderAndConfigKey(provider, IntegrationConfigReader.INTERNAL_ENABLED_KEY) + .orElseGet(SysIntegrationConfig::new); + refreshExisting(switchConfig); + switchConfig.setProvider(provider); + switchConfig.setConfigKey(IntegrationConfigReader.INTERNAL_ENABLED_KEY); + switchConfig.setConfigValue(String.valueOf(enabled)); + switchConfig.setSecret(false); + switchConfig.setEnabled(enabled); + repository.save(switchConfig); + for (Map.Entry entry : values.entrySet()) { + String key = String.valueOf(entry.getKey()); Field field = allowList.get(key); + String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue()); + Optional existing = repository.findByProviderAndConfigKey(provider, key); + existing.ifPresent(this::refreshExisting); + if (field.secret && !StringUtils.hasText(value) && existing.isPresent()) continue; + if (field.secret && StringUtils.hasText(value)) { + value = integrationConfigCrypto.encrypt(value); + } + SysIntegrationConfig config = existing.orElseGet(SysIntegrationConfig::new); + config.setProvider(provider); config.setConfigKey(key); config.setConfigValue(value); + config.setSecret(field.secret); config.setEnabled(enabled); repository.save(config); + } + // Keep the enable switch consistent for all existing keys without creating + // an unlisted sentinel key (which would make configuration injection possible). + repository.flush(); + for (SysIntegrationConfig config : repository.findByProviderOrderByConfigKeyAsc(provider)) { + refreshExisting(config); + // A legacy plaintext secret may be read, but it must never be + // written back as part of an unrelated provider update. When the + // key is available, transparently migrate it to ENC[v1]. + if (Boolean.TRUE.equals(config.getSecret()) + && StringUtils.hasText(config.getConfigValue()) + && !IntegrationConfigCrypto.isEncrypted(config.getConfigValue())) { + if (integrationConfigCrypto == null) continue; + integrationConfigCrypto.assertConfigured(); + config.setConfigValue(integrationConfigCrypto.encrypt(config.getConfigValue())); + } + config.setEnabled(enabled); repository.save(config); + } + } + + private void refreshExisting(SysIntegrationConfig config) { + if (config.getId() != null) entityManager.refresh(config); + } + + @Transactional(readOnly = true) + public Map test(String requestedProvider) { + String provider = provider(requestedProvider); + Map current = providerView(provider); + boolean configured = Boolean.TRUE.equals(current.get("enabled")) && hasRequiredConfiguration(provider); + Map result = new LinkedHashMap<>(); result.put("provider", provider); result.put("configured", configured); + if (!configured) { result.put("success", false); result.put("message", "集成未配置或未启用,未执行外部连接"); return result; } + try { + if ("FEISHU".equals(provider) && feishuAuthService != null) { + feishuAuthService.getTenantAccessToken(); result.put("success", true); result.put("message", "连接测试成功"); return result; + } + if ("KINGDEE".equals(provider) && kingdeeClient != null && kingdeeClient.isEnabled()) { + kingdeeClient.login(); result.put("success", true); result.put("message", "连接测试成功"); return result; + } + } catch (Exception ignored) { + // Deliberately do not include an exception containing request/config values. + result.put("success", false); result.put("message", "外部连接测试失败"); return result; + } + result.put("success", false); result.put("message", "连接测试客户端未配置"); return result; + } + + private Map providerView(String provider) { + Map values = new HashMap<>(); + for (SysIntegrationConfig config : repository.findByProviderOrderByConfigKeyAsc(provider)) values.put(config.getConfigKey(), config); + boolean enabled = integrationConfigReader == null + ? values.values().stream().anyMatch(x -> Boolean.TRUE.equals(x.getEnabled())) + : integrationConfigReader.isEnabled(provider); + List> fields = new ArrayList<>(); + for (Field field : FIELDS.get(provider)) { + SysIntegrationConfig config = values.get(field.key); + String rawValue = config == null && integrationConfigReader != null + ? integrationConfigReader.get(provider, field.key) + : config == null ? null : storedValue(config); + boolean configured = StringUtils.hasText(rawValue); + Map item = new LinkedHashMap<>(); item.put("key", field.key); item.put("label", field.label); + item.put("value", field.secret ? (configured ? RoleService.mask(rawValue) : "") : (rawValue == null ? "" : rawValue)); + item.put("secret", field.secret); item.put("configured", configured); fields.add(item); + } + Map result = new LinkedHashMap<>(); result.put("enabled", enabled); result.put("fields", fields); return result; + } + + private boolean hasRequiredConfiguration(String provider) { + if (integrationConfigReader != null) { + if ("FEISHU".equals(provider)) return present(integrationConfigReader.get(provider, "appId")) && present(integrationConfigReader.get(provider, "appSecret")); + return safeKingdeeUrl(integrationConfigReader.get(provider, "baseUrl")) && present(integrationConfigReader.get(provider, "clientId")) + && present(integrationConfigReader.get(provider, "clientSecret")) && present(integrationConfigReader.get(provider, "dbId")); + } + Map values = new HashMap<>(); + for (SysIntegrationConfig x : repository.findByProviderOrderByConfigKeyAsc(provider)) values.put(x.getConfigKey(), x); + if ("FEISHU".equals(provider)) return present(values, "appId") && present(values, "appSecret"); + return present(values, "baseUrl") && safeKingdeeUrl(values.get("baseUrl").getConfigValue()) + && present(values, "clientId") && present(values, "clientSecret") && present(values, "dbId"); + } + private boolean present(Map values, String key) { + return values.containsKey(key) && StringUtils.hasText(storedValue(values.get(key))); + } + private boolean present(String value) { return StringUtils.hasText(value); } + private String storedValue(SysIntegrationConfig config) { + if (config == null) return null; + if (!Boolean.TRUE.equals(config.getSecret())) return config.getConfigValue(); + if (integrationConfigCrypto == null && IntegrationConfigCrypto.isEncrypted(config.getConfigValue())) { + throw new IllegalStateException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能读取加密集成配置"); + } + return integrationConfigCrypto == null ? config.getConfigValue() + : integrationConfigCrypto.decrypt(config.getConfigValue()); + } + private String provider(Object value) { String result = value == null ? "" : String.valueOf(value).trim().toUpperCase(Locale.ROOT); if (!FIELDS.containsKey(result)) throw new BadRequestException("provider 必须是 FEISHU 或 KINGDEE"); return result; } + private Boolean booleanValue(Object value, boolean defaultValue) { if (value == null) return defaultValue; if (value instanceof Boolean) return (Boolean) value; if ("true".equalsIgnoreCase(String.valueOf(value)) || "false".equalsIgnoreCase(String.valueOf(value))) return Boolean.valueOf(String.valueOf(value)); throw new BadRequestException("enabled 必须是布尔值"); } + + /** + * Validates the outbound Kingdee endpoint before it can be persisted or + * considered configured. Exact hosts (or an explicitly configured + * *.suffix entry) are required, and every resolved address must be public. + */ + public void validateKingdeeBaseUrl(String rawUrl) { + if (!StringUtils.hasText(rawUrl)) throw new BadRequestException("金蝶 baseUrl 不能为空"); + final URI uri; + try { + uri = new URI(rawUrl.trim()); + } catch (URISyntaxException e) { + throw new BadRequestException("金蝶 baseUrl 格式不正确"); + } + if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null + || uri.getUserInfo() != null || uri.getQuery() != null || uri.getFragment() != null) { + throw new BadRequestException("金蝶 baseUrl 必须是允许主机上的 HTTPS 地址"); + } + String host = uri.getHost().toLowerCase(Locale.ROOT); + while (host.endsWith(".")) host = host.substring(0, host.length() - 1); + if (isBlockedHost(host) || !isAllowedKingdeeHost(host)) { + throw new BadRequestException("金蝶 baseUrl 主机不在允许列表中"); + } + try { + for (InetAddress address : InetAddress.getAllByName(host)) { + if (isBlockedAddress(address)) throw new BadRequestException("金蝶 baseUrl 不得指向内网或本机地址"); + } + } catch (BadRequestException e) { + throw e; + } catch (Exception e) { + // DNS may be unavailable during an offline configuration + // change. The explicit host allowlist remains authoritative; + // literal/private addresses were already rejected above. + } + } + + /** Validation sink used immediately before every outbound Kingdee URL is built. */ + public String validateAndNormalizeKingdeeBaseUrl(String rawUrl) { + validateKingdeeBaseUrl(rawUrl); + String normalized = rawUrl.trim(); + return normalized.endsWith("/") ? normalized : normalized + "/"; + } + + public void setKingdeeAllowedHosts(String hosts) { this.kingdeeAllowedHosts = hosts; } + + private boolean safeKingdeeUrl(String value) { + try { validateKingdeeBaseUrl(value); return true; } + catch (RuntimeException ignored) { return false; } + } + + private boolean isAllowedKingdeeHost(String host) { + String configured = StringUtils.hasText(kingdeeAllowedHosts) ? kingdeeAllowedHosts : DEFAULT_KINGDEE_HOST; + for (String raw : configured.split(",")) { + String allowed = raw.trim().toLowerCase(Locale.ROOT); + if (allowed.isEmpty()) continue; + if (allowed.startsWith("*.") && host.endsWith(allowed.substring(1)) + && host.length() > allowed.length() - 1) return true; + if (host.equals(allowed)) return true; + } + return false; + } + + private boolean isBlockedHost(String host) { + return "localhost".equals(host) || host.endsWith(".localhost") + || "metadata".equals(host) || host.endsWith(".metadata.google.internal") + || "metadata.google.internal".equals(host) || "instance-data".equals(host) + || host.endsWith(".internal") || host.endsWith(".local"); + } + + private boolean isBlockedAddress(InetAddress address) { + return address.isAnyLocalAddress() || address.isLoopbackAddress() + || address.isLinkLocalAddress() || address.isSiteLocalAddress() + || address.isMulticastAddress() || isMetadataAddress(address); + } + + private boolean isMetadataAddress(InetAddress address) { + byte[] b = address.getAddress(); + return b.length == 4 && (b[0] & 0xff) == 169 && (b[1] & 0xff) == 254 + && (b[2] & 0xff) == 169 && (b[3] & 0xff) == 254; + } + + private static final class Field { + private final String key; private final String label; private final boolean secret; + private Field(String key, String label, boolean secret) { this.key = key; this.label = label; this.secret = secret; } + } +} diff --git a/src/main/java/com/finance/system/service/PaymentIdempotencyLock.java b/src/main/java/com/finance/system/service/PaymentIdempotencyLock.java new file mode 100644 index 0000000..688fa94 --- /dev/null +++ b/src/main/java/com/finance/system/service/PaymentIdempotencyLock.java @@ -0,0 +1,9 @@ +package com.finance.system.service; + +/** + * Serializes payment requests sharing an idempotency key for the duration of + * the current database transaction. + */ +public interface PaymentIdempotencyLock { + void lock(String normalizedIdempotencyKey); +} diff --git a/src/main/java/com/finance/system/service/ReimApplicationService.java b/src/main/java/com/finance/system/service/ReimApplicationService.java new file mode 100644 index 0000000..03bb78d --- /dev/null +++ b/src/main/java/com/finance/system/service/ReimApplicationService.java @@ -0,0 +1,51 @@ +package com.finance.system.service; + +import com.finance.system.dto.*; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface ReimApplicationService { + + WorkbenchDto getWorkbench(Long userId); + + Page getMyApplications(Long userId, String status, Pageable pageable); + + ReimApplicationDetail getApplicationDetail(Long id, Long userId); + + default ReimApplicationDetail getApplicationDetail(Long id) { + return getApplicationDetail(id, com.finance.system.util.AuditUtil.getCurrentUserId()); + } + + ReimApplicationDetail getByApplicationNo(String applicationNo, Long userId); + + default ReimApplicationDetail getByApplicationNo(String applicationNo) { + return getByApplicationNo(applicationNo, com.finance.system.util.AuditUtil.getCurrentUserId()); + } + + ReimApplicationDetail createApplication(CreateApplicationRequest request, Long userId); + + ReimApplicationDetail updateApplication(Long id, CreateApplicationRequest request, Long userId); + + /** Compatibility overload; web entry points must use the actor-aware method. */ + default ReimApplicationDetail updateApplication(Long id, CreateApplicationRequest request) { + return updateApplication(id, request, com.finance.system.util.AuditUtil.getCurrentUserId()); + } + + ReimApplicationDetail submitApplication(Long id, Long userId); + + default ReimApplicationDetail submitApplication(Long id) { + return submitApplication(id, com.finance.system.util.AuditUtil.getCurrentUserId()); + } + + ReimApplicationDetail receiveApplication(Long id, Long operatorId); + + void deleteApplication(Long id, Long userId); + + default void deleteApplication(Long id) { + deleteApplication(id, com.finance.system.util.AuditUtil.getCurrentUserId()); + } + + Page getAccountsPayableTasks(String status, Pageable pageable); + + Page getCashierTasks(String status, Pageable pageable); +} diff --git a/src/main/java/com/finance/system/service/ReimApprovalService.java b/src/main/java/com/finance/system/service/ReimApprovalService.java new file mode 100644 index 0000000..bbd4636 --- /dev/null +++ b/src/main/java/com/finance/system/service/ReimApprovalService.java @@ -0,0 +1,20 @@ +package com.finance.system.service; + +import com.finance.system.dto.ApprovalRecordDto; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +public interface ReimApprovalService { + + ApprovalRecordDto approve(Long applicationId, Long approverId, String comment); + + ApprovalRecordDto reject(Long applicationId, Long approverId, String comment, String returnReason); + + ApprovalRecordDto transfer(Long applicationId, Long fromUserId, Long toUserId, String comment); + + List getApprovalHistory(Long applicationId); + + List getApprovalHistoryByUser(Long userId); +} \ No newline at end of file diff --git a/src/main/java/com/finance/system/service/ReimPaymentService.java b/src/main/java/com/finance/system/service/ReimPaymentService.java new file mode 100644 index 0000000..ff550d1 --- /dev/null +++ b/src/main/java/com/finance/system/service/ReimPaymentService.java @@ -0,0 +1,33 @@ +package com.finance.system.service; + +import com.finance.system.dto.*; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.math.BigDecimal; +import java.util.List; + +public interface ReimPaymentService { + + Page getPendingPayments(Long operatorId, Pageable pageable); + + PaymentDetailDto getPaymentDetail(Long applicationId, Long operatorId); + + default PaymentDetailDto getPaymentDetail(Long applicationId) { + return getPaymentDetail(applicationId, com.finance.system.util.AuditUtil.getCurrentUserId()); + } + + PaymentResultDto executePayment(Long applicationId, BigDecimal amount, Long operatorId, + String paymentMethod, String referenceNo, String remark, String idempotencyKey); + + PaymentResultDto processPartialPayment(Long applicationId, BigDecimal amount, Long operatorId, + String paymentMethod, String referenceNo, String remark, String idempotencyKey); + + List getPaymentHistoryByOperator(Long operatorId); + + PaymentRecordDto getPaymentByNo(String paymentNo, Long operatorId); + + default PaymentRecordDto getPaymentByNo(String paymentNo) { + return getPaymentByNo(paymentNo, com.finance.system.util.AuditUtil.getCurrentUserId()); + } +} diff --git a/src/main/java/com/finance/system/service/RoleService.java b/src/main/java/com/finance/system/service/RoleService.java new file mode 100644 index 0000000..2c8ce39 --- /dev/null +++ b/src/main/java/com/finance/system/service/RoleService.java @@ -0,0 +1,638 @@ +package com.finance.system.service; + +import com.finance.system.entity.*; +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.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import com.finance.system.util.AuditUtil; + +import java.util.*; +import java.util.stream.Collectors; + +/** Application service for database-backed roles, permissions and groups. */ +@Service +public class RoleService { + public static final String EMPLOYEE = "EMPLOYEE"; + public static final String ADMIN = "ADMIN"; + public static final String SUPER_ADMIN = "SUPER_ADMIN"; + 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 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 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; + private final SysUserGroupRoleRepository groupRoles; + private SysDepartmentRepository departments; + @Autowired + private com.finance.system.adapter.feishu.FeishuDirectoryAccessService directoryAccess; + @Autowired + private JdbcTemplate jdbc; + + public RoleService(SysRoleRepository roles, SysPermissionRepository permissions, + SysRolePermissionRepository rolePermissions, SysUserRoleRepository userRoles, + 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; + this.groupRoles = groupRoles; + } + + @Autowired(required = false) + public void setDepartments(SysDepartmentRepository departments) { this.departments = departments; } + + @Transactional(readOnly = true) + public List> listRoles() { + List> result = new ArrayList<>(); + for (SysRole role : roles.findAll()) { + Map item = roleMap(role); + item.put("memberCount", userRoles.countByIdRoleId(role.getId())); + item.put("permissionCount", rolePermissions.countByIdRoleId(role.getId())); + result.add(item); + } + return result; + } + + @Transactional + public SysRole saveRole(Long id, Map body) { + 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("角色不存在")); + if (id != null && !code.equals(role.getRoleCode()) && roles.existsByRoleCode(code)) { + throw new BusinessException("角色编码已存在", 409); + } + if (id != null && Boolean.TRUE.equals(role.getBuiltIn()) && !code.equals(role.getRoleCode())) { + throw new BusinessException("内置角色编码不可修改", 400); + } + role.setRoleCode(code); + role.setRoleName(name); + role.setDescription(text(body.get("description"))); + role.setStatus(status(body.get("status"))); + if (role.getBuiltIn() == null) role.setBuiltIn(false); + return roles.save(role); + } + + @Transactional + public void deleteRole(Long id) { + SysRole role = roles.findById(id).orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + if (Boolean.TRUE.equals(role.getBuiltIn())) throw new BusinessException("内置角色不可删除", 400); + if ((ADMIN.equals(role.getRoleCode()) || SUPER_ADMIN.equals(role.getRoleCode())) + && countAdministratorAssignments(role.getId()) <= 1) { + throw new BusinessException("不能删除最后一个管理员角色", 400); + } + rolePermissions.deleteByIdRoleId(id); + userRoles.deleteByIdRoleId(id); + groupRoles.deleteByIdRoleId(id); + roles.delete(role); + } + + @Transactional(readOnly = true) + public List> permissionCatalog() { + List> result = new ArrayList<>(); + for (SysPermission permission : permissions.findAll()) { + Map item = new LinkedHashMap<>(); + item.put("code", permission.getPermissionCode()); + item.put("name", permission.getPermissionName()); + item.put("type", permission.getPermissionType()); + item.put("parentCode", permission.getParentCode()); + item.put("resource", permission.getResource()); + result.add(item); + } + return result; + } + + @Transactional(readOnly = true) + public Map rolePermissions(Long roleId) { + requireRole(roleId); + Map field = new LinkedHashMap<>(); + List codes = new ArrayList<>(); + Map catalog = permissionMap(rolePermissions.findByIdRoleId(roleId)); + for (SysRolePermission assignment : safe(rolePermissions.findByIdRoleId(roleId))) { + SysPermission permission = catalog.get(assignment.getId().getPermissionId()); + if (permission == null) continue; + if ("FIELD".equals(permission.getPermissionType())) { + field.put(permission.getPermissionCode(), assignment.getAccessLevel()); + } else if (!"HIDDEN".equals(assignment.getAccessLevel())) { + codes.add(permission.getPermissionCode()); + } + } + Map result = new LinkedHashMap<>(); + result.put("permissionCodes", codes); + result.put("fieldPermissions", field); + return result; + } + + @Transactional + public void replaceRolePermissions(Long roleId, Map body) { + replaceRolePermissions(roleId, body, AuditUtil.getCurrentUserId()); + } + + @Transactional + public void replaceRolePermissions(Long roleId, Map body, Long actorId) { + SysRole targetRole = requireRole(roleId); + boolean superAdmin = isSuperAdmin(actorId); + if (!superAdmin && !hasPermission(actorId, "system:role:manage")) { + 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)) { + 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")); + } + if (!replacements.isEmpty()) rolePermissions.saveAll(replacements); + } + + @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, + 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))) { + if (member.getId() != null) groupIds.add(member.getId().getGroupId()); + } + for (SysUserGroup group : groups.findAllById(groupIds)) { + if (!"INACTIVE".equalsIgnoreCase(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()); + } + + LinkedHashSet roleCodes = effectiveRoles.stream().map(SysRole::getRoleCode) + .collect(Collectors.toCollection(LinkedHashSet::new)); + LinkedHashSet permissionCodes = new LinkedHashSet<>(); + Map permissionAccess = new LinkedHashMap<>(); + Map fieldPermissions = new LinkedHashMap<>(); + 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; + if ("FIELD".equals(permission.getPermissionType())) { + fieldPermissions.put(permission.getPermissionCode(), stronger(fieldPermissions.get(permission.getPermissionCode()), assignment.getAccessLevel())); + } else { + permissionCodes.add(permission.getPermissionCode()); + permissionAccess.put(permission.getPermissionCode(), stronger(permissionAccess.get(permission.getPermissionCode()), assignment.getAccessLevel())); + } + } + } 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"); } + } + 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"); + } + } + return new ResolvedPermissions(roleCodes, permissionCodes, fieldPermissions, permissionAccess, configured); + } + + @Transactional(readOnly = true) + public Map currentPermissionsMap(Long userId) { + ResolvedPermissions current = currentPermissions(userId); + Map result = new LinkedHashMap<>(); + result.put("roleCodes", new ArrayList<>(current.getRoleCodes())); + result.put("permissionCodes", new ArrayList<>(current.getPermissionCodes())); + result.put("fieldPermissions", current.getFieldPermissions()); + return result; + } + + 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; + String fieldAccess = current.getFieldPermissions().get(code); + return current.getPermissionCodes().contains(code) || (fieldAccess != null && !"HIDDEN".equals(fieldAccess)); + } + + /** + * Returns the effective access level of a field permission. A missing + * assignment is deliberately treated as HIDDEN; callers must not infer + * write access from a menu/button permission. + */ + @Transactional(readOnly = true) + 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"; + String access = resolved.getFieldPermissions().get(code); + return access == null ? "HIDDEN" : access; + } + + @Transactional(readOnly = true) + public boolean canEditField(Long userId, String code) { + return "EDIT".equals(fieldAccess(userId, code)); + } + + /** Only a real, currently effective SUPER_ADMIN may delegate privileged roles. */ + @Transactional(readOnly = true) + public boolean isSuperAdmin(Long userId) { + 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); + } + + @Transactional + public void replaceUserRoles(Long userId, Collection roleIds) { + replaceUserRoles(userId, roleIds, AuditUtil.getCurrentUserId()); + } + + @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); + } + + /** Actor-first form for service callers that pass the security subject first. */ + @Transactional + public void replaceUserRoles(Long actorId, Long userId, Collection roleIds) { + replaceUserRoles(userId, roleIds, actorId); + } + + /** Compatibility endpoint: userType is kept, and the corresponding built-in role is assigned. */ + @Transactional + public void syncLegacyRole(Long userId, String roleCode) { + syncLegacyRole(userId, roleCode, AuditUtil.getCurrentUserId()); + } + + @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); + } + + @Transactional + public void syncLegacyRole(Long actorId, Long userId, String roleCode) { + syncLegacyRole(userId, roleCode, actorId); + } + + @Transactional(readOnly = true) + public List userRoleCodes(Long userId) { return new ArrayList<>(currentPermissions(userId).getRoleCodes()); } + + @Transactional(readOnly = true) + public List userGroupNames(Long userId) { + List result = new ArrayList<>(); + for (SysUserGroupMember member : safe(members.findByIdUserId(userId))) { + if (member.getId() == null) continue; + groups.findById(member.getId().getGroupId()).filter(g -> !"INACTIVE".equalsIgnoreCase(g.getStatus())) + .ifPresent(g -> result.add(g.getGroupName())); + } + return result; + } + + @Transactional(readOnly = true) + public List> listGroups() { + List> result = new ArrayList<>(); + 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); + } + return result; + } + + @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("用户组不存在")); + if (id != null && !code.equals(group.getGroupCode()) && groups.existsByGroupCode(code)) { + throw new BusinessException("用户组编码已存在", 409); + } + group.setGroupCode(code); group.setGroupName(name); group.setDescription(text(body.get("description"))); + group.setStatus(status(body.get("status"))); + return groups.save(group); + } + + @Transactional + public void deleteGroup(Long id) { + requireGroup(id); members.deleteByIdGroupId(id); groupRoles.deleteByIdGroupId(id); groups.deleteById(id); + } + + @Transactional(readOnly = true) + public List groupRoleIds(Long id) { requireGroup(id); return 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()); } + + @Transactional + public void replaceGroupRoles(Long id, Collection roleIds) { + replaceGroupRoles(id, roleIds, AuditUtil.getCurrentUserId()); + } + + @Transactional + public void replaceGroupRoles(Long id, Collection roleIds, Long actorId) { + requireGroup(id); Set ids = longSet(roleIds); validateRoleIds(ids); + validateDelegatedRoles(actorId, ids); + ensurePrivilegedRoleDelegation(actorId, null, ids); + groupRoles.deleteByIdGroupId(id); for (Long roleId : ids) groupRoles.save(new SysUserGroupRole(id, roleId)); + } + + @Transactional + public void replaceGroupRoles(Long actorId, Long id, Collection roleIds) { + replaceGroupRoles(id, roleIds, actorId); + } + @Transactional + public void replaceGroupMembers(Long id, Collection userIds) { + replaceGroupMembers(id, userIds, AuditUtil.getCurrentUserId()); + } + + @Transactional + public void replaceGroupMembers(Long id, Collection userIds, Long actorId) { + requireGroup(id); + 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 = false; + for (Long roleId : assignedRoleIds) { + SysRole role = requireRole(roleId); + String code = normalize(role.getRoleCode()); + if (ADMIN.equals(code) || SUPER_ADMIN.equals(code)) { + privilegedGroup = true; + break; + } + } + if (privilegedGroup && !isSuperAdmin(actorId)) { + throw new BusinessException("只有超级管理员可以管理管理员用户组成员", 403); + } + Set ids = longSet(userIds); + Set existing = safe(members.findByIdGroupId(id)).stream().map(m -> m.getId().getUserId()).collect(Collectors.toSet()); + // 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))) { + FeishuDirectoryLock.acquire(jdbc); + } + for (Long userId : ids) { + SysUser user = requireUser(userId); + if (!existing.contains(userId)) directoryAccess.requireSynced(user); + } + members.deleteByIdGroupId(id); for (Long userId : ids) members.save(new SysUserGroupMember(id, userId)); + } + + @Transactional + public void replaceGroupMembers(Long actorId, Long id, Collection userIds) { + replaceGroupMembers(id, userIds, actorId); + } + + @Transactional(readOnly = true) + public List> candidates() { + List> result = 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()); + 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); + } + return result; + } + + 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); + } + + 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 void ensurePrivilegedRoleDelegation(Long actorId, Long targetUserId, Collection roleIds) { + boolean privileged = false; + for (Long roleId : roleIds) { + SysRole role = requireRole(roleId); + String code = normalize(role.getRoleCode()); + if (ADMIN.equals(code) || SUPER_ADMIN.equals(code)) { + privileged = true; + break; + } + } + if (!privileged) return; + if (!isSuperAdmin(actorId)) { + throw new BusinessException("只有超级管理员可以授予管理员角色", 403); + } + if (targetUserId != null && targetUserId.equals(actorId)) { + throw new BusinessException("不能把当前操作者提升为管理员", 403); + } + } + 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); + return accessRank(effective) >= accessRank(requestedAccess); + } + private void validateDelegatedRoles(Long actorId, Collection roleIds) { + if (isSuperAdmin(actorId)) return; + for (Long roleId : roleIds) { + SysRole role = requireRole(roleId); + List assignments = safe(rolePermissions.findByIdRoleId(roleId)); + if (assignments.isEmpty()) continue; + 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) { + throw new BusinessException("角色包含不存在的权限,不能分配", 403); + } + if (!ACCESS_LEVELS.contains(assignment.getAccessLevel())) { + throw new BusinessException("角色包含无效的访问级别,不能分配", 403); + } + if (EMPLOYEE.equals(normalize(role.getRoleCode())) + && SAFE_EMPLOYEE_PERMISSIONS.contains(permission.getPermissionCode())) { + continue; + } + String access = assignment.getAccessLevel(); + if (!canDelegatePermission(actorId, permission, access)) { + throw new BusinessException("不能分配超出操作者自身有效权限的角色", 403); + } + } + } + } + private boolean isSuperAdminOnlyPermission(String code) { + return SUPER_ADMIN_ONLY_PERMISSIONS.contains(code) + || (code.startsWith("system:") && code.endsWith(":manage")) + || code.startsWith("system:integration:"); + } + private String permissionAccess(Long userId, String code) { + ResolvedPermissions resolved = currentPermissions(userId); + if (resolved.getRoleCodes().contains(ADMIN) || resolved.getRoleCodes().contains(SUPER_ADMIN)) return "EDIT"; + String access = resolved.getPermissionAccess().get(code); + return access == null && resolved.getPermissionCodes().contains(code) ? "READ" : access; + } + private int accessRank(String access) { + if ("EDIT".equals(access)) return 2; + 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"; + } + 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 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 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 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 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 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; } + private List safe(List value) { return value == null ? Collections.emptyList() : value; } + + public static final class ResolvedPermissions { + private final Set roleCodes; private final Set permissionCodes; private final Map fieldPermissions; private final boolean configured; + private final Map permissionAccess; + public ResolvedPermissions(Set roles, Set permissions, Map fields, boolean configured) { + this(roles, permissions, fields, Collections.emptyMap(), configured); + } + public ResolvedPermissions(Set roles, Set permissions, Map fields, + Map permissionAccess, boolean configured) { + this.roleCodes = roles; this.permissionCodes = permissions; this.fieldPermissions = fields; + this.permissionAccess = permissionAccess; this.configured = configured; + } + public Set getRoleCodes() { return roleCodes; } public Set getPermissionCodes() { return permissionCodes; } public Map getFieldPermissions() { return fieldPermissions; } public boolean isConfigured() { return configured; } + public Map getPermissionAccess() { return permissionAccess; } + } +} diff --git a/src/main/java/com/finance/system/service/impl/ApprovalRoutingRules.java b/src/main/java/com/finance/system/service/impl/ApprovalRoutingRules.java new file mode 100644 index 0000000..a5075f1 --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ApprovalRoutingRules.java @@ -0,0 +1,61 @@ +package com.finance.system.service.impl; + +import com.finance.system.entity.SysApprovalNode; +import com.finance.system.entity.SysUser; + +import java.util.Locale; + +/** Shared, explicit routing rules for approval nodes and their assignees. */ +final class ApprovalRoutingRules { + + private ApprovalRoutingRules() { + } + + static boolean isApprovalNode(SysApprovalNode node) { + if (node == null || !isActive(node.getStatus())) { + return false; + } + String approverType = normalize(node.getApproverType()); + if ("FIXED".equals(approverType) + || "流程已完成".equals(node.getNodeName())) { + return false; + } + return isKnownRole(node.getApproverRole()); + } + + static boolean isKnownRole(String role) { + String normalized = normalize(role); + return "ACCOUNTS_PAYABLE".equals(normalized) + || "FINANCE_MANAGER".equals(normalized) + || "CASHIER".equals(normalized); + } + + static boolean matchesRole(SysUser user, String role) { + if (!isActive(user) || !isKnownRole(role) || user.getPosition() == null) { + return false; + } + String position = user.getPosition().trim().toUpperCase(Locale.ROOT); + switch (normalize(role)) { + case "ACCOUNTS_PAYABLE": + return position.contains("应付会计") || position.contains("AP"); + case "FINANCE_MANAGER": + return position.contains("经理") || position.contains("MANAGER"); + case "CASHIER": + return position.contains("出纳") || position.contains("CASHIER"); + default: + return false; + } + } + + static boolean isActive(SysUser user) { + return user != null && isActive(user.getStatus()); + } + + private static boolean isActive(String status) { + return "ACTIVE".equalsIgnoreCase(status); + } + + private static String normalize(String value) { + return value == null ? "" : value.trim().toUpperCase(Locale.ROOT); + } +} diff --git a/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java b/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java new file mode 100644 index 0000000..47ba21d --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java @@ -0,0 +1,152 @@ +package com.finance.system.service.impl; + +import com.finance.system.dto.DashboardStats; +import com.finance.system.dto.ReimApplicationSummary; +import com.finance.system.entity.ReimApplication; +import com.finance.system.entity.SysUser; +import com.finance.system.entity.SysDepartment; +import com.finance.system.entity.SysExpenseType; +import com.finance.system.enums.ApprovalStatus; +import com.finance.system.enums.PaymentStatus; +import com.finance.system.repository.ReimApplicationRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.repository.SysExpenseTypeRepository; +import com.finance.system.service.DashboardService; +import com.finance.system.service.RoleService; +import com.finance.system.exception.UnauthorizedException; +import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class DashboardServiceImpl implements DashboardService { + + private final ReimApplicationRepository reimApplicationRepository; + private final SysUserRepository sysUserRepository; + private final SysDepartmentRepository sysDepartmentRepository; + private final SysExpenseTypeRepository sysExpenseTypeRepository; + private RoleService roleService; + + @Autowired(required = false) + public void setRoleService(RoleService roleService) { this.roleService = roleService; } + + @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); + if (viewAll) { + // 财务人员查看所有申请 + applications = reimApplicationRepository.findAll(); + } else { + // 普通员工查看自己的申请 + applications = reimApplicationRepository.findByApplicantIdOrderByCreatedAtDesc(userId); + } + + long total = applications.size(); + long pendingApproval = applications.stream() + .filter(a -> ApprovalStatus.PENDING.name().equals(a.getApprovalStatus())) + .count(); + long approved = applications.stream() + .filter(a -> ApprovalStatus.APPROVED.name().equals(a.getApprovalStatus())) + .count(); + long rejected = applications.stream() + .filter(a -> ApprovalStatus.REJECTED.name().equals(a.getApprovalStatus())) + .count(); + long pendingPayment = applications.stream() + .filter(a -> PaymentStatus.UNPAID.name().equals(a.getPaymentStatus())) + .count(); + long unpaid = applications.stream() + .filter(a -> PaymentStatus.UNPAID.name().equals(a.getPaymentStatus()) + || PaymentStatus.PARTIAL.name().equals(a.getPaymentStatus())) + .count(); + + BigDecimal totalAmount = applications.stream() + .map(ReimApplication::getTotalAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal paidAmount = applications.stream() + .filter(a -> PaymentStatus.PAID.name().equals(a.getPaymentStatus())) + .map(ReimApplication::getTotalAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal pendingAmount = totalAmount.subtract(paidAmount); + + return DashboardStats.builder() + .totalApplications(total) + .pendingApproval(pendingApproval) + .approved(approved) + .rejected(rejected) + .pendingPayment(pendingPayment) + .unpaid(unpaid) + .totalAmount(totalAmount) + .paidAmount(paidAmount) + .pendingAmount(pendingAmount) + .build(); + } + + @Override + public List getRecentApplications(Long userId, int limit) { + if (userId == null) throw new UnauthorizedException("未登录"); + List applications; + if (canViewAll(userId, sysUserRepository.findById(userId).orElse(null))) { + int safeLimit = Math.max(1, Math.min(limit, 100)); + applications = reimApplicationRepository.findAll().stream() + .sorted((left, right) -> { + if (left.getCreatedAt() == null) return right.getCreatedAt() == null ? 0 : 1; + if (right.getCreatedAt() == null) return -1; + return right.getCreatedAt().compareTo(left.getCreatedAt()); + }) + .limit(safeLimit).collect(Collectors.toList()); + } else { + applications = reimApplicationRepository.findFirst10ByApplicantIdOrderByCreatedAtDesc(userId); + } + + return applications.stream().map(this::buildSummary).collect(Collectors.toList()); + } + + private boolean canViewAll(Long userId, SysUser user) { + if (roleService != null) { + return 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()); + } + + private ReimApplicationSummary buildSummary(ReimApplication app) { + SysUser applicant = app.getApplicantId() != null ? + sysUserRepository.findById(app.getApplicantId()).orElse(null) : null; + SysDepartment dept = app.getDepartmentId() != null ? + sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null; + SysExpenseType expenseType = app.getExpenseTypeId() != null ? + sysExpenseTypeRepository.findById(app.getExpenseTypeId()).orElse(null) : null; + + return ReimApplicationSummary.builder() + .id(app.getId()) + .applicationNo(app.getApplicationNo()) + .title(app.getTitle()) + .applicantName(applicant != null ? applicant.getRealName() : null) + .departmentName(dept != null ? dept.getDeptName() : null) + .expenseTypeName(expenseType != null ? expenseType.getTypeName() : null) + .category(app.getCategory()) + .totalAmount(app.getTotalAmount()) + .applicationStatus(app.getApplicationStatus()) + .approvalStatus(app.getApprovalStatus()) + .currentApprovalNode(app.getCurrentApprovalNode()) + .receiptStatus(app.getReceiptStatus()) + .paymentStatus(app.getPaymentStatus()) + .budgetStatus(app.getBudgetStatus()) + .submitTime(app.getSubmitTime()) + .createdAt(app.getCreatedAt()) + .build(); + } +} diff --git a/src/main/java/com/finance/system/service/impl/PostgresPaymentIdempotencyLock.java b/src/main/java/com/finance/system/service/impl/PostgresPaymentIdempotencyLock.java new file mode 100644 index 0000000..f1c2701 --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/PostgresPaymentIdempotencyLock.java @@ -0,0 +1,48 @@ +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 new file mode 100644 index 0000000..5d69add --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java @@ -0,0 +1,744 @@ +package com.finance.system.service.impl; + +import com.finance.system.dto.*; +import com.finance.system.entity.*; +import com.finance.system.enums.*; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.repository.*; +import com.finance.system.service.ReimApplicationService; +import com.finance.system.service.RoleService; +import com.finance.system.util.AuditUtil; +import com.finance.system.adapter.kingdee.KingdeeConfig; +import com.finance.system.adapter.feishu.FeishuApprovalService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.beans.factory.annotation.Autowired; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ReimApplicationServiceImpl implements ReimApplicationService { + + private final ReimApplicationRepository reimApplicationRepository; + private final SysUserRepository sysUserRepository; + private final SysDepartmentRepository sysDepartmentRepository; + private final SysExpenseTypeRepository sysExpenseTypeRepository; + private final SysBankAccountRepository sysBankAccountRepository; + private final ReimExpenseItemRepository reimExpenseItemRepository; + private final ReimInvoiceRepository reimInvoiceRepository; + private final ReimAttachmentRepository reimAttachmentRepository; + private final ReimApprovalRecordRepository reimApprovalRecordRepository; + private final ReimPaymentRepository reimPaymentRepository; + private final SysApprovalNodeRepository sysApprovalNodeRepository; + private final KingdeeConfig kingdeeConfig; + private RoleService roleService; + private FeishuApprovalService feishuApprovalService; + + @Autowired(required = false) + public void setRoleService(RoleService roleService) { + this.roleService = roleService; + } + + @Autowired(required = false) + public void setFeishuApprovalService(FeishuApprovalService feishuApprovalService) { + this.feishuApprovalService = feishuApprovalService; + } + + @Override + public WorkbenchDto getWorkbench(Long userId) { + requirePermission(userId, "reimbursement:view-own", "application:view-own"); + SysUser user = sysUserRepository.findById(userId) + .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); + + List applications = reimApplicationRepository + .findByApplicantIdOrderByCreatedAtDesc(userId); + + UserProfile userProfile = buildUserProfile(user); + List summaries = applications.stream() + .map(this::buildSummary) + .collect(Collectors.toList()); + + List payments = reimPaymentRepository.findByPayeeId(userId); + List paymentDtos = payments.stream() + .map(this::buildPaymentRecord) + .collect(Collectors.toList()); + + DashboardStats stats = buildDashboardStats(userId, applications); + + WorkbenchDto workbench = new WorkbenchDto(); + workbench.setUser(userProfile); + workbench.setReimbursements(summaries); + workbench.setPayments(paymentDtos); + workbench.setStats(stats); + return workbench; + } + + @Override + public Page getMyApplications(Long userId, String status, Pageable pageable) { + requirePermission(userId, "reimbursement:view-own", "application:view-own"); + Page applications; + if (status != null && !status.isEmpty() && !"ALL".equalsIgnoreCase(status)) { + if (ApplicationStatus.DRAFT.name().equalsIgnoreCase(status)) { + applications = reimApplicationRepository.findByApplicantIdAndApplicationStatus( + userId, ApplicationStatus.DRAFT.name(), pageable); + } else { + applications = reimApplicationRepository.findByApplicantIdAndApprovalStatus( + userId, status, pageable); + } + } else { + applications = reimApplicationRepository.findByApplicantIdOrderByCreatedAtDesc(userId, pageable); + } + return applications.map(this::buildSummary); + } + + @Override + public ReimApplicationDetail getApplicationDetail(Long id, Long userId) { + requirePermission(userId, "reimbursement:view-own", "application:view-own", + "reimbursement:view-all", "approval:view"); + ReimApplication app = reimApplicationRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ensureCanRead(app, userId); + return buildDetail(app); + } + + @Override + public ReimApplicationDetail getByApplicationNo(String applicationNo, Long userId) { + requirePermission(userId, "reimbursement:view-own", "application:view-own", + "reimbursement:view-all", "approval:view"); + ReimApplication app = reimApplicationRepository.findByApplicationNo(applicationNo); + if (app == null) { + throw new ResourceNotFoundException("报销申请不存在: " + applicationNo); + } + ensureCanRead(app, userId); + return buildDetail(app); + } + + @Override + @Transactional + public ReimApplicationDetail createApplication(CreateApplicationRequest request, Long userId) { + requirePermission(userId, "reimbursement:create", "application:create"); + SysUser user = sysUserRepository.findById(userId) + .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); + validateFieldPermissions(request, userId, null, true); + validateRequest(request, userId); + + ReimApplication app = new ReimApplication(); + app.setApplicationNo(generateApplicationNo()); + app.setTitle(request.getTitle()); + app.setApplicantId(user.getId()); + app.setDepartmentId(user.getDepartmentId()); + app.setExpenseTypeId(request.getExpenseTypeId()); + app.setCategory(request.getCategory()); + app.setTotalAmount(request.getTotalAmount()); + app.setDescription(request.getDescription()); + app.setPayeeName(request.getPayeeName()); + app.setPayeeBankId(request.getPayeeBankId()); + app.setApplicationStatus(ApplicationStatus.DRAFT.name()); + app.setApprovalStatus(ApprovalStatus.PENDING.name()); + app.setReceiptStatus(ReceiptStatus.UNRECEIVED.name()); + app.setPaymentStatus(PaymentStatus.UNPAID.name()); + app.setBudgetStatus(BudgetStatus.PENDING.name()); + app.setSourceSystem("LOCAL"); + app.setSourceStatus(kingdeeConfig.isEnabled() ? SyncStatus.PENDING.name() : "NOT_CONFIGURED"); + app.setDeleted(false); + + app = reimApplicationRepository.save(app); + + saveItems(app.getId(), request.getItems()); + + log.info("创建报销申请: applicationNo={}, userId={}", app.getApplicationNo(), userId); + return buildDetail(app); + } + + @Override + @Transactional + public ReimApplicationDetail updateApplication(Long id, CreateApplicationRequest request, Long userId) { + ReimApplication app = reimApplicationRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + requirePermission(userId, "reimbursement:create", "application:create"); + ensureOwner(app, userId); + if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { + if (!ApprovalStatus.REJECTED.name().equals(app.getApprovalStatus()) + && !ApprovalStatus.CANCELLED.name().equals(app.getApprovalStatus())) { + throw new BusinessException("只能修改草稿或退回状态的申请"); + } + } + validateFieldPermissions(request, userId, app, false); + validateRequest(request, app.getApplicantId()); + + app.setTitle(request.getTitle()); + app.setExpenseTypeId(request.getExpenseTypeId()); + app.setCategory(request.getCategory()); + app.setTotalAmount(request.getTotalAmount()); + app.setDescription(request.getDescription()); + app.setPayeeName(request.getPayeeName()); + app.setPayeeBankId(request.getPayeeBankId()); + reimExpenseItemRepository.deleteByApplicationId(id); + saveItems(app.getId(), request.getItems()); + // A returned submission re-enters the editable draft state. The next + // explicit submit then starts a fresh approval transition while the + // original application number remains unchanged. + if (ApprovalStatus.REJECTED.name().equals(app.getApprovalStatus()) + || ApprovalStatus.CANCELLED.name().equals(app.getApprovalStatus())) { + app.setApplicationStatus(ApplicationStatus.DRAFT.name()); + app.setReceiptStatus(ReceiptStatus.UNRECEIVED.name()); + } + app.setReturnReason(null); + app = reimApplicationRepository.save(app); + + return buildDetail(app); + } + + @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); + } + + log.info("提交报销申请: applicationNo={}", app.getApplicationNo()); + return buildDetail(app); + } + + @Override + @Transactional + public ReimApplicationDetail receiveApplication(Long id, Long operatorId) { + Long currentUserId = AuditUtil.getCurrentUserId(); + boolean permitted = roleService != null ? roleService.hasPermission(operatorId, "receipt:manage") + : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); + if (operatorId == null || !operatorId.equals(currentUserId) || !permitted) { + throw new com.finance.system.exception.UnauthorizedException("仅财务人员可以确认收单"); + } + + // Lock before checking or changing the receipt state so repeated/concurrent + // requests cannot create more than one receipt transition or audit record. + ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + if (!ApprovalStatus.APPROVED.name().equals(app.getApprovalStatus())) { + throw new BusinessException("申请未通过审批,无法收单"); + } + + if (ReceiptStatus.RECEIVED.name().equals(app.getReceiptStatus())) { + return buildDetail(app); + } + + app.setReceiptStatus(ReceiptStatus.RECEIVED.name()); + reimApplicationRepository.save(app); + + // Approval records are the existing application audit trail. A receipt + // action is deliberately recorded without changing approval or amount. + ReimApprovalRecord auditRecord = new ReimApprovalRecord(); + auditRecord.setApplicationId(app.getId()); + auditRecord.setNodeName("财务收单"); + auditRecord.setApproverId(operatorId); + auditRecord.setAction("RECEIVE"); + auditRecord.setComment("财务收单完成"); + auditRecord.setActionTime(LocalDateTime.now()); + reimApprovalRecordRepository.save(auditRecord); + + log.info("财务收单: applicationNo={}, operatorId={}", app.getApplicationNo(), operatorId); + return buildDetail(app); + } + + @Override + @Transactional + public void deleteApplication(Long id, Long userId) { + ReimApplication app = reimApplicationRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + requirePermission(userId, "reimbursement:create", "application:create"); + ensureOwner(app, userId); + if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { + throw new BusinessException("只能删除草稿状态的申请"); + } + + app.setDeleted(true); + reimApplicationRepository.save(app); + } + + @Override + public Page getAccountsPayableTasks(String status, Pageable pageable) { + Page tasks; + + if ("PENDING".equalsIgnoreCase(status)) { + tasks = reimApplicationRepository.findByApplicationStatusAndApprovalStatus( + ApplicationStatus.SUBMITTED.name(), ApprovalStatus.PENDING.name(), pageable); + } else if ("APPROVED".equalsIgnoreCase(status)) { + tasks = reimApplicationRepository.findByApplicationStatusAndApprovalStatus( + ApplicationStatus.SUBMITTED.name(), ApprovalStatus.APPROVED.name(), pageable); + } else { + tasks = reimApplicationRepository.findByApplicationStatus( + ApplicationStatus.SUBMITTED.name(), pageable); + } + + return tasks.map(this::buildSummary); + } + + @Override + public Page getCashierTasks(String status, Pageable pageable) { + Page tasks; + + if ("UNPAID".equalsIgnoreCase(status)) { + tasks = reimApplicationRepository.findByApprovalStatusAndPaymentStatus( + ApprovalStatus.APPROVED.name(), PaymentStatus.UNPAID.name(), pageable); + } else if ("PARTIAL".equalsIgnoreCase(status)) { + tasks = reimApplicationRepository.findByApprovalStatusAndPaymentStatus( + ApprovalStatus.APPROVED.name(), PaymentStatus.PARTIAL.name(), pageable); + } else { + tasks = reimApplicationRepository.findByApprovalStatus( + ApprovalStatus.APPROVED.name(), pageable); + } + + return tasks.map(this::buildSummary); + } + + private ReimApplicationSummary buildSummary(ReimApplication app) { + SysUser applicant = sysUserRepository.findById(app.getApplicantId()).orElse(null); + SysDepartment dept = app.getDepartmentId() != null ? + sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null; + SysExpenseType expenseType = app.getExpenseTypeId() != null ? + sysExpenseTypeRepository.findById(app.getExpenseTypeId()).orElse(null) : null; + + return ReimApplicationSummary.builder() + .id(app.getId()) + .applicationNo(app.getApplicationNo()) + .title(app.getTitle()) + .applicantName(applicant != null ? applicant.getRealName() : null) + .departmentName(dept != null ? dept.getDeptName() : null) + .expenseTypeName(expenseType != null ? expenseType.getTypeName() : null) + .category(app.getCategory()) + .totalAmount(app.getTotalAmount()) + .applicationStatus(app.getApplicationStatus()) + .approvalStatus(app.getApprovalStatus()) + .currentApprovalNode(app.getCurrentApprovalNode()) + .receiptStatus(app.getReceiptStatus()) + .paymentStatus(app.getPaymentStatus()) + .budgetStatus(app.getBudgetStatus()) + .sourceDocNo(app.getSourceDocNo()) + .sourceStatus(app.getSourceStatus()) + .returnReason(app.getReturnReason()) + .submitTime(app.getSubmitTime()) + .createdAt(app.getCreatedAt()) + .build(); + } + + private void ensureOwner(ReimApplication app, Long currentId) { + if (currentId == null || !currentId.equals(app.getApplicantId())) { + throw new org.springframework.security.access.AccessDeniedException("只能操作本人申请"); + } + } + + 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 && (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole())) return; + throw new org.springframework.security.access.AccessDeniedException("无权访问该申请"); + } + + private void requirePermission(Long userId, String... permissionCodes) { + if (userId == null) throw new com.finance.system.exception.UnauthorizedException("未登录"); + if (roleService == null) return; // retained for narrow legacy unit tests + for (String permissionCode : permissionCodes) { + if (roleService.hasPermission(userId, permissionCode)) return; + } + throw new org.springframework.security.access.AccessDeniedException("权限不足,无法访问"); + } + + private void validateFieldPermissions(CreateApplicationRequest request, Long userId, + ReimApplication existing, boolean creating) { + if (roleService == null) return; + checkField(request == null ? null : request.getTotalAmount(), existing == null ? null : existing.getTotalAmount(), + userId, "application:amount", creating, "报销金额"); + checkField(request == null ? null : request.getPayeeName(), existing == null ? null : existing.getPayeeName(), + userId, "application:payeeName", creating, "收款人"); + checkField(request == null ? null : request.getPayeeBankId(), existing == null ? null : existing.getPayeeBankId(), + userId, "application:bankAccount", creating, "收款账户"); + if (!creating && existing != null && !roleService.canEditField(userId, "application:amount") + && expenseAmountsChanged(existing.getId(), request == null ? null : request.getItems())) { + throw new BusinessException("字段无权修改: application:amount", 403); + } + } + + private void checkField(Object submitted, Object current, Long userId, String permission, + boolean creating, String label) { + String access = roleService.fieldAccess(userId, permission); + boolean missing = submitted == null || (submitted instanceof String && !org.springframework.util.StringUtils.hasText((String) submitted)); + if (creating && missing && "EDIT".equals(access)) { + throw new BusinessException(label + "不能为空", 400); + } + if (!missing && !"EDIT".equals(access) && (creating || !same(submitted, current))) { + throw new BusinessException("字段无权修改: " + permission, 403); + } + if (!creating && missing && current != null && !"EDIT".equals(access)) { + throw new BusinessException("字段无权修改: " + permission, 403); + } + } + + private boolean same(Object a, Object b) { + return a == null ? b == null : a.equals(b); + } + + private boolean expenseAmountsChanged(Long applicationId, List submitted) { + List persisted = reimExpenseItemRepository.findByApplicationId(applicationId); + if (persisted == null) persisted = Collections.emptyList(); + List oldAmounts = new ArrayList<>(); + for (ReimExpenseItem item : persisted) oldAmounts.add(item.getAmount()); + List newAmounts = new ArrayList<>(); + if (submitted != null) for (ExpenseItemDto item : submitted) newAmounts.add(item == null ? null : item.getAmount()); + return !oldAmounts.equals(newAmounts); + } + + private void validateRequest(CreateApplicationRequest request, Long userId) { + if (request == null || request.getTotalAmount() == null + || request.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) { + throw new BusinessException("总金额必须大于0", 400); + } + if (userId == null || !sysUserRepository.findById(userId).map(u -> u.getDepartmentId() != null).orElse(false)) { + throw new BusinessException("申请人未配置部门"); + } + if (request.getTitle() == null || request.getTitle().trim().isEmpty()) { + throw new BusinessException("标题不能为空", 400); + } + if (request.getPayeeName() == null || request.getPayeeName().trim().isEmpty()) { + throw new BusinessException("收款人不能为空", 400); + } + if (request.getItems() == null || request.getItems().isEmpty()) { + throw new BusinessException("费用明细不能为空"); + } + SysExpenseType type = request.getExpenseTypeId() == null ? null : + sysExpenseTypeRepository.findById(request.getExpenseTypeId()).orElse(null); + if (type == null || (type.getStatus() != null && !"ACTIVE".equalsIgnoreCase(type.getStatus()))) { + throw new BusinessException("费用类型不存在或已停用"); + } + BigDecimal sum = BigDecimal.ZERO; + for (ExpenseItemDto item : request.getItems()) { + if (item == null || item.getAmount() == null || item.getAmount().compareTo(BigDecimal.ZERO) <= 0 + || item.getCategory() == null || item.getCategory().trim().isEmpty()) { + throw new BusinessException("费用明细金额必须大于0"); + } + sum = sum.add(item.getAmount()); + } + if (sum.compareTo(request.getTotalAmount()) != 0) { + throw new BusinessException("费用明细合计必须等于总金额"); + } + if (request.getPayeeBankId() == null + || !sysBankAccountRepository.findById(request.getPayeeBankId()).map(b -> userId.equals(b.getUserId())).orElse(false)) { + throw new BusinessException("收款银行账户不属于本人", 400); + } + } + + private void validatePersistedApplication(ReimApplication app) { + List items = reimExpenseItemRepository.findByApplicationId(app.getId()); + if (app.getTotalAmount() == null || app.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0 || items.isEmpty()) { + throw new BusinessException("申请金额或费用明细无效"); + } + BigDecimal sum = items.stream().map(ReimExpenseItem::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); + if (sum.compareTo(app.getTotalAmount()) != 0) throw new BusinessException("费用明细合计必须等于总金额"); + if (app.getPayeeBankId() == null || !sysBankAccountRepository.findById(app.getPayeeBankId()) + .map(b -> app.getApplicantId().equals(b.getUserId())).orElse(false)) { + throw new BusinessException("收款银行账户不属于本人"); + } + } + + private void saveItems(Long applicationId, List items) { + int seq = 1; + for (ExpenseItemDto dto : items) { + ReimExpenseItem item = new ReimExpenseItem(); + item.setApplicationId(applicationId); + item.setSeqNo(dto.getSeqNo() == null ? seq : dto.getSeqNo()); + item.setExpenseDate(dto.getExpenseDate() == null ? LocalDate.now() : dto.getExpenseDate()); + item.setCategory(dto.getCategory()); + item.setDescription(dto.getDescription()); + item.setAmount(dto.getAmount()); + item.setCurrency("CNY"); + reimExpenseItemRepository.save(item); + seq++; + } + } + + private Long resolveApprover(SysApprovalNode node) { + if (!ApprovalRoutingRules.isApprovalNode(node)) return null; + if (node.getApproverId() != null) { + SysUser specified = sysUserRepository.findById(node.getApproverId()).orElse(null); + return ApprovalRoutingRules.matchesRole(specified, node.getApproverRole()) + ? specified.getId() : null; + } + String role = node.getApproverRole(); + List users = roleService == null + ? sysUserRepository.findByUserType("FINANCE") : sysUserRepository.findAll(); + for (SysUser user : users) { + if ((roleService == null || roleService.hasPermission(user.getId(), "approval:view")) + && ApprovalRoutingRules.matchesRole(user, role)) return user.getId(); + } + return null; + } + + private ReimApplicationDetail buildDetail(ReimApplication app) { + SysUser applicant = sysUserRepository.findById(app.getApplicantId()).orElse(null); + SysDepartment dept = app.getDepartmentId() != null ? + sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null; + SysExpenseType expenseType = app.getExpenseTypeId() != null ? + sysExpenseTypeRepository.findById(app.getExpenseTypeId()).orElse(null) : null; + + List items = reimExpenseItemRepository.findByApplicationId(app.getId()); + List invoices = reimInvoiceRepository.findByApplicationId(app.getId()); + List attachments = reimAttachmentRepository.findByApplicationId(app.getId()); + List approvalRecords = reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(app.getId()); + List payments = reimPaymentRepository.findByApplicationId(app.getId()); + SysBankAccount bank = app.getPayeeBankId() == null ? null + : sysBankAccountRepository.findById(app.getPayeeBankId()).orElse(null); + SysUser currentApprover = app.getCurrentApproverId() == null ? null + : sysUserRepository.findById(app.getCurrentApproverId()).orElse(null); + + return ReimApplicationDetail.builder() + .id(app.getId()) + .applicationNo(app.getApplicationNo()) + .title(app.getTitle()) + .applicantId(app.getApplicantId()) + .applicantName(applicant != null ? applicant.getRealName() : null) + .applicantEmployeeNo(applicant != null ? applicant.getEmployeeNo() : null) + .departmentId(app.getDepartmentId()) + .departmentName(dept != null ? dept.getDeptName() : null) + .expenseTypeId(app.getExpenseTypeId()) + .expenseTypeName(expenseType != null ? expenseType.getTypeName() : null) + .category(app.getCategory()) + .totalAmount(app.getTotalAmount()) + .description(app.getDescription()) + .applicationStatus(app.getApplicationStatus()) + .approvalStatus(app.getApprovalStatus()) + .currentApprovalNode(app.getCurrentApprovalNode()) + .currentApproverId(app.getCurrentApproverId()) + .currentApproverName(currentApprover != null ? currentApprover.getRealName() : null) + .receiptStatus(app.getReceiptStatus()) + .paymentStatus(app.getPaymentStatus()) + .budgetStatus(app.getBudgetStatus()) + .sourceDocNo(app.getSourceDocNo()) + .sourceDocType(app.getSourceDocType()) + .sourceSystem(app.getSourceSystem()) + .sourceDocDate(app.getSourceDocDate()) + .sourceStatus(app.getSourceStatus()) + .payeeName(app.getPayeeName()) + .payeeBankId(app.getPayeeBankId()) + .bankName(bank != null ? bank.getBankName() : null) + .bankAccountMask(bank != null ? bank.getAccountNoMask() : null) + .returnReason(app.getReturnReason()) + .submitTime(app.getSubmitTime()) + .approveTime(app.getApproveTime()) + .createdAt(app.getCreatedAt()) + .updatedAt(app.getUpdatedAt()) + .expenseItems(items.stream().map(this::buildExpenseItem).collect(Collectors.toList())) + .invoices(invoices.stream().map(this::buildInvoice).collect(Collectors.toList())) + .attachments(attachments.stream().map(this::buildAttachment).collect(Collectors.toList())) + .approvalRecords(approvalRecords.stream().map(this::buildApprovalRecord).collect(Collectors.toList())) + .payments(payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList())) + .build(); + } + + private ExpenseItemDto buildExpenseItem(ReimExpenseItem item) { + ExpenseItemDto dto = new ExpenseItemDto(); + dto.setId(item.getId()); + dto.setSeqNo(item.getSeqNo()); + dto.setExpenseDate(item.getExpenseDate()); + dto.setCategory(item.getCategory()); + dto.setDescription(item.getDescription()); + dto.setAmount(item.getAmount()); + return dto; + } + + private InvoiceDto buildInvoice(ReimInvoice invoice) { + InvoiceDto dto = new InvoiceDto(); + dto.setId(invoice.getId()); + dto.setInvoiceNo(invoice.getInvoiceNo()); + dto.setInvoiceType(invoice.getInvoiceType()); + dto.setIssueDate(invoice.getIssueDate()); + dto.setAmount(invoice.getAmount()); + dto.setSellerName(invoice.getSellerName()); + dto.setVerifyStatus(invoice.getVerifyStatus()); + return dto; + } + + private AttachmentDto buildAttachment(ReimAttachment attachment) { + AttachmentDto dto = new AttachmentDto(); + dto.setId(attachment.getId()); + dto.setFileName(attachment.getFileName()); + dto.setFileType(attachment.getFileType()); + dto.setFileUrl(attachment.getFileUrl()); + return dto; + } + + private ApprovalRecordDto buildApprovalRecord(ReimApprovalRecord record) { + SysUser approver = record.getApproverId() != null ? + sysUserRepository.findById(record.getApproverId()).orElse(null) : null; + + ApprovalRecordDto dto = new ApprovalRecordDto(); + dto.setId(record.getId()); + dto.setNodeName(record.getNodeName()); + dto.setApproverName(approver != null ? approver.getRealName() : null); + dto.setAction(record.getAction()); + dto.setComment(record.getComment()); + dto.setActionTime(record.getActionTime()); + return dto; + } + + private PaymentRecordDto buildPaymentRecord(ReimPayment payment) { + SysUser operator = payment.getOperatorId() != null ? + sysUserRepository.findById(payment.getOperatorId()).orElse(null) : null; + + PaymentRecordDto dto = new PaymentRecordDto(); + dto.setId(payment.getId()); + dto.setPaymentNo(payment.getPaymentNo()); + dto.setPaymentAmount(payment.getPaymentAmount()); + dto.setTotalAmount(payment.getTotalAmount()); + dto.setPaidAmount(payment.getPaidAmount()); + dto.setRemainingAmount(payment.getRemainingAmount()); + dto.setPaymentMethod(payment.getPaymentMethod()); + dto.setPaymentStatus(payment.getPaymentStatus()); + dto.setOperatorName(operator != null ? operator.getRealName() : null); + dto.setPaymentTime(payment.getPaymentTime()); + dto.setRemark(payment.getRemark()); + return dto; + } + + private UserProfile buildUserProfile(SysUser user) { + String deptName = null; + if (user.getDepartmentId() != null) { + SysDepartment dept = sysDepartmentRepository.findById(user.getDepartmentId()).orElse(null); + if (dept != null) deptName = dept.getDeptName(); + } + return UserProfile.builder() + .id(user.getId()) + .employeeNo(user.getEmployeeNo()) + .realName(user.getRealName()) + .avatarUrl(user.getAvatarUrl()) + .email(user.getEmail()) + .departmentName(deptName) + .position(user.getPosition()) + .userType(RoleService.normalize(user.getUserType())) + .feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定") + .build(); + } + + private DashboardStats buildDashboardStats(Long userId, List applications) { + long total = applications.size(); + long pendingApproval = applications.stream() + .filter(a -> ApprovalStatus.PENDING.name().equals(a.getApprovalStatus())) + .count(); + long approved = applications.stream() + .filter(a -> ApprovalStatus.APPROVED.name().equals(a.getApprovalStatus())) + .count(); + long rejected = applications.stream() + .filter(a -> ApprovalStatus.REJECTED.name().equals(a.getApprovalStatus())) + .count(); + long pendingPayment = applications.stream() + .filter(a -> PaymentStatus.UNPAID.name().equals(a.getPaymentStatus())) + .count(); + long unpaid = applications.stream() + .filter(a -> PaymentStatus.UNPAID.name().equals(a.getPaymentStatus()) + || PaymentStatus.PARTIAL.name().equals(a.getPaymentStatus())) + .count(); + + BigDecimal totalAmount = applications.stream() + .map(ReimApplication::getTotalAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + return DashboardStats.builder() + .totalApplications(total) + .pendingApproval(pendingApproval) + .approved(approved) + .rejected(rejected) + .pendingPayment(pendingPayment) + .unpaid(unpaid) + .totalAmount(totalAmount) + .build(); + } + + private String generateApplicationNo() { + String datePart = LocalDate.now().toString().replace("-", ""); + List lastApps = reimApplicationRepository + .findTopByApplicationNoStartingWithOrderByApplicationNoDesc("BX" + datePart); + int seq = 1; + if (!lastApps.isEmpty()) { + String lastNo = lastApps.get(0).getApplicationNo(); + seq = Integer.parseInt(lastNo.substring(10)) + 1; + } + return "BX" + datePart + String.format("%04d", seq); + } +} diff --git a/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java new file mode 100644 index 0000000..b59e92e --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java @@ -0,0 +1,239 @@ +package com.finance.system.service.impl; + +import com.finance.system.dto.ApprovalRecordDto; +import com.finance.system.entity.ReimApplication; +import com.finance.system.entity.ReimApprovalRecord; +import com.finance.system.entity.SysApprovalNode; +import com.finance.system.entity.SysUser; +import com.finance.system.enums.ApprovalAction; +import com.finance.system.enums.ApprovalStatus; +import com.finance.system.enums.ApplicationStatus; +import com.finance.system.enums.BudgetStatus; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.repository.*; +import com.finance.system.service.ReimApprovalService; +import com.finance.system.service.RoleService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.beans.factory.annotation.Autowired; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ReimApprovalServiceImpl implements ReimApprovalService { + + private final ReimApplicationRepository reimApplicationRepository; + private final ReimApprovalRecordRepository reimApprovalRecordRepository; + private final SysUserRepository sysUserRepository; + private final SysApprovalNodeRepository sysApprovalNodeRepository; + private RoleService roleService; + + @Autowired(required = false) + public void setRoleService(RoleService roleService) { + this.roleService = roleService; + } + + @Override + @Transactional + public ApprovalRecordDto approve(Long applicationId, Long approverId, String comment) { + ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + if (!ApplicationStatus.SUBMITTED.name().equals(app.getApplicationStatus()) + || !ApprovalStatus.PENDING.name().equals(app.getApprovalStatus())) { + throw new BusinessException("该申请不在待审批状态"); + } + ensureCurrentApprover(app, approverId); + + // 记录审批动作 + ReimApprovalRecord record = new ReimApprovalRecord(); + record.setApplicationId(applicationId); + record.setNodeName(app.getCurrentApprovalNode()); + record.setApproverId(approverId); + record.setAction(ApprovalAction.APPROVE.name()); + record.setComment(comment); + record.setActionTime(LocalDateTime.now()); + reimApprovalRecordRepository.save(record); + + // 查找下一个审批节点 + SysApprovalNode currentNode = sysApprovalNodeRepository.findByNodeName(app.getCurrentApprovalNode()); + if (currentNode == null) { + throw new BusinessException("当前审批节点配置不存在,无法继续审批"); + } + SysApprovalNode nextNode = null; + List allNodes = sysApprovalNodeRepository.findAllByOrderBySortOrder(); + int currentIndex = -1; + for (int i = 0; i < allNodes.size(); i++) { + if (allNodes.get(i).getNodeCode().equals(currentNode.getNodeCode())) { + currentIndex = i; + break; + } + } + if (currentIndex >= 0) { + for (int i = currentIndex + 1; i < allNodes.size(); i++) { + if (ApprovalRoutingRules.isApprovalNode(allNodes.get(i))) { + nextNode = allNodes.get(i); + break; + } + } + } else { + throw new BusinessException("当前审批节点不在审批流程中,无法继续审批"); + } + + if (nextNode != null) { + Long nextApproverId = resolveApprover(nextNode); + if (nextApproverId == null) { + throw new BusinessException("下一个审批节点未配置有效审批人,无法继续审批"); + } + // 流转到下一个节点 + app.setCurrentApprovalNode(nextNode.getNodeName()); + app.setCurrentApproverId(nextApproverId); + } else { + // 审批完成 + app.setApprovalStatus(ApprovalStatus.APPROVED.name()); + app.setCurrentApprovalNode("流程已完成"); + app.setCurrentApproverId(null); + app.setApproveTime(LocalDateTime.now()); + app.setBudgetStatus(BudgetStatus.EXECUTED.name()); + } + + reimApplicationRepository.save(app); + + log.info("审批通过: applicationNo={}, approverId={}", app.getApplicationNo(), approverId); + return buildApprovalRecordDto(record); + } + + @Override + @Transactional + public ApprovalRecordDto reject(Long applicationId, Long approverId, String comment, String returnReason) { + ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + if (!ApplicationStatus.SUBMITTED.name().equals(app.getApplicationStatus()) + || !ApprovalStatus.PENDING.name().equals(app.getApprovalStatus())) { + throw new BusinessException("该申请不在待审批状态"); + } + ensureCurrentApprover(app, approverId); + + // 记录审批动作 + ReimApprovalRecord record = new ReimApprovalRecord(); + record.setApplicationId(applicationId); + record.setNodeName(app.getCurrentApprovalNode()); + record.setApproverId(approverId); + record.setAction(ApprovalAction.REJECT.name()); + record.setComment(comment); + record.setActionTime(LocalDateTime.now()); + reimApprovalRecordRepository.save(record); + + // 退回申请 + app.setApplicationStatus(com.finance.system.enums.ApplicationStatus.DRAFT.name()); + app.setApprovalStatus(ApprovalStatus.REJECTED.name()); + app.setReturnReason(returnReason != null ? returnReason : comment); + app.setCurrentApprovalNode("申请人补充材料"); + app.setCurrentApproverId(app.getApplicantId()); + reimApplicationRepository.save(app); + + log.info("审批退回: applicationNo={}, approverId={}, reason={}", + app.getApplicationNo(), approverId, returnReason); + return buildApprovalRecordDto(record); + } + + @Override + @Transactional + public ApprovalRecordDto transfer(Long applicationId, Long fromUserId, Long toUserId, String comment) { + ReimApplication app = reimApplicationRepository.findById(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + ReimApprovalRecord record = new ReimApprovalRecord(); + record.setApplicationId(applicationId); + record.setNodeName(app.getCurrentApprovalNode()); + record.setApproverId(fromUserId); + record.setAction(ApprovalAction.TRANSFER.name()); + record.setComment(comment); + record.setActionTime(LocalDateTime.now()); + reimApprovalRecordRepository.save(record); + + app.setCurrentApproverId(toUserId); + reimApplicationRepository.save(app); + + return buildApprovalRecordDto(record); + } + + @Override + public List getApprovalHistory(Long applicationId) { + List records = reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(applicationId); + return records.stream().map(this::buildApprovalRecordDto).collect(Collectors.toList()); + } + + @Override + public List getApprovalHistoryByUser(Long userId) { + List records = reimApprovalRecordRepository.findByApproverId(userId); + return records.stream().map(this::buildApprovalRecordDto).collect(Collectors.toList()); + } + + private ApprovalRecordDto buildApprovalRecordDto(ReimApprovalRecord record) { + SysUser approver = record.getApproverId() != null ? + sysUserRepository.findById(record.getApproverId()).orElse(null) : null; + + ApprovalRecordDto dto = new ApprovalRecordDto(); + dto.setId(record.getId()); + dto.setNodeName(record.getNodeName()); + dto.setApproverName(approver != null ? approver.getRealName() : null); + dto.setAction(record.getAction()); + dto.setComment(record.getComment()); + dto.setActionTime(record.getActionTime()); + return dto; + } + + private void ensureCurrentApprover(ReimApplication app, Long approverId) { + Long actorId = AuditUtil.getCurrentUserId(); + boolean permitted = roleService != null ? roleService.hasPermission(approverId, "approval:view") + : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); + if (approverId == null || (actorId != null && !approverId.equals(actorId)) || !permitted) { + throw new com.finance.system.exception.UnauthorizedException("无审批权限"); + } + SysUser actingUser = sysUserRepository.findById(approverId).orElse(null); + if (!ApprovalRoutingRules.isActive(actingUser)) { + throw new com.finance.system.exception.UnauthorizedException("审批用户不存在或已停用"); + } + if (app.getCurrentApproverId() == null) { + throw new BusinessException("当前申请未配置有效审批人,无法审批"); + } + SysUser currentApprover = sysUserRepository.findById(app.getCurrentApproverId()).orElse(null); + if (!ApprovalRoutingRules.isActive(currentApprover)) { + throw new BusinessException("当前审批人不存在或已停用,无法审批"); + } + SysApprovalNode currentNode = sysApprovalNodeRepository.findByNodeName(app.getCurrentApprovalNode()); + if (!ApprovalRoutingRules.isApprovalNode(currentNode) + || !ApprovalRoutingRules.matchesRole(currentApprover, currentNode.getApproverRole())) { + throw new BusinessException("当前审批节点与审批人配置不匹配,无法审批"); + } + if (app.getCurrentApproverId().equals(approverId)) return; + throw new com.finance.system.exception.UnauthorizedException("当前申请不属于您的审批节点"); + } + + private Long resolveApprover(SysApprovalNode node) { + if (!ApprovalRoutingRules.isApprovalNode(node)) return null; + if (node.getApproverId() != null) { + SysUser specified = sysUserRepository.findById(node.getApproverId()).orElse(null); + return ApprovalRoutingRules.matchesRole(specified, node.getApproverRole()) + ? specified.getId() : null; + } + List users = roleService == null + ? sysUserRepository.findByUserType("FINANCE") : sysUserRepository.findAll(); + for (SysUser user : users) { + if ((roleService == null || roleService.hasPermission(user.getId(), "approval:view")) + && 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 new file mode 100644 index 0000000..1a4b1fc --- /dev/null +++ b/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java @@ -0,0 +1,360 @@ +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.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.repository.*; +import com.finance.system.service.PaymentIdempotencyLock; +import com.finance.system.service.ReimPaymentService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.finance.system.util.AuditUtil; +import com.finance.system.service.RoleService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ReimPaymentServiceImpl implements ReimPaymentService { + + private final ReimApplicationRepository reimApplicationRepository; + private final ReimPaymentRepository reimPaymentRepository; + private final ReimPaymentInstallmentRepository reimPaymentInstallmentRepository; + private final ReimApprovalRecordRepository reimApprovalRecordRepository; + private final SysUserRepository sysUserRepository; + private final SysBankAccountRepository sysBankAccountRepository; + private final SysDepartmentRepository sysDepartmentRepository; + private final PaymentIdempotencyLock paymentIdempotencyLock; + private RoleService roleService; + + @Autowired(required = false) + public void setRoleService(RoleService roleService) { + this.roleService = roleService; + } + + @Override + public Page getPendingPayments(Long operatorId, Pageable pageable) { + requirePaymentPermission(operatorId); + Page applications = reimApplicationRepository + .findByApprovalStatusAndPaymentStatusIn( + "APPROVED", + java.util.Arrays.asList("UNPAID", "PARTIAL"), + pageable); + + return applications.map(this::buildPaymentTask); + } + + @Override + public PaymentDetailDto getPaymentDetail(Long applicationId, Long operatorId) { + requirePaymentPermission(operatorId); + ReimApplication app = reimApplicationRepository.findById(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + + SysUser payee = sysUserRepository.findById(app.getApplicantId()).orElse(null); + SysDepartment dept = app.getDepartmentId() != null ? + sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null; + + List payments = reimPaymentRepository.findByApplicationId(applicationId); + List approvalRecords = reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(applicationId); + + BigDecimal paidAmount = payments.stream() + .filter(p -> "COMPLETED".equals(p.getPaymentStatus())) + .map(ReimPayment::getPaymentAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal remainingAmount = app.getTotalAmount().subtract(paidAmount); + + PaymentDetailDto dto = new PaymentDetailDto(); + dto.setId(app.getId()); + dto.setApplicationNo(app.getApplicationNo()); + dto.setTitle(app.getTitle()); + dto.setPayeeName(app.getPayeeName()); + dto.setDepartmentName(dept != null ? dept.getDeptName() : app.getPayeeName()); + dto.setTotalAmount(app.getTotalAmount()); + dto.setPaidAmount(paidAmount); + dto.setRemainingAmount(remainingAmount); + dto.setPaymentStatus(app.getPaymentStatus()); + + // 获取银行信息 + if (app.getPayeeBankId() != null) { + SysBankAccount bank = sysBankAccountRepository.findById(app.getPayeeBankId()).orElse(null); + if (bank != null) { + dto.setBankName(bank.getBankName()); + dto.setBranchName(bank.getBranchName()); + dto.setBankAccountMask(bank.getAccountNoMask()); + dto.setAccountName(bank.getAccountName()); + } + } + + dto.setPaymentHistory(payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList())); + dto.setApprovalRecords(approvalRecords.stream().map(this::buildApprovalRecord).collect(Collectors.toList())); + + return dto; + } + + @Override + @Transactional + public PaymentResultDto executePayment(Long applicationId, BigDecimal amount, Long operatorId, + String paymentMethod, String referenceNo, String remark, + String idempotencyKey) { + return executePaymentInternal(applicationId, amount, operatorId, paymentMethod, referenceNo, + remark, idempotencyKey, true, false); + } + + private PaymentResultDto executePaymentInternal(Long applicationId, BigDecimal amount, Long operatorId, + 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("无权使用其他用户身份付款"); + } + ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + String normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey); + if (normalizedIdempotencyKey != null) { + // Acquire the transaction-scoped PostgreSQL advisory lock before + // reading the key. This serializes claims across application rows. + paymentIdempotencyLock.lock(normalizedIdempotencyKey); + ReimPayment existing = reimPaymentRepository.findByIdempotencyKey(normalizedIdempotencyKey); + if (existing != null) { + if (!sameIdempotentRequest(existing, applicationId, amount, operatorId, + paymentMethod, referenceNo, remark)) { + throw new BusinessException("幂等键已用于其他付款请求", 409); + } + return buildPaymentResult(existing); + } + } + + if (!"APPROVED".equals(app.getApprovalStatus())) { + throw new BusinessException("申请未通过审批,无法付款"); + } + if (!"RECEIVED".equals(app.getReceiptStatus())) { + throw new BusinessException("申请尚未完成财务收单,无法付款"); + } + + if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) { + throw new BusinessException("付款金额必须大于0"); + } + idempotencyKey = normalizedIdempotencyKey; + + // 计算已付金额 + List existingPayments = reimPaymentRepository.findByApplicationId(applicationId); + BigDecimal paidAmount = existingPayments.stream() + .filter(p -> "COMPLETED".equals(p.getPaymentStatus())) + .map(ReimPayment::getPaymentAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + BigDecimal remaining = app.getTotalAmount().subtract(paidAmount); + + if (amount.compareTo(remaining) > 0) { + throw new BusinessException("付款金额超过剩余未付金额"); + } + if (requireFullPayment && amount.compareTo(remaining) != 0) { + throw new BusinessException("全额付款金额必须等于剩余未付金额"); + } + if (partialOnly && amount.compareTo(remaining) >= 0) { + throw new BusinessException("部分付款必须小于剩余未付金额"); + } + + // 创建付款记录 + ReimPayment payment = new ReimPayment(); + payment.setPaymentNo(generatePaymentNo()); + payment.setApplicationId(applicationId); + payment.setPayeeId(app.getApplicantId()); + payment.setPayeeBankId(app.getPayeeBankId()); + payment.setTotalAmount(app.getTotalAmount()); + payment.setPaymentAmount(amount); + payment.setPaidAmount(paidAmount.add(amount)); + payment.setRemainingAmount(remaining.subtract(amount)); + payment.setPaymentMethod(paymentMethod == null || paymentMethod.trim().isEmpty() + ? "BANK_TRANSFER" : paymentMethod.trim()); + payment.setReferenceNo(referenceNo); + payment.setBankAccountNo(null); // never persist a full account number + payment.setOperatorId(operatorId); + payment.setPaymentStatus("COMPLETED"); + payment.setPaymentTime(LocalDateTime.now()); + payment.setIdempotencyKey(idempotencyKey); + payment.setRemark(remark); + payment.setDeleted(false); + payment = reimPaymentRepository.save(payment); + + // 更新申请付款状态 + BigDecimal newPaidAmount = paidAmount.add(amount); + if (newPaidAmount.compareTo(app.getTotalAmount()) >= 0) { + app.setPaymentStatus(PaymentStatus.PAID.name()); + } else { + app.setPaymentStatus(PaymentStatus.PARTIAL.name()); + } + reimApplicationRepository.save(app); + + log.info("执行付款: paymentNo={}, applicationNo={}, amount={}", + payment.getPaymentNo(), app.getApplicationNo(), amount); + + PaymentResultDto result = new PaymentResultDto(); + result.setPaymentNo(payment.getPaymentNo()); + result.setAmount(amount); + result.setPaymentStatus("COMPLETED"); + result.setMessage("付款登记成功(模拟)"); + return result; + } + + @Override + @Transactional + public PaymentResultDto processPartialPayment(Long applicationId, BigDecimal amount, Long operatorId, + String paymentMethod, String referenceNo, String remark, + String idempotencyKey) { + // Keep all state and amount checks behind the application row lock. This + // also makes an idempotent retry return its original result before any + // duplicate validation can reject it. + return executePaymentInternal(applicationId, amount, operatorId, paymentMethod, referenceNo, + remark, idempotencyKey, false, true); + } + + @Override + public List getPaymentHistoryByOperator(Long operatorId) { + requirePaymentPermission(operatorId); + List payments = reimPaymentRepository.findByOperatorId(operatorId); + return payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList()); + } + + @Override + public PaymentRecordDto getPaymentByNo(String paymentNo, Long operatorId) { + requirePaymentPermission(operatorId); + ReimPayment payment = reimPaymentRepository.findByPaymentNo(paymentNo); + if (payment == null) { + throw new ResourceNotFoundException("付款记录不存在: " + paymentNo); + } + return buildPaymentRecord(payment); + } + + private void requirePaymentPermission(Long operatorId) { + boolean permitted = roleService != null ? roleService.hasPermission(operatorId, "payment:register") + : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); + if (!permitted) throw new com.finance.system.exception.UnauthorizedException("仅财务人员可以登记付款"); + } + + private boolean sameIdempotentRequest(ReimPayment existing, Long applicationId, BigDecimal amount, + Long operatorId, String paymentMethod, String referenceNo, String remark) { + return java.util.Objects.equals(existing.getApplicationId(), applicationId) + && java.util.Objects.equals(existing.getOperatorId(), operatorId) + && sameAmount(existing.getPaymentAmount(), amount) + && java.util.Objects.equals(normalizePaymentMethod(existing.getPaymentMethod()), + normalizePaymentMethod(paymentMethod)) + && java.util.Objects.equals(existing.getReferenceNo(), referenceNo) + && java.util.Objects.equals(existing.getRemark(), remark); + } + + private boolean sameAmount(BigDecimal left, BigDecimal right) { + return left == null ? right == null : right != null && left.compareTo(right) == 0; + } + + private String normalizePaymentMethod(String paymentMethod) { + return paymentMethod == null || paymentMethod.trim().isEmpty() + ? "BANK_TRANSFER" : paymentMethod.trim(); + } + + private String normalizeIdempotencyKey(String idempotencyKey) { + if (idempotencyKey == null || idempotencyKey.trim().isEmpty()) return null; + return idempotencyKey.trim(); + } + + private PaymentTaskDto buildPaymentTask(ReimApplication app) { + SysUser payee = sysUserRepository.findById(app.getApplicantId()).orElse(null); + SysDepartment dept = app.getDepartmentId() != null ? + sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null; + + List payments = reimPaymentRepository.findByApplicationId(app.getId()); + BigDecimal paidAmount = payments.stream() + .filter(p -> "COMPLETED".equals(p.getPaymentStatus())) + .map(ReimPayment::getPaymentAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal remaining = app.getTotalAmount().subtract(paidAmount); + + PaymentTaskDto dto = new PaymentTaskDto(); + dto.setId(app.getId()); + dto.setApplicationNo(app.getApplicationNo()); + dto.setTitle(app.getTitle()); + dto.setPayeeName(app.getPayeeName()); + dto.setDepartmentName(dept != null ? dept.getDeptName() : null); + dto.setTotalAmount(app.getTotalAmount()); + dto.setPaidAmount(paidAmount); + dto.setRemainingAmount(remaining); + dto.setPaymentStatus(app.getPaymentStatus()); + dto.setReceiptStatus(app.getReceiptStatus()); + dto.setApprovalStatus(app.getApprovalStatus()); + dto.setSubmitTime(app.getSubmitTime()); + dto.setCreatedAt(app.getCreatedAt()); + + // 获取银行信息 + if (app.getPayeeBankId() != null) { + SysBankAccount bank = sysBankAccountRepository.findById(app.getPayeeBankId()).orElse(null); + if (bank != null) { + dto.setBankName(bank.getBankName()); + dto.setBankAccountMask(bank.getAccountNoMask()); + } + } + + return dto; + } + + private PaymentRecordDto buildPaymentRecord(ReimPayment payment) { + SysUser operator = payment.getOperatorId() != null ? + sysUserRepository.findById(payment.getOperatorId()).orElse(null) : null; + + PaymentRecordDto dto = new PaymentRecordDto(); + dto.setId(payment.getId()); + dto.setPaymentNo(payment.getPaymentNo()); + dto.setPaymentAmount(payment.getPaymentAmount()); + dto.setTotalAmount(payment.getTotalAmount()); + dto.setPaidAmount(payment.getPaidAmount()); + dto.setRemainingAmount(payment.getRemainingAmount()); + dto.setPaymentMethod(payment.getPaymentMethod()); + dto.setReferenceNo(payment.getReferenceNo()); + dto.setPaymentStatus(payment.getPaymentStatus()); + dto.setOperatorName(operator != null ? operator.getRealName() : null); + dto.setPaymentTime(payment.getPaymentTime()); + dto.setRemark(payment.getRemark()); + return dto; + } + + private PaymentResultDto buildPaymentResult(ReimPayment payment) { + return PaymentResultDto.builder().paymentNo(payment.getPaymentNo()) + .amount(payment.getPaymentAmount()).paymentStatus(payment.getPaymentStatus()) + .message("重复请求,返回原付款结果").build(); + } + + private ApprovalRecordDto buildApprovalRecord(ReimApprovalRecord record) { + SysUser approver = record.getApproverId() != null ? + sysUserRepository.findById(record.getApproverId()).orElse(null) : null; + + ApprovalRecordDto dto = new ApprovalRecordDto(); + dto.setId(record.getId()); + dto.setNodeName(record.getNodeName()); + dto.setApproverName(approver != null ? approver.getRealName() : null); + dto.setAction(record.getAction()); + dto.setComment(record.getComment()); + dto.setActionTime(record.getActionTime()); + return dto; + } + + private String generatePaymentNo() { + String datePart = LocalDate.now().toString().replace("-", ""); + String randomPart = UUID.randomUUID().toString().replace("-", "") + .substring(0, 12).toUpperCase(java.util.Locale.ROOT); + return "PAY-" + datePart + "-" + randomPart; + } +} diff --git a/src/main/java/com/finance/system/util/AuditUtil.java b/src/main/java/com/finance/system/util/AuditUtil.java new file mode 100644 index 0000000..e96be13 --- /dev/null +++ b/src/main/java/com/finance/system/util/AuditUtil.java @@ -0,0 +1,37 @@ +package com.finance.system.util; + +import com.finance.system.security.UserPrincipal; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class AuditUtil { + + public static UserPrincipal getCurrentUser() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getPrincipal() instanceof UserPrincipal) { + return (UserPrincipal) authentication.getPrincipal(); + } + return null; + } + + public static Long getCurrentUserId() { + UserPrincipal user = getCurrentUser(); + return user != null ? user.getId() : null; + } + + public static String getCurrentUserRealName() { + UserPrincipal user = getCurrentUser(); + return user != null ? user.getRealName() : "系统"; + } + + public static boolean isFinanceRole() { + UserPrincipal user = getCurrentUser(); + return user != null && "FINANCE".equalsIgnoreCase(user.getUserType()); + } + + public static boolean isAdminRole() { + UserPrincipal user = getCurrentUser(); + return user != null && ("ADMIN".equalsIgnoreCase(user.getUserType()) + || "SUPER_ADMIN".equalsIgnoreCase(user.getUserType())); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..8c0b42d --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,75 @@ +server: + port: 8080 +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 + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + idle-timeout: 300000 + connection-timeout: 20000 + jpa: + hibernate: + ddl-auto: validate + show-sql: false + properties: + hibernate: + format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + open-in-view: false + flyway: + enabled: true + baseline-on-migrate: true + locations: classpath:db/migration +jwt: + secret: "${JWT_SECRET:}" + expiration: ${JWT_EXPIRATION:86400000} +auth: + time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}" +feishu: + app-id: "${FEISHU_APP_ID:}" + app-secret: "${FEISHU_APP_SECRET:}" + redirect-uri: "${FEISHU_REDIRECT_URI:http://127.0.0.1:8080/api/feishu/callback}" + local-bootstrap-enabled: ${FEISHU_LOCAL_BOOTSTRAP_ENABLED:false} + local-bootstrap-open-id: "${FEISHU_LOCAL_BOOTSTRAP_OPEN_ID:}" + 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} + max-retries: ${FEISHU_DIRECTORY_MAX_RETRIES:3} + requests-per-second: ${FEISHU_DIRECTORY_REQUESTS_PER_SECOND:45} + requests-per-minute: ${FEISHU_DIRECTORY_REQUESTS_PER_MINUTE:900} + approval: + approval-code: ${FEISHU_APPROVAL_CODE:} + verification-token: ${FEISHU_VERIFICATION_TOKEN:} + encrypt-key: ${FEISHU_ENCRYPT_KEY:} +app: + frontend-url: ${FRONTEND_URL:http://localhost:5173} + # Required when saving secret=true integration settings. Never put a real + # key in this file; provide APP_INTEGRATION_ENCRYPTION_KEY at deployment. + integration-encryption-key: "${APP_INTEGRATION_ENCRYPTION_KEY:}" +kingdee: + enabled: ${KINGDEE_ENABLED:false} + base-url: ${KINGDEE_BASE_URL:} + client-id: ${KINGDEE_CLIENT_ID:} + client-secret: ${KINGDEE_CLIENT_SECRET:} + db-id: ${KINGDEE_DB_ID:} +logging: + level: + com.finance.system: DEBUG + org.springframework.security: INFO + org.hibernate.SQL: WARN +springdoc: + api-docs: + path: /v3/api-docs + swagger-ui: + path: /swagger-ui.html + enabled: true diff --git a/src/main/resources/db/migration/V10__feishu_directory_normalized.sql b/src/main/resources/db/migration/V10__feishu_directory_normalized.sql new file mode 100644 index 0000000..defc272 --- /dev/null +++ b/src/main/resources/db/migration/V10__feishu_directory_normalized.sql @@ -0,0 +1,62 @@ +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 new file mode 100644 index 0000000..c439b37 --- /dev/null +++ b/src/main/resources/db/migration/V11__feishu_directory_user_details.sql @@ -0,0 +1,17 @@ +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 new file mode 100644 index 0000000..f8fd897 --- /dev/null +++ b/src/main/resources/db/migration/V1__init_schema.sql @@ -0,0 +1,62 @@ +-- 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 new file mode 100644 index 0000000..f1548b6 --- /dev/null +++ b/src/main/resources/db/migration/V2__add_local_password_hash.sql @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..4c7b3dd --- /dev/null +++ b/src/main/resources/db/migration/V3__add_oauth_state.sql @@ -0,0 +1,3 @@ +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 new file mode 100644 index 0000000..63b7402 --- /dev/null +++ b/src/main/resources/db/migration/V4__add_webhook_event_inbox.sql @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..49925e0 --- /dev/null +++ b/src/main/resources/db/migration/V5__add_rbac_and_integration_config.sql @@ -0,0 +1,105 @@ +-- 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 new file mode 100644 index 0000000..a9b4338 --- /dev/null +++ b/src/main/resources/db/migration/V6__add_super_admin_role.sql @@ -0,0 +1,25 @@ +-- 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 new file mode 100644 index 0000000..33758b6 --- /dev/null +++ b/src/main/resources/db/migration/V7__unique_feishu_application_mapping.sql @@ -0,0 +1,10 @@ +-- 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 new file mode 100644 index 0000000..f41eb56 --- /dev/null +++ b/src/main/resources/db/migration/V8__feishu_directory.sql @@ -0,0 +1,12 @@ +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 new file mode 100644 index 0000000..4bcb3e5 --- /dev/null +++ b/src/main/resources/db/migration/V9__feishu_directory_snapshot.sql @@ -0,0 +1,2 @@ +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 new file mode 100644 index 0000000..ed7755d --- /dev/null +++ b/src/main/resources/db/seed/seed_dev_admin.sql @@ -0,0 +1,68 @@ +-- ============================================================================ +-- 开发测试环境:预配置飞书超级管理员 +-- ============================================================================ +-- 使用说明: +-- 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 new file mode 100644 index 0000000..0d150d8 --- /dev/null +++ b/src/test/java/com/finance/system/ReimbursementMvpIntegrationTest.java @@ -0,0 +1,144 @@ +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 new file mode 100644 index 0000000..cbeb5b4 --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalServiceTest.java @@ -0,0 +1,225 @@ +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 new file mode 100644 index 0000000..0f80f75 --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuAuthServiceTest.java @@ -0,0 +1,213 @@ +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 new file mode 100644 index 0000000..8725c65 --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryAuthGateTest.java @@ -0,0 +1,106 @@ +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 new file mode 100644 index 0000000..5f3a379 --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryClientTest.java @@ -0,0 +1,421 @@ +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 new file mode 100644 index 0000000..b22612d --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryMigrationTest.java @@ -0,0 +1,66 @@ +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 new file mode 100644 index 0000000..9ea750e --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryPersistenceTest.java @@ -0,0 +1,470 @@ +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 new file mode 100644 index 0000000..57493c5 --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuDirectoryReviewRegressionTest.java @@ -0,0 +1,210 @@ +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 new file mode 100644 index 0000000..b450db9 --- /dev/null +++ b/src/test/java/com/finance/system/adapter/feishu/FeishuTenantTokenServiceTest.java @@ -0,0 +1,94 @@ +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 new file mode 100644 index 0000000..5f4f83d --- /dev/null +++ b/src/test/java/com/finance/system/config/JwtConfigTest.java @@ -0,0 +1,182 @@ +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 new file mode 100644 index 0000000..057cb39 --- /dev/null +++ b/src/test/java/com/finance/system/config/WebConfigTest.java @@ -0,0 +1,39 @@ +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 new file mode 100644 index 0000000..478766d --- /dev/null +++ b/src/test/java/com/finance/system/controller/AuthControllerTest.java @@ -0,0 +1,58 @@ +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 new file mode 100644 index 0000000..4ceb86c --- /dev/null +++ b/src/test/java/com/finance/system/controller/CashierControllerTest.java @@ -0,0 +1,82 @@ +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 new file mode 100644 index 0000000..4bea227 --- /dev/null +++ b/src/test/java/com/finance/system/controller/FeishuDirectoryControllerTest.java @@ -0,0 +1,42 @@ +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 new file mode 100644 index 0000000..44d1b24 --- /dev/null +++ b/src/test/java/com/finance/system/controller/FeishuWebhookControllerTest.java @@ -0,0 +1,97 @@ +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 new file mode 100644 index 0000000..0c989c7 --- /dev/null +++ b/src/test/java/com/finance/system/repository/SysWebhookEventRepositoryTest.java @@ -0,0 +1,31 @@ +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 new file mode 100644 index 0000000..401924a --- /dev/null +++ b/src/test/java/com/finance/system/security/PermissionEnforcementTest.java @@ -0,0 +1,57 @@ +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 new file mode 100644 index 0000000..c04c60f --- /dev/null +++ b/src/test/java/com/finance/system/service/IntegrationConfigCryptoTest.java @@ -0,0 +1,36 @@ +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 new file mode 100644 index 0000000..13bb653 --- /dev/null +++ b/src/test/java/com/finance/system/service/IntegrationConfigReaderTest.java @@ -0,0 +1,85 @@ +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 new file mode 100644 index 0000000..f803191 --- /dev/null +++ b/src/test/java/com/finance/system/service/IntegrationConfigServiceTest.java @@ -0,0 +1,125 @@ +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 new file mode 100644 index 0000000..6faf5c3 --- /dev/null +++ b/src/test/java/com/finance/system/service/RoleServiceTest.java @@ -0,0 +1,321 @@ +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 new file mode 100644 index 0000000..07dc0bf --- /dev/null +++ b/src/test/java/com/finance/system/service/impl/ApprovalSecurityTest.java @@ -0,0 +1,284 @@ +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 new file mode 100644 index 0000000..2303d51 --- /dev/null +++ b/src/test/java/com/finance/system/service/impl/DashboardServiceTest.java @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000..26ad48e --- /dev/null +++ b/src/test/java/com/finance/system/service/impl/ReimApplicationFeishuSubmissionTest.java @@ -0,0 +1,137 @@ +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 new file mode 100644 index 0000000..7f76433 --- /dev/null +++ b/src/test/java/com/finance/system/service/impl/ReimPaymentServiceIdempotencyTest.java @@ -0,0 +1,104 @@ +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(); + } +}