diff --git a/pom.xml b/pom.xml index eaf8e51..1755489 100644 --- a/pom.xml +++ b/pom.xml @@ -112,6 +112,12 @@ jackson-datatype-jsr310 + + org.springframework.boot + spring-boot-starter-test + test + + diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java new file mode 100644 index 0000000..780e2d5 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java @@ -0,0 +1,63 @@ +package com.finance.system.adapter.feishu; + +import com.fasterxml.jackson.databind.JsonNode; +import com.finance.system.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.*; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; + +/** One-shot adapter for the legacy approval attachment upload contract. */ +@Slf4j +@Component +@RequiredArgsConstructor +public class FeishuApprovalFileClient { + static final String UPLOAD_URL = "https://www.feishu.cn/approval/openapi/v2/file/upload"; + private final FeishuAuthService auth; + private final RestTemplate http; + + public String upload(String fileName, String contentType, byte[] content) { + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(auth.getTenantAccessToken()); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + MultiValueMap parts = new LinkedMultiValueMap<>(); + parts.add("name", fileName); + parts.add("type", "attachment"); + HttpHeaders fileHeaders = new HttpHeaders(); + if (StringUtils.hasText(contentType)) { + try { fileHeaders.setContentType(MediaType.parseMediaType(contentType)); } + catch (Exception ignored) { fileHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); } + } else fileHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + ByteArrayResource resource = new ByteArrayResource(content) { + @Override public String getFilename() { return fileName; } + }; + parts.add("content", new HttpEntity<>(resource, fileHeaders)); + try { + ResponseEntity response = http.exchange(UPLOAD_URL, HttpMethod.POST, + new HttpEntity<>(parts, headers), JsonNode.class); + JsonNode body = response.getBody(); + if (body == null || !body.path("code").isIntegralNumber() || body.path("code").asInt() != 0) + throw new BusinessException("飞书拒绝上传附件,请检查文件或应用权限", 502); + JsonNode code = body.path("data").path("code"); + if (!code.isTextual() || !StringUtils.hasText(code.asText()) || code.asText().length() > 500) + throw new BusinessException("飞书附件上传响应无效,结果可能未知,请勿自动重试", 502); + return code.asText(); + } catch (BusinessException e) { throw e; + } catch (RestClientResponseException e) { + log.warn("Feishu attachment upload rejected: httpStatus={}", e.getRawStatusCode()); + throw new BusinessException("飞书附件上传失败,结果可能未知,请勿自动重试", 502); + } catch (Exception e) { + log.warn("Feishu attachment upload outcome unknown", e); + throw new BusinessException("飞书附件上传结果未知,请勿自动重试", 502); + } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java index ddbb872..b807bb4 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java @@ -1,82 +1,354 @@ 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 com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.finance.system.dto.ReimbursementFormField; +import com.finance.system.entity.*; +import com.finance.system.exception.BusinessException; +import com.finance.system.util.Sha256; +import org.springframework.util.StringUtils; import java.math.BigDecimal; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; +import java.nio.charset.StandardCharsets; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.*; -/** - * 飞书审批表单构建器 - * 将系统报销数据转换为飞书审批实例的表单数据 - */ -public class FeishuApprovalFormBuilder { +/** Builds approval-v4 form data exclusively from immutable application snapshots. */ +public final class FeishuApprovalFormBuilder { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final int MAX_JSON_BYTES = 1000000; + private FeishuApprovalFormBuilder() { } - /** - * 构建审批表单数据 - */ - public static Map buildForm(ReimApplication app, SysUser applicant, - SysDepartment department, SysExpenseType expenseType, - List items) { - Map form = new LinkedHashMap<>(); - - // 基本字段 - 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 = ReimbursementCanonicalizer.orderedItems(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; + public static String buildFormJson(ReimApplication app) { + if (!StringUtils.hasText(app.getFeishuFormFingerprint()) || !StringUtils.hasText(app.getFeishuFormSchema())) + throw new BusinessException("报销申请缺少已固定的飞书表单快照,禁止创建远程审批", 409); + if (!app.getFeishuFormFingerprint().equals(Sha256.hex(app.getFeishuFormSchema()))) + throw new BusinessException("报销申请的飞书表单快照校验失败", 409); + if (!StringUtils.hasText(app.getFeishuFormDisplayValues())) + throw new BusinessException("报销申请缺少不可变的飞书展示值快照", 409); + try { + requireSize(app.getFeishuFormSchema(), "飞书表单快照过大"); + requireSize(app.getFeishuFormValues(), "飞书自定义表单值过大"); + requireSize(app.getFeishuFormDisplayValues(), "飞书展示值快照过大"); + List fields = JSON.readValue(app.getFeishuFormSchema(), + new TypeReference>() { }); + Map custom = StringUtils.hasText(app.getFeishuFormValues()) + ? JSON.readValue(app.getFeishuFormValues(), new TypeReference>() { }) + : Collections.emptyMap(); + Map display = JSON.readValue(app.getFeishuFormDisplayValues(), + new TypeReference>() { }); + validateDisplaySnapshot(fields, display); + validateTotals(fields, display, app.getTotalAmount()); + List> controls = new ArrayList<>(); + appendControls(controls, fields, custom, display); + String result = JSON.writeValueAsString(controls); + requireSize(result, "飞书审批表单过大"); + return result; + } catch (BusinessException e) { throw e; } + catch (Exception e) { throw new BusinessException("报销申请的飞书表单快照无效", 409); } } - /** - * 构建飞书审批表单(用于创建审批实例的API请求) - */ - public static String buildFormJson(Map formData) { - StringBuilder json = new StringBuilder("{"); - boolean first = true; - for (Map.Entry entry : formData.entrySet()) { - if (!first) { - json.append(","); + /** Compatibility overload; mutable master data and line entities are deliberately ignored. */ + public static String buildFormJson(ReimApplication app, SysUser applicant, SysDepartment department, + SysExpenseType expenseType, List items) { + return buildFormJson(app); + } + + private static void appendControls(List> out, List fields, + Map custom, Map display) { + for (ReimbursementFormField field : fields) { + boolean bound = !"CUSTOM".equals(field.getBinding()); + if ((field.isReadOnly() && !"CONTACT".equals(field.getType()) && !"DEPARTMENT".equals(field.getType()) + && !"FORMULA".equals(field.getType())) || "DISPLAY".equals(field.getType()) + || "text".equalsIgnoreCase(field.getProviderType())) continue; + Object value = bound ? display.get(field.getValueKey()) : custom.get(field.getValueKey()); + if (isEmpty(value)) { + if (field.isRequired() || "CONTACT".equals(field.getType()) || "DEPARTMENT".equals(field.getType())) + throw new BusinessException("飞书必填表单字段缺少快照值: " + field.getLabel(), 409); + continue; } - json.append("\"") - .append(escapeJson(entry.getKey())) - .append("\":\"") - .append(escapeJson(entry.getValue() != null ? entry.getValue() : "")) - .append("\""); - first = false; + requireIdentity(field); + if ("CONTACT".equals(field.getType())) { + out.add(contactControl(field, value)); + continue; + } + if ("DEPARTMENT".equals(field.getType())) { + out.add(departmentControl(field, value)); + continue; + } + if ("EXPENSE_ITEMS".equals(field.getBinding())) value = expenseRows(field, value, custom); + else if (bound) validateProviderSemantic(field, value); + else value = providerValue(field, value); + Map control = new LinkedHashMap<>(); + control.put("id", field.getId()); control.put("type", field.getProviderType()); control.put("value", value); + if ("amount".equals(normalizedProviderType(field))) { + control.put("currency", currencyCode(field, custom.get("__currency__" + field.getValueKey()), 0)); + } + out.add(control); } - 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"); + private static List>> expenseRows(ReimbursementFormField parent, Object snapshot, Map custom) { + if (!(snapshot instanceof List)) throw new BusinessException("费用明细展示值快照无效", 409); + List>> result = new ArrayList<>(); + for (Object rowValue : (List)snapshot) { + if (!(rowValue instanceof Map)) throw new BusinessException("费用明细展示值快照无效", 409); + Map source = (Map)rowValue; List> row = new ArrayList<>(); + for (ReimbursementFormField child : parent.getChildren() == null + ? Collections.emptyList() : parent.getChildren()) { + if (child.isReadOnly() || "DISPLAY".equals(child.getType())) continue; + Object value = source.get(child.getValueKey()); + if (isEmpty(value)) { + if (child.isRequired()) throw new BusinessException("费用明细必填子控件缺少快照值: " + child.getLabel(), 409); + continue; + } + requireIdentity(child); validateProviderSemantic(child, value); + Map control = new LinkedHashMap<>(); + control.put("id", child.getId()); control.put("type", child.getProviderType()); + control.put("value", providerSubmissionValue(child, value)); + if ("amount".equals(normalizedProviderType(child))) { + control.put("currency", currencyCode(child, custom.get("__currency__" + child.getValueKey()), result.size())); + } + row.add(control); + } + if (!row.isEmpty()) result.add(row); + } + return result; } + + private static void validateDisplaySnapshot(List fields, Map display) { + if (fields == null || display == null) throw new BusinessException("飞书展示值快照无效", 409); + Map allowed = new HashMap<>(); + for (ReimbursementFormField field : fields) if (!"CUSTOM".equals(field.getBinding())) allowed.put(field.getValueKey(), field); + for (String key : display.keySet()) if (!allowed.containsKey(key)) + throw new BusinessException("飞书展示值快照包含未知字段", 409); + for (ReimbursementFormField field : allowed.values()) { + Object value = display.get(field.getValueKey()); + if ((field.isRequired() && !field.isReadOnly() || "CONTACT".equals(field.getType()) + || "DEPARTMENT".equals(field.getType())) && isEmpty(value)) + throw new BusinessException("飞书必填绑定字段缺少快照值: " + field.getLabel(), 409); + if ("EXPENSE_ITEMS".equals(field.getBinding()) && value != null) validateExpenseSnapshot(field, value); + else if (value != null) validateProviderSemantic(field, value); + } + } + + private static void validateExpenseSnapshot(ReimbursementFormField parent, Object value) { + if (!(value instanceof List) || ((List)value).size() > 500) + throw new BusinessException("费用明细展示值快照无效", 409); + Map allowed = new HashMap<>(); + if (parent.getChildren() != null) for (ReimbursementFormField child : parent.getChildren()) + if (!"CUSTOM".equals(child.getBinding())) allowed.put(child.getValueKey(), child); + for (Object rowValue : (List)value) { + if (!(rowValue instanceof Map)) throw new BusinessException("费用明细展示值快照无效", 409); + Map row = (Map)rowValue; + for (Object key : row.keySet()) if (!(key instanceof String) || !allowed.containsKey(key)) + throw new BusinessException("费用明细展示值快照包含未知字段", 409); + for (ReimbursementFormField child : allowed.values()) { + Object childValue = row.get(child.getValueKey()); + if (child.isRequired() && !child.isReadOnly() && isEmpty(childValue)) + throw new BusinessException("费用明细必填子控件缺少快照值: " + child.getLabel(), 409); + if (childValue != null) validateProviderSemantic(child, childValue); + } + } + } + + private static Object providerValue(ReimbursementFormField field, Object value) { + String type = normalizedProviderType(field); + if ("input".equals(type) || "textarea".equals(type)) return String.valueOf(value); + if ("number".equals(type) || "amount".equals(type)) { + try { return new BigDecimal(String.valueOf(value)).stripTrailingZeros(); } + catch (Exception e) { throw invalid(field); } + } + if ("date".equals(type)) { + try { return LocalDate.parse(String.valueOf(value)).atStartOfDay(ZoneId.of("Asia/Shanghai")) + .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); } + catch (Exception e) { throw invalid(field); } + } + if ("radio".equals(type) || "radiov2".equals(type)) return providerOption(field, String.valueOf(value)); + if ("checkbox".equals(type) || "checkboxv2".equals(type)) { + if (!(value instanceof Collection)) throw invalid(field); + List converted = new ArrayList<>(); + for (Object item : (Collection)value) converted.add(providerOption(field, String.valueOf(item))); + return converted; + } + return value; + } + + private static void validateProviderSemantic(ReimbursementFormField field, Object value) { + String type = normalizedProviderType(field); + if ("contact".equals(type)) { + validateContactSnapshot(field, value); + } else if ("department".equals(type)) { + validateDepartmentSnapshot(field, value); + } else if ("number".equals(type) || "amount".equals(type) || "formula".equals(type)) { + if (!(value instanceof Number)) throw invalid(field); + try { new BigDecimal(String.valueOf(value)); } + catch (NumberFormatException e) { throw invalid(field); } + } else if ("attachmentv2".equals(type)) { + attachmentCodes(field, value); + } else if ("date".equals(type)) { + if (!(value instanceof String)) throw invalid(field); + try { + OffsetDateTime date = OffsetDateTime.parse((String)value, DateTimeFormatter.ISO_OFFSET_DATE_TIME); + if (!date.getOffset().equals(ZoneOffset.ofHours(8)) || !date.toLocalTime().equals(LocalTime.MIDNIGHT)) + throw invalid(field); + } + catch (Exception e) { throw invalid(field); } + } else if ("radio".equals(type) || "radiov2".equals(type)) { + if (!(value instanceof String) || !optionValues(field).contains(value)) throw invalid(field); + } else if ("checkbox".equals(type) || "checkboxv2".equals(type)) { + if (!(value instanceof Collection) || ((Collection)value).size() > 500) throw invalid(field); + for (Object item : (Collection)value) if (!(item instanceof String) || !optionValues(field).contains(item)) throw invalid(field); + } else if (!(value instanceof String)) throw invalid(field); + else { + int max = field.getMaxLength() == null ? 5000 : Math.min(field.getMaxLength(), 20000); + if (((String)value).length() > max) throw invalid(field); + } + } + + private static Set optionValues(ReimbursementFormField field) { + Set values = new HashSet<>(); + if (field.getOptions() != null) for (ReimbursementFormField.Option option : field.getOptions()) values.add(option.getValue()); + return values; + } + + private static Object providerSubmissionValue(ReimbursementFormField field, Object value) { + if ("attachmentv2".equals(normalizedProviderType(field))) return attachmentCodes(field, value); + return value; + } + + private static List attachmentCodes(ReimbursementFormField field, Object value) { + if (!(value instanceof List) || ((List)value).size() > 50) throw invalid(field); + List codes = new ArrayList<>(); + Set unique = new HashSet<>(); + for (Object item : (List)value) { + if (!(item instanceof Map)) throw invalid(field); + Map map = (Map)item; + if (map.size() != 3 || !map.keySet().containsAll(Arrays.asList( + "attachment_id", "provider_code", "display_name"))) throw invalid(field); + Object id = map.get("attachment_id"), code = map.get("provider_code"), name = map.get("display_name"); + if (!(id instanceof Number) || !(name instanceof String) || !StringUtils.hasText((String)name) + || ((String)name).length() > 500 || !(code instanceof String) || !StringUtils.hasText((String)code) + || ((String)code).length() > 500 || !unique.add((String)code)) throw invalid(field); + codes.add((String)code); + } + return codes; + } + + private static void validateTotals(List fields, Map display, + BigDecimal applicationTotal) { + BigDecimal formula = null, rows = BigDecimal.ZERO; + boolean formulaSeen = false, detailsSeen = false; + for (ReimbursementFormField field : fields) { + if ("TOTAL_AMOUNT".equals(field.getBinding())) { + formulaSeen = true; + formula = decimal(display.get(field.getValueKey()), field); + } + if (!"EXPENSE_ITEMS".equals(field.getBinding())) continue; + detailsSeen = true; + Object value = display.get(field.getValueKey()); + if (!(value instanceof List)) throw invalid(field); + ReimbursementFormField amount = null; + for (ReimbursementFormField child : field.getChildren()) + if ("EXPENSE_AMOUNT".equals(child.getBinding())) amount = child; + if (amount == null) throw invalid(field); + for (Object row : (List)value) { + if (!(row instanceof Map)) throw invalid(field); + rows = rows.add(decimal(((Map)row).get(amount.getValueKey()), amount)); + } + } + if (applicationTotal == null || (formulaSeen && (formula == null || formula.compareTo(applicationTotal) != 0)) + || (detailsSeen && rows.compareTo(applicationTotal) != 0)) + throw new BusinessException("飞书总金额、申请总额与明细合计不一致", 409); + } + + private static BigDecimal decimal(Object value, ReimbursementFormField field) { + if (!(value instanceof Number)) throw invalid(field); + try { return new BigDecimal(String.valueOf(value)); } + catch (NumberFormatException e) { throw invalid(field); } + } + private static Map contactControl(ReimbursementFormField field, Object snapshot) { + Map contact = validateContactSnapshot(field, snapshot); + Map control = new LinkedHashMap<>(); + control.put("id", field.getId()); + control.put("type", field.getProviderType()); + Object userId = contact.get("user_id"); + Object openId = contact.get("open_id"); + if (userId != null) control.put("value", Collections.singletonList(userId)); + if (openId != null) control.put("open_ids", Collections.singletonList(openId)); + return control; + } + private static Map validateContactSnapshot(ReimbursementFormField field, Object value) { + if (!(value instanceof Map) || ((Map)value).size() > 3) throw invalid(field); + Map contact = (Map)value; + for (Object key : contact.keySet()) if (!(key instanceof String) + || !Arrays.asList("user_id", "open_id", "display_label").contains(key)) throw invalid(field); + String userId = contactText(field, contact.get("user_id"), 100, false); + String openId = contactText(field, contact.get("open_id"), 100, false); + contactText(field, contact.get("display_label"), 500, true); + if (!StringUtils.hasText(userId) && !StringUtils.hasText(openId)) + throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 409); + return contact; + } + private static Map departmentControl(ReimbursementFormField field, Object snapshot) { + Map department = validateDepartmentSnapshot(field, snapshot); + List> providerValue = new ArrayList<>(); + for (Object id : (List)department.get("open_department_ids")) { + Map item = new LinkedHashMap<>(); + item.put("open_id", id); + providerValue.add(item); + } + Map control = new LinkedHashMap<>(); + control.put("id", field.getId()); + control.put("type", field.getProviderType()); + control.put("value", providerValue); + return control; + } + private static Map validateDepartmentSnapshot(ReimbursementFormField field, Object value) { + if (!(value instanceof Map) || ((Map)value).size() != 2) throw invalid(field); + Map department = (Map)value; + for (Object key : department.keySet()) if (!(key instanceof String) + || !Arrays.asList("open_department_ids", "display_label").contains(key)) throw invalid(field); + Object idsValue = department.get("open_department_ids"); + if (!(idsValue instanceof List) || ((List)idsValue).isEmpty() || ((List)idsValue).size() > 10) + throw invalid(field); + Set unique = new HashSet<>(); + for (Object id : (List)idsValue) { + if (!(id instanceof String) || !StringUtils.hasText((String)id) || ((String)id).length() > 64 + || !id.equals(((String)id).trim()) || !unique.add((String)id)) throw invalid(field); + } + contactText(field, department.get("display_label"), 500, true); + return department; + } + private static String contactText(ReimbursementFormField field, Object value, int max, boolean required) { + if (value == null && !required) return null; + if (!(value instanceof String) || !StringUtils.hasText((String)value) + || ((String)value).length() > max || !value.equals(((String)value).trim())) throw invalid(field); + return (String)value; + } + private static String providerOption(ReimbursementFormField field, String value) { + if (field.getOptions() != null) for (ReimbursementFormField.Option option : field.getOptions()) + if (value.equals(option.getLabel()) || value.equals(option.getValue())) return option.getValue(); + throw invalid(field); + } + private static String currencyCode(ReimbursementFormField field, Object supplied, int index) { + String fallback = StringUtils.hasText(field.getCurrency()) ? field.getCurrency() : "CNY"; + String selected = fallback; + if (supplied instanceof String && StringUtils.hasText((String) supplied)) selected = ((String) supplied).trim().toUpperCase(Locale.ROOT); + else if (supplied instanceof List && index >= 0 && index < ((List) supplied).size() && ((List) supplied).get(index) instanceof String) + selected = ((String) ((List) supplied).get(index)).trim().toUpperCase(Locale.ROOT); + if (field.getOptions() != null && !field.getOptions().isEmpty()) { + for (ReimbursementFormField.Option option : field.getOptions()) + if (selected.equals(option.getValue())) return selected; + throw invalid(field); + } + if (!fallback.equals(selected)) throw invalid(field); + return selected; + } + private static String normalizedProviderType(ReimbursementFormField field) { return field.getProviderType() == null ? "" : field.getProviderType().replace("_", "").toLowerCase(Locale.ROOT); } + private static boolean isEmpty(Object value) { return value == null || (value instanceof String && !StringUtils.hasText((String)value)) || (value instanceof Collection && ((Collection)value).isEmpty()); } + private static void requireIdentity(ReimbursementFormField field) { if (!StringUtils.hasText(field.getId()) || !StringUtils.hasText(field.getProviderType())) throw invalid(field); } + private static BusinessException invalid(ReimbursementFormField field) { return new BusinessException("飞书表单快照值无效: " + field.getLabel(), 409); } + private static void requireSize(String value, String message) { if (value != null && value.getBytes(StandardCharsets.UTF_8).length > MAX_JSON_BYTES) throw new BusinessException(message, 409); } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java index 42f5b77..d9e9309 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalResponse.java @@ -1,5 +1,6 @@ package com.finance.system.adapter.feishu; +import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; @@ -13,7 +14,7 @@ import java.util.List; @NoArgsConstructor public class FeishuApprovalResponse { - private int code; + private Integer code; private String msg; private Data data; @@ -22,10 +23,12 @@ public class FeishuApprovalResponse { public static class Data { /** 审批实例编码 */ @JsonProperty("instance_code") + @JsonAlias({"instance_id", "instanceCode"}) private String instanceCode; /** 审批定义编码 */ @JsonProperty("approval_code") + @JsonAlias("approvalCode") private String approvalCode; /** 审批状态 PENDING/APPROVED/REJECTED/CANCELED/TERMINATED */ @@ -41,6 +44,10 @@ public class FeishuApprovalResponse { /** 审批时间线 */ private List timeline; + /** v4 审批任务列表,作为审批进度的结构化来源。 */ + @JsonProperty("task_list") + private List taskList; + /** 审批定义名称 */ @JsonProperty("approval_name") private String approvalName; @@ -49,16 +56,56 @@ public class FeishuApprovalResponse { private Object form; } + /** v4 审批实例中的任务。用户标识保持为 ID,不推断用户姓名。 */ + @lombok.Data + @NoArgsConstructor + public static class ApprovalTask { + @JsonProperty("id") + @JsonAlias({"task_id", "taskId"}) + private String taskId; + + @JsonProperty("user_id") + private String userId; + + @JsonProperty("open_id") + private String openId; + + private String status; + + @JsonProperty("node_id") + private String nodeId; + + @JsonProperty("node_name") + private String nodeName; + + @JsonProperty("type") + @JsonAlias({"node_type", "nodeType"}) + private String nodeType; + + @JsonProperty("start_time") + private String startTime; + + @JsonProperty("end_time") + private String endTime; + } + /** * 审批节点定义 */ @lombok.Data @NoArgsConstructor public static class ApprovalNode { + @JsonProperty("node_id") + @JsonAlias({"id", "nodeId"}) private String id; + + @JsonProperty("node_name") + @JsonAlias({"name", "nodeName"}) private String name; /** AND/OR */ + @JsonProperty("node_type") + @JsonAlias({"type", "nodeType"}) private String type; /** 审批人列表 */ @@ -124,6 +171,32 @@ public class FeishuApprovalResponse { /** 审批时间 */ @JsonProperty("action_time") + @JsonAlias({"create_time", "actionTime"}) private String actionTime; + + /** v4 时间线返回用户标识,不将标识伪装为审批人姓名。 */ + @JsonProperty("user_id") + private String userId; + + @JsonProperty("open_id") + private String openId; + + @JsonProperty("task_id") + private String taskId; + + @JsonProperty("node_id") + private String nodeId; + + @JsonProperty("node_type") + private String nodeType; + + @JsonProperty("cc_id") + private String ccId; + + @JsonProperty("user_id_list") + private List userIdList; + + @JsonProperty("open_id_list") + private List openIdList; } -} \ No newline at end of file +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java index c219de1..49c05b3 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java @@ -19,7 +19,9 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestClientResponseException; import org.springframework.util.StringUtils; +import org.springframework.web.util.UriComponentsBuilder; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.*; @@ -37,9 +39,6 @@ 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; @@ -86,52 +85,52 @@ public class FeishuApprovalService { * 包括审批流程的所有节点、审批人配置、表单定义 */ 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; + return JSON.treeToValue(fetchApprovalDefinitionResponse(), FeishuApprovalResponse.class); + } catch (BusinessException e) { + throw e; } catch (Exception e) { - log.error("获取飞书审批定义失败", e); - throw new BusinessException("获取审批节点信息失败,请检查飞书权限配置"); + log.warn("飞书审批定义响应解析失败: httpStatus=200, providerCode=0, requestId=unknown"); + throw new BusinessException("飞书审批定义响应格式无效", 502); } } /** Raw transport response for server-side normalization only. Never expose this from a controller. */ public JsonNode fetchApprovalDefinitionJson() { - String token = feishuAuthService.getTenantAccessToken(); + return fetchApprovalDefinitionResponse(); + } + + private JsonNode fetchApprovalDefinitionResponse() { + String code = requiredApprovalCode(); + URI uri = UriComponentsBuilder.fromHttpUrl(FEISHU_OPEN_API) + .pathSegment("approval", "v4", "approvals", code) + .queryParam("locale", "zh-CN") + .queryParam("user_id_type", "open_id") + .build().encode().toUri(); HttpHeaders headers = new HttpHeaders(); - headers.setBearerAuth(token); - headers.setContentType(MediaType.APPLICATION_JSON); - Map body = Collections.singletonMap("approval_code", approvalCode()); + headers.setBearerAuth(feishuAuthService.getTenantAccessToken()); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); try { ResponseEntity response = restTemplate.exchange( - FEISHU_OPEN_API + "/approval/openapi/v2/approval/get", HttpMethod.POST, - new HttpEntity<>(body, headers), JsonNode.class); + uri, HttpMethod.GET, new HttpEntity(headers), JsonNode.class); JsonNode value = response.getBody(); - if (value == null || value.path("code").asInt(-1) != 0) { - throw new BusinessException("飞书审批定义同步失败", 502); + Integer providerCode = providerCode(value); + if (value == null || !Integer.valueOf(0).equals(providerCode)) { + String requestId = requestId(response.getHeaders(), value); + logDefinitionFailure(response.getStatusCodeValue(), providerCode, requestId); + throw definitionFailure(response.getStatusCodeValue(), providerCode); } return value; } catch (BusinessException e) { throw e; + } catch (RestClientResponseException e) { + JsonNode error = parseJson(e.getResponseBodyAsString(StandardCharsets.UTF_8)); + Integer providerCode = providerCode(error); + String requestId = requestId(e.getResponseHeaders(), error); + logDefinitionFailure(e.getRawStatusCode(), providerCode, requestId); + throw definitionFailure(e.getRawStatusCode(), providerCode); } catch (Exception e) { - log.warn("飞书审批定义请求失败: {}", e.getClass().getSimpleName()); + logDefinitionFailure(null, null, null); throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502); } } @@ -140,6 +139,51 @@ public class FeishuApprovalService { return approvalCode(); } + /** + * Subscribe this app to approval events for the configured definition code. + * Feishu returns 1390007 when the subscription already exists — treated as success. + * + * @return true when newly subscribed; false when already subscribed + */ + public boolean subscribeApprovalEvents() { + String code = requiredApprovalCode(); + URI uri = UriComponentsBuilder.fromHttpUrl(FEISHU_OPEN_API) + .pathSegment("approval", "v4", "approvals", code, "subscribe") + .build().encode().toUri(); + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(feishuAuthService.getTenantAccessToken()); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + try { + ResponseEntity response = restTemplate.exchange( + uri, HttpMethod.POST, new HttpEntity(headers), JsonNode.class); + JsonNode body = response.getBody(); + Integer providerCode = providerCode(body); + if (Integer.valueOf(0).equals(providerCode)) return true; + if (Integer.valueOf(1390007).equals(providerCode)) return false; + String requestId = requestId(response.getHeaders(), body); + log.warn("飞书审批事件订阅失败: httpStatus={}, providerCode={}, requestId={}", + response.getStatusCodeValue(), + providerCode == null ? "unknown" : providerCode, + StringUtils.hasText(requestId) ? requestId : "unknown"); + throw new BusinessException("飞书审批事件订阅失败,请检查应用权限与事件订阅配置", 502); + } catch (BusinessException e) { + throw e; + } catch (RestClientResponseException e) { + JsonNode error = parseJson(e.getResponseBodyAsString(StandardCharsets.UTF_8)); + Integer providerCode = providerCode(error); + if (Integer.valueOf(1390007).equals(providerCode)) return false; + String requestId = requestId(e.getResponseHeaders(), error); + log.warn("飞书审批事件订阅失败: httpStatus={}, providerCode={}, requestId={}", + e.getRawStatusCode(), + providerCode == null ? "unknown" : providerCode, + StringUtils.hasText(requestId) ? requestId : "unknown"); + throw new BusinessException("飞书审批事件订阅失败,请检查应用权限与事件订阅配置", 502); + } catch (Exception e) { + log.warn("飞书审批事件订阅失败: httpStatus=unknown, providerCode=unknown, requestId=unknown"); + throw new BusinessException("飞书审批事件订阅失败,请稍后重试", 502); + } + } + /** * 获取审批节点列表(用于前端展示审批流程) */ @@ -162,6 +206,9 @@ public class FeishuApprovalService { /** Built in Phase A while the application row is locked, then persisted verbatim. */ public String buildCreatePayload(Long applicationId, String requestUuid, String intendedApprovalCode) { + if (applicationId == null || !StringUtils.hasText(requestUuid) || !StringUtils.hasText(intendedApprovalCode)) + throw new BusinessException("飞书审批创建参数无效", 400); + String normalizedApprovalCode = intendedApprovalCode.trim(); ReimApplication application = reimApplicationRepository.findById(applicationId) .orElseThrow(() -> new BusinessException("报销申请不存在,无法创建飞书审批", 400)); SysUser applicant = application.getApplicantId() == null ? null @@ -169,17 +216,15 @@ public class FeishuApprovalService { if (applicant == null || (!StringUtils.hasText(applicant.getFeishuUserId()) && !StringUtils.hasText(applicant.getFeishuOpenId()))) throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 400); - SysDepartment department = application.getDepartmentId() == null ? null - : sysDepartmentRepository.findById(application.getDepartmentId()).orElse(null); - SysExpenseType expenseType = application.getExpenseTypeId() == null ? null - : sysExpenseTypeRepository.findById(application.getExpenseTypeId()).orElse(null); - List items = reimExpenseItemRepository.findByApplicationId(applicationId); - String formJson = FeishuApprovalFormBuilder.buildFormJson( - FeishuApprovalFormBuilder.buildForm(application, applicant, department, expenseType, items)); + String formJson = FeishuApprovalFormBuilder.buildFormJson(application); Map body = new LinkedHashMap<>(); - body.put("approval_code", intendedApprovalCode); - body.put("user_id", applicant.getFeishuUserId() == null ? "" : applicant.getFeishuUserId()); - body.put("open_id", applicant.getFeishuOpenId() == null ? "" : applicant.getFeishuOpenId()); + body.put("approval_code", normalizedApprovalCode); + if (StringUtils.hasText(applicant.getFeishuUserId())) { + body.put("user_id", applicant.getFeishuUserId().trim()); + } + if (StringUtils.hasText(applicant.getFeishuOpenId())) { + body.put("open_id", applicant.getFeishuOpenId().trim()); + } body.put("form", formJson); body.put("uuid", requestUuid); try { String json = JSON.writeValueAsString(body); @@ -197,33 +242,51 @@ public class FeishuApprovalService { try { body = JSON.readValue(persistedPayload, new TypeReference>() {}); } catch (Exception e) { throw new BusinessException("飞书审批创建载荷无效", 500); } if (!Objects.equals(requestUuid, body.get("uuid"))) throw new BusinessException("飞书审批创建载荷不匹配", 500); + Object approvalCode = body.get("approval_code"); + if (!(approvalCode instanceof String) || !StringUtils.hasText((String) approvalCode)) + throw new BusinessException("飞书审批创建载荷缺少审批编码", 500); HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(feishuAuthService.getTenantAccessToken()); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("X-Request-ID", requestUuid); + URI uri = UriComponentsBuilder.fromHttpUrl(FEISHU_OPEN_API) + .pathSegment("approval", "v4", "instances").build().encode().toUri(); try { - ResponseEntity response = restTemplate.exchange( - FEISHU_OPEN_API + "/approval/openapi/v2/instance/create", HttpMethod.POST, - new HttpEntity<>(body, headers), FeishuApprovalResponse.class); - FeishuApprovalResponse value = response.getBody(); - if (value == null) throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试"); - if (value.getCode() != 0) throw new BusinessException("创建飞书审批失败: " + value.getMsg(), 502); - if (value.getData() == null || !StringUtils.hasText(value.getData().getInstanceCode())) + ResponseEntity response = restTemplate.exchange( + uri, HttpMethod.POST, + new HttpEntity<>(body, headers), JsonNode.class); + JsonNode value = response.getBody(); + Integer code = providerCode(value); + String responseRequestId = requestId(response.getHeaders(), value); + if (value == null || code == null) { + logProviderFailure("create", response.getStatusCodeValue(), code, responseRequestId); throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试"); - String instance = value.getData().getInstanceCode().trim(); - if (instance.length() > 200) + } + if (!Integer.valueOf(0).equals(code)) { + logProviderFailure("create", response.getStatusCodeValue(), code, responseRequestId); + throw classifyCreateFailure(response.getStatusCodeValue(), code, null); + } + JsonNode data = value.path("data"); + String instance = firstJsonText(data, "instance_code", "instance_id"); + if (!StringUtils.hasText(instance)) { + logProviderFailure("create", response.getStatusCodeValue(), code, responseRequestId); + throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试"); + } + instance = instance.trim(); + if (instance.length() > 200) { + logProviderFailure("create", response.getStatusCodeValue(), code, responseRequestId); throw new FeishuCreateOutcomeUnknownException("飞书已响应创建但实例标识无效,禁止修改原申请"); + } return instance; } catch (FeishuCreateOutcomeUnknownException e) { throw e; } catch (BusinessException e) { throw e; } catch (RestClientResponseException e) { int status = e.getRawStatusCode(); - if (status == 408 || status == 409 || status == 425 || status == 429 || status >= 500) - throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e); - if (status >= 400 && status < 500) - throw new BusinessException("飞书拒绝创建审批实例", 502); - throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e); + JsonNode error = parseJson(e.getResponseBodyAsString(StandardCharsets.UTF_8)); + Integer code = providerCode(error); + logProviderFailure("create", status, code, requestId(e.getResponseHeaders(), error)); + throw classifyCreateFailure(status, code, e); } catch (Exception e) { - log.warn("飞书审批远程创建失败: {}", e.getClass().getSimpleName()); + logProviderFailure("create", null, null, null); throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e); } } @@ -235,29 +298,46 @@ public class FeishuApprovalService { * 包含审批进度、各节点状态、审批意见 */ public FeishuApprovalResponse getApprovalInstanceDetail(String instanceCode) { - String token = feishuAuthService.getTenantAccessToken(); - String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/get"; + if (!StringUtils.hasText(instanceCode)) throw new BusinessException("飞书审批实例标识不能为空", 400); + String normalizedInstanceCode = instanceCode.trim(); + URI uri = UriComponentsBuilder.fromHttpUrl(FEISHU_OPEN_API) + .pathSegment("approval", "v4", "instances", normalizedInstanceCode) + .queryParam("locale", "zh-CN") + .queryParam("user_id_type", "open_id") + .build().encode().toUri(); 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); + headers.setBearerAuth(feishuAuthService.getTenantAccessToken()); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); 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()); + ResponseEntity response = restTemplate.exchange( + uri, HttpMethod.GET, new HttpEntity(headers), JsonNode.class); + JsonNode value = response.getBody(); + Integer code = providerCode(value); + if (value == null || !Integer.valueOf(0).equals(code)) { + logProviderFailure("detail", response.getStatusCodeValue(), code, + requestId(response.getHeaders(), value)); + throw new BusinessException("飞书审批实例详情响应无效", 502); } - return resp; + try { + return JSON.treeToValue(value, FeishuApprovalResponse.class); + } catch (Exception e) { + logProviderFailure("detail", response.getStatusCodeValue(), code, + requestId(response.getHeaders(), value)); + throw new BusinessException("飞书审批实例详情响应格式无效", 502); + } + } catch (BusinessException e) { + throw e; + } catch (RestClientResponseException e) { + JsonNode error = parseJson(e.getResponseBodyAsString(StandardCharsets.UTF_8)); + Integer code = providerCode(error); + logProviderFailure("detail", e.getRawStatusCode(), code, + requestId(e.getResponseHeaders(), error)); + throw new BusinessException("获取飞书审批进度失败,请稍后重试", 502); } catch (Exception e) { - log.error("获取审批实例详情失败: instanceCode={}", instanceCode, e); - throw new BusinessException("获取审批进度失败"); + logProviderFailure("detail", null, null, null); + throw new BusinessException("获取飞书审批进度失败,请稍后重试", 502); } } @@ -267,7 +347,11 @@ public class FeishuApprovalService { public List getApprovalTimeline(String instanceCode) { FeishuApprovalResponse detail = getApprovalInstanceDetail(instanceCode); if (detail != null && detail.getData() != null) { - return detail.getData().getTimeline(); + if (detail.getData().getTaskList() != null) { + return taskProgress(detail.getData().getTaskList(), detail.getData().getTimeline()); + } + return detail.getData().getTimeline() == null + ? Collections.emptyList() : detail.getData().getTimeline(); } return Collections.emptyList(); } @@ -513,6 +597,172 @@ public class FeishuApprovalService { return integrationConfigReader == null ? fallback : integrationConfigReader.get("FEISHU", "approvalCode"); } + private String requiredApprovalCode() { + String code = approvalCode(); + if (!StringUtils.hasText(code)) throw new BusinessException("飞书审批编码未配置", 400); + return code.trim(); + } + + private BusinessException classifyCreateFailure(int httpStatus, Integer code, Throwable cause) { + boolean unknown = code == null + || Integer.valueOf(60012).equals(code) + || Integer.valueOf(1395001).equals(code) + || httpStatus == 408 || httpStatus == 409 || httpStatus == 425 || httpStatus == 429 + || httpStatus >= 500; + if (unknown) { + return cause == null + ? new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试") + : new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", cause); + } + if (!Integer.valueOf(0).equals(code) || (httpStatus >= 400 && httpStatus < 500)) { + return new BusinessException("飞书拒绝创建审批实例,请检查申请参数或应用权限", 502); + } + return cause == null + ? new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试") + : new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", cause); + } + + private List taskProgress( + List tasks, + List timeline) { + List progress = new ArrayList<>( + tasks.size() + (timeline == null ? 0 : timeline.size())); + Map taskTemplates = new LinkedHashMap<>(); + Map taskProgress = new LinkedHashMap<>(); + for (FeishuApprovalResponse.ApprovalTask task : tasks) { + if (task == null) continue; + FeishuApprovalResponse.TimelineNode node = taskNode(task); + progress.add(node); + if (StringUtils.hasText(task.getTaskId()) && !taskTemplates.containsKey(task.getTaskId())) { + taskTemplates.put(task.getTaskId(), taskNode(task)); + taskProgress.put(task.getTaskId(), node); + } + } + if (timeline == null) return progress; + + Set mergedTaskEvents = new HashSet<>(); + for (FeishuApprovalResponse.TimelineNode event : timeline) { + if (event == null) continue; + String taskId = event.getTaskId(); + FeishuApprovalResponse.TimelineNode target = StringUtils.hasText(taskId) + ? taskProgress.get(taskId) : null; + boolean commentEvent = "COMMENT".equalsIgnoreCase(event.getType()); + if (target != null && !commentEvent && mergedTaskEvents.add(taskId)) { + mergeTimelineEvent(target, event); + continue; + } + FeishuApprovalResponse.TimelineNode copy = StringUtils.hasText(taskId) + && taskTemplates.containsKey(taskId) + ? copyTimelineNode(taskTemplates.get(taskId)) : new FeishuApprovalResponse.TimelineNode(); + mergeTimelineEvent(copy, event); + progress.add(copy); + } + return progress; + } + + private FeishuApprovalResponse.TimelineNode taskNode(FeishuApprovalResponse.ApprovalTask task) { + FeishuApprovalResponse.TimelineNode node = new FeishuApprovalResponse.TimelineNode(); + node.setType(task.getNodeType()); + node.setNodeId(task.getNodeId()); + node.setNodeType(task.getNodeType()); + node.setNodeName(task.getNodeName()); + node.setStatus(task.getStatus()); + node.setTaskId(task.getTaskId()); + node.setUserId(task.getUserId()); + node.setOpenId(task.getOpenId()); + String endTime = task.getEndTime(); + boolean completed = StringUtils.hasText(endTime) && !"0".equals(endTime.trim()); + node.setActionTime(completed ? endTime : task.getStartTime()); + return node; + } + + private FeishuApprovalResponse.TimelineNode copyTimelineNode(FeishuApprovalResponse.TimelineNode source) { + FeishuApprovalResponse.TimelineNode copy = new FeishuApprovalResponse.TimelineNode(); + mergeTimelineEvent(copy, source); + return copy; + } + + private void mergeTimelineEvent(FeishuApprovalResponse.TimelineNode target, + FeishuApprovalResponse.TimelineNode event) { + if (StringUtils.hasText(event.getType())) target.setType(event.getType()); + if (!StringUtils.hasText(target.getNodeId())) target.setNodeId(event.getNodeId()); + if (!StringUtils.hasText(target.getNodeType())) target.setNodeType(event.getNodeType()); + if (!StringUtils.hasText(target.getNodeName())) target.setNodeName(event.getNodeName()); + if (!StringUtils.hasText(target.getStatus())) target.setStatus(event.getStatus()); + if (StringUtils.hasText(event.getTaskId())) target.setTaskId(event.getTaskId()); + if (StringUtils.hasText(event.getUserId())) target.setUserId(event.getUserId()); + if (StringUtils.hasText(event.getOpenId())) target.setOpenId(event.getOpenId()); + if (event.getUserIdList() != null) target.setUserIdList(new ArrayList<>(event.getUserIdList())); + if (event.getOpenIdList() != null) target.setOpenIdList(new ArrayList<>(event.getOpenIdList())); + if (StringUtils.hasText(event.getCcId())) target.setCcId(event.getCcId()); + if (event.getComment() != null) target.setComment(event.getComment()); + if (StringUtils.hasText(event.getActionTime())) target.setActionTime(event.getActionTime()); + if (event.getApprover() != null) target.setApprover(event.getApprover()); + if (event.getApproverAvatar() != null) target.setApproverAvatar(event.getApproverAvatar()); + } + + private String firstJsonText(JsonNode parent, String... fields) { + if (parent == null || parent.isMissingNode() || parent.isNull()) return null; + for (String field : fields) { + JsonNode value = parent.get(field); + if (value != null && value.isValueNode() && StringUtils.hasText(value.asText())) return value.asText(); + } + return null; + } + + private Integer providerCode(JsonNode body) { + if (body == null || !body.has("code") || !body.get("code").canConvertToInt()) return null; + return body.get("code").intValue(); + } + + private JsonNode parseJson(String body) { + if (!StringUtils.hasText(body)) return null; + try { + return JSON.readTree(body); + } catch (Exception ignored) { + return null; + } + } + + private BusinessException definitionFailure(int httpStatus, Integer providerCode) { + if (Integer.valueOf(1390002).equals(providerCode)) { + return new BusinessException("飞书审批编码无效,请检查审批编码配置", 400); + } + if (httpStatus == 403 || Integer.valueOf(1390009).equals(providerCode)) { + return new BusinessException("无权读取飞书审批定义,请检查应用审批权限", 403); + } + if (httpStatus == 404) { + return new BusinessException("飞书审批接口路由不存在,请检查服务部署版本和接口契约", 502); + } + if (httpStatus == 429 || Integer.valueOf(99991400).equals(providerCode)) { + return new BusinessException("飞书审批接口请求频率过高,请稍后重试", 502); + } + return new BusinessException("飞书拒绝获取审批定义,请稍后重试", 502); + } + + private String requestId(HttpHeaders headers, JsonNode body) { + String value = headers == null ? null : headers.getFirst("X-Request-ID"); + if (!StringUtils.hasText(value) && headers != null) value = headers.getFirst("X-Tt-Logid"); + if (!StringUtils.hasText(value) && body != null) { + JsonNode requestId = body.get("request_id"); + if (requestId != null && requestId.isValueNode()) value = requestId.asText(); + } + if (!StringUtils.hasText(value)) return null; + return value.replace('\r', '_').replace('\n', '_').substring(0, Math.min(value.length(), 200)); + } + + private void logDefinitionFailure(Integer httpStatus, Integer providerCode, String requestId) { + logProviderFailure("definition", httpStatus, providerCode, requestId); + } + + private void logProviderFailure(String operation, Integer httpStatus, Integer providerCode, String requestId) { + log.warn("飞书审批请求失败: operation={}, httpStatus={}, providerCode={}, requestId={}", + operation, + httpStatus == null ? "unknown" : httpStatus, + providerCode == null ? "unknown" : providerCode, + StringUtils.hasText(requestId) ? requestId : "unknown"); + } + private String configValue(String key, String fallback) { if (integrationConfigReader == null) return fallback; String value = integrationConfigReader.get("FEISHU", key); @@ -527,7 +777,10 @@ public class FeishuApprovalService { 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(); + if ("CANCELED".equals(normalized) || "DELETED".equals(normalized) + || "TERMINATED".equals(normalized)) { + normalized = ApprovalStatus.CANCELLED.name(); + } for (ApprovalStatus known : ApprovalStatus.values()) { if (known.name().equals(normalized)) return normalized; } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java index b6ce8c6..e289bc9 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java @@ -8,9 +8,13 @@ import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "feishu") public class FeishuConfig { + /** Master switch for Feishu OAuth / approval / directory token use. */ + private boolean enabled = true; private String appId; private String appSecret; private String redirectUri; + /** Independent switch for Feishu directory sync (defaults on when credentials exist). */ + private boolean syncOrgEnabled = true; /** * Legacy setting retained for configuration compatibility. OAuth no * longer has a local bootstrap exception and always provisions an diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java index dcd8a1f..bd78b3c 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizer.java @@ -1,6 +1,8 @@ package com.finance.system.adapter.feishu; -import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.*; +import com.finance.system.dto.ReimbursementFormField; +import com.finance.system.exception.BusinessException; import com.finance.system.util.Sha256; import lombok.*; import org.springframework.stereotype.Component; @@ -8,187 +10,398 @@ import org.springframework.util.StringUtils; import java.util.*; -/** Converts the known v1/v2 approval-definition envelopes into one stable model. */ +/** Converts the approval-v4 definition into a bounded, sanitized snapshot. */ @Component +@RequiredArgsConstructor public class FeishuDefinitionNormalizer { - private static final int MAX_NODES = 100; - private static final int MAX_APPROVERS = 50; + private static final int MAX_NODES = 100, MAX_APPROVERS = 50; + private static final int MAX_CONTROLS = 200, MAX_DEPTH = 5, MAX_OPTIONS = 500; + private static final Set BINDINGS = new HashSet<>(Arrays.asList( + "application_no", "title", "applicant_name", "department", "expense_type", + "total_amount", "description", "source_doc_no", "expense_items", "reimbursement_date")); + private static final Set APPLICANT_CONTACT_IDS = new HashSet<>(Arrays.asList( + "applicant", "applicant_user", "applicant_name", "applicant_contact", + "reimbursement_applicant")); + private static final Set APPLICANT_DEPARTMENT_IDS = new HashSet<>(Arrays.asList( + "applicant_department", "applicant_department_id", "reimbursement_department", "department")); + private final ObjectMapper json; public NormalizedDefinition normalize(JsonNode response, String configuredApprovalCode) { JsonNode data = response == null ? null : response.path("data"); if (data == null || data.isMissingNode() || data.isNull()) data = response; + String status = displayText(findDeep(data, 0, "status")); + if (StringUtils.hasText(status) && !"ACTIVE".equalsIgnoreCase(status.trim())) + throw new BusinessException("飞书审批定义状态不是 ACTIVE,当前状态: " + bounded(status, 80), 409); JsonNode nodesJson = findNodeArray(data, 0); - if (nodesJson == null || !nodesJson.isArray() || nodesJson.size() == 0) { + if (nodesJson == null || !nodesJson.isArray() || nodesJson.size() == 0) throw new IllegalArgumentException("Feishu approval definition has no usable nodes"); - } String code = displayText(findDeep(data, 0, "approval_code", "approvalCode")); if (!StringUtils.hasText(code)) code = configuredApprovalCode; if (!StringUtils.hasText(code)) throw new IllegalArgumentException("Feishu approval code is missing"); String name = displayText(findDeep(data, 0, "approval_name", "approvalName")); - code = bounded(code, 200); - name = bounded(name, 300); + code = bounded(code, 200); name = bounded(name, 300); - List nodes = new ArrayList<>(); - int order = 1; + List nodes = new ArrayList<>(); int order = 1; for (JsonNode raw : nodesJson) { if (order > MAX_NODES) throw new IllegalArgumentException("too many Feishu approval nodes"); if (!raw.isObject()) continue; String key = firstText(raw, "node_id", "nodeId", "id", "key", "node_key"); if (!StringUtils.hasText(key)) key = "node-" + order; - key = bounded(key, 300); String nodeName = displayText(first(raw, "node_name", "nodeName", "name", "title")); if (!StringUtils.hasText(nodeName)) nodeName = "审批节点 " + order; - nodeName = bounded(nodeName, 300); String rawType = firstText(raw, "node_type", "nodeType", "type"); String mode = firstText(raw, "approval_mode", "approvalMode", "mode"); - if (!StringUtils.hasText(mode) && ("AND".equalsIgnoreCase(rawType) || "OR".equalsIgnoreCase(rawType))) { + if (!StringUtils.hasText(mode) && ("AND".equalsIgnoreCase(rawType) || "OR".equalsIgnoreCase(rawType))) mode = rawType.toUpperCase(Locale.ROOT); - } - List approvers = normalizeApprovers(raw); - boolean dynamic = isDynamicNode(raw, approvers); - if (approvers.isEmpty()) { - approvers.add(new NormalizedApprover("FEISHU", null, - "提交时由飞书解析", true)); + List nodeApprovers = normalizeApprovers(raw); + boolean dynamic = isDynamicNode(raw, nodeApprovers); + if (nodeApprovers.isEmpty()) { + nodeApprovers.add(new NormalizedApprover("FEISHU", null, "提交时由飞书解析", true)); dynamic = true; } - nodes.add(new NormalizedNode(order++, key, nodeName, bounded(rawType, 80), bounded(mode, 80), dynamic, approvers)); + nodes.add(new NormalizedNode(order++, bounded(key, 300), bounded(nodeName, 300), + bounded(rawType, 80), bounded(mode, 80), dynamic, nodeApprovers)); } if (nodes.isEmpty()) throw new IllegalArgumentException("Feishu approval definition has no usable nodes"); - NormalizedDefinition definition = new NormalizedDefinition(code, name, nodes, null); + + JsonNode formNode = first(data, "form"); + if (formNode == null) formNode = findDeep(data, 0, "form"); + List fields = normalizeForm(formNode); + String formSchema; + try { formSchema = json.writeValueAsString(fields); } + catch (Exception e) { throw new IllegalArgumentException("cannot serialize normalized Feishu form"); } + String formFingerprint = Sha256.hex(formSchema); + NormalizedDefinition definition = new NormalizedDefinition(code, name, nodes, null, + fields, formSchema, formFingerprint); definition.setFingerprint(fingerprint(definition)); return definition; } + private List normalizeForm(JsonNode source) { + if (source == null || source.isNull() || source.isMissingNode()) + throw new BusinessException("飞书审批定义缺少表单,请检查审批定义后重新同步", 409); + try { + if (json.writeValueAsBytes(source).length > 1000000) + throw new BusinessException("飞书审批表单定义超过 1MB", 409); + } catch (BusinessException e) { throw e; } + catch (Exception e) { throw new BusinessException("飞书审批表单定义无法解析", 409); } + if (source.isTextual()) { + String text = source.asText(); + if (text.length() > 1000000) throw new BusinessException("飞书审批表单定义过大", 409); + try { source = json.readTree(text); } + catch (Exception e) { throw new BusinessException("飞书审批表单不是有效的 JSON 数组", 409); } + } + if (!source.isArray()) throw new BusinessException("飞书审批表单必须为控件数组", 409); + Counter counter = new Counter(); Set ids = new HashSet<>(); Set valueKeys = new HashSet<>(); + List result = new ArrayList<>(); + for (JsonNode control : source) { + if (control == null || !control.isObject()) + throw new BusinessException("飞书审批表单包含无效控件", 409); + result.add(normalizeControl(control, 1, false, counter, ids, valueKeys)); + } + if (result.isEmpty() || !hasUsableField(result)) + throw new BusinessException("飞书审批表单为空或没有可用控件", 409); + validateUnambiguousSystemBindings(result); + return result; + } + + private ReimbursementFormField normalizeControl(JsonNode raw, int depth, boolean fieldListChild, + Counter counter, Set ids, Set valueKeys) { + if (depth > MAX_DEPTH) throw new BusinessException("飞书审批表单控件层级超过 5 层", 409); + if (++counter.controls > MAX_CONTROLS) throw new BusinessException("飞书审批表单控件超过 200 个", 409); + String id = bounded(firstText(raw, "id", "control_id", "controlId"), 300); + String customId = bounded(firstText(raw, "custom_id", "customId"), 200); + String providerType = bounded(firstText(raw, "type", "control_type", "controlType"), 80); + if (!StringUtils.hasText(id) || !StringUtils.hasText(providerType)) + throw new BusinessException("飞书表单控件缺少 id/type", 409); + if (!ids.add(id)) throw new BusinessException("飞书表单控件 id 重复: " + id, 409); + String label = bounded(displayText(first(raw, "name", "label", "title")), 500); + if (!StringUtils.hasText(label)) label = StringUtils.hasText(customId) ? customId : providerType; + boolean required = booleanValue(raw, false, "required", "is_required", "isRequired"); + boolean readOnly = booleanValue(raw, false, "read_only", "readOnly", "readonly", "disabled"); + JsonNode displayCondition = first(raw, "display_condition", "displayCondition"); + if (!hasContent(displayCondition) && raw.path("property").isObject()) + displayCondition = first(raw.path("property"), "display_condition", "displayCondition"); + if (hasContent(displayCondition)) + throw new BusinessException("飞书控件“" + label + "”配置了条件显示,当前版本不支持,请移除条件后重新同步", 409); + String normalizedType = providerType == null ? "" : providerType.replace("_", "").toLowerCase(Locale.ROOT); + String type; + switch (normalizedType) { + case "input": type = "TEXT"; break; + case "textarea": type = "TEXTAREA"; break; + case "text": type = "DISPLAY"; readOnly = true; break; + case "number": case "amount": type = "DECIMAL"; break; + case "formula": type = "FORMULA"; readOnly = true; break; + case "date": validateDateOnlyDefinition(raw, label); type = "DATE"; break; + case "attachmentv2": type = "ATTACHMENT"; break; + case "radio": case "radiov2": type = "SINGLE_SELECT"; break; + case "checkbox": case "checkboxv2": type = "MULTI_SELECT"; break; + case "contact": + if (depth == 1 && !fieldListChild && isApplicantContact(customId, label)) { + type = "CONTACT"; + readOnly = true; + } else { + if (required) + throw new BusinessException("飞书必填联系人控件“" + label + "”不是受支持的报销人绑定", 409); + type = "DISPLAY"; + readOnly = true; + } + break; + case "department": + if (depth == 1 && !fieldListChild && isApplicantDepartment(customId, label)) { + type = "DEPARTMENT"; + readOnly = false; + } else { + if (required) + throw new BusinessException("飞书必填部门控件“" + label + "”不是受支持的报销人所属部门绑定", 409); + type = "DISPLAY"; + readOnly = true; + } + break; + case "fieldlist": + if ("expense_items".equals(customId) + || (!StringUtils.hasText(customId) && "明细".equals(label))) type = "EXPENSE_ITEMS"; + else { type = unsupported(raw, required, readOnly, label, providerType); readOnly = true; } + break; + default: type = unsupported(raw, required, readOnly, label, providerType); readOnly = true; + } + String binding = "CONTACT".equals(type) ? "APPLICANT_CONTACT" + : ("DEPARTMENT".equals(type) ? "APPLICANT_DEPARTMENT" : (fieldListChild + ? expenseBinding(customId, label, normalizedType) + : topLevelBinding(customId, label, normalizedType, type))); + if (fieldListChild && binding == null) { + if (required && !readOnly) + throw new BusinessException("费用明细必填子控件“" + label + "”缺少受支持的 custom_id 绑定", 409); + binding = "CUSTOM"; type = "DISPLAY"; readOnly = true; + } + String valueKey = fieldListChild || !StringUtils.hasText(customId) ? id : customId; + if (!valueKeys.add(valueKey)) throw new BusinessException("飞书表单值键重复: " + valueKey, 409); + + List options = new ArrayList<>(); + boolean choice = "SINGLE_SELECT".equals(type) || "MULTI_SELECT".equals(type); + JsonNode optionNode = choice ? first(raw, "options", "option", "option_list", "optionList") : null; + if (choice && optionNode == null && raw.path("property").isObject()) + optionNode = first(raw.path("property"), "options", "option", "option_list", "optionList"); + if (choice && optionNode == null && raw.path("value").isObject()) + optionNode = first(raw.path("value"), "options", "option", "option_list", "optionList"); + if (choice && optionNode == null && raw.path("value").isArray()) optionNode = raw.path("value"); + Set optionValues = new HashSet<>(); + if (optionNode != null && !optionNode.isArray()) + throw new BusinessException("飞书表单选项定义不是数组: " + label, 409); + if (optionNode != null) for (JsonNode option : optionNode) { + if (option == null || !option.isObject()) + throw new BusinessException("飞书表单包含无效选项: " + label, 409); + if (++counter.options > MAX_OPTIONS) throw new BusinessException("飞书审批表单选项超过 500 个", 409); + String value = bounded(firstText(option, "value", "id", "key"), 500); + String optionLabel = bounded(displayText(first(option, "name", "label", "text")), 500); + if (!StringUtils.hasText(value)) value = optionLabel; + if (StringUtils.hasText(value)) { + if (!optionValues.add(value)) throw new BusinessException("飞书表单选项值重复: " + value, 409); + options.add(new ReimbursementFormField.Option(value, StringUtils.hasText(optionLabel) ? optionLabel : value)); + } + } + if (("SINGLE_SELECT".equals(type) || "MULTI_SELECT".equals(type)) && options.isEmpty()) + throw new BusinessException("飞书选择控件没有可用选项: " + label, 409); + String currency = null; + if ("amount".equals(normalizedType)) { + Set currencies = currencyRange(raw); + if (currencies.isEmpty()) currencies = new LinkedHashSet<>(Collections.singletonList("CNY")); + for (String code : currencies) { + options.add(new ReimbursementFormField.Option(code, code)); + } + currency = currencies.contains("CNY") ? "CNY" : currencies.iterator().next(); + } + List children = new ArrayList<>(); + JsonNode childNode = first(raw, "children", "controls", "fields", "items"); + if (childNode == null && "EXPENSE_ITEMS".equals(type) && raw.path("value").isArray()) + childNode = raw.path("value"); + if (childNode == null && raw.path("value").isObject()) + childNode = first(raw.path("value"), "children", "controls", "fields", "items"); + if (childNode != null && !childNode.isArray()) + throw new BusinessException("飞书表单子控件定义不是数组: " + label, 409); + if (childNode != null) for (JsonNode child : childNode) { + if (child == null || !child.isObject()) + throw new BusinessException("飞书表单包含无效子控件: " + label, 409); + children.add(normalizeControl(child, depth + 1, + fieldListChild || "EXPENSE_ITEMS".equals(type), counter, ids, valueKeys)); + } + int maxLength = intValue(raw, "max_length", "maxLength"); + if (maxLength <= 0 || maxLength > 20000) maxLength = 5000; + return ReimbursementFormField.builder().id(id).customId(customId).valueKey(valueKey).providerType(providerType) + .type(type).binding(binding).label(label).required(required).readOnly(readOnly) + .maxLength(maxLength).currency(currency).options(options).children(children).build(); + } + + private String expenseBinding(String customId, String label, String providerType) { + if (!StringUtils.hasText(customId)) { + if ("input".equals(providerType) && "报销事由".equals(label)) return "EXPENSE_DESCRIPTION"; + if ("date".equals(providerType) && "发生日期".equals(label)) return "EXPENSE_DATE"; + if ("amount".equals(providerType) && "金额".equals(label)) return "EXPENSE_AMOUNT"; + if ("attachmentv2".equals(providerType) && "附件".equals(label)) return "EXPENSE_ATTACHMENT"; + return null; + } + switch (customId) { + case "expense_date": case "date": return "EXPENSE_DATE"; + case "category": case "expense_category": return "EXPENSE_CATEGORY"; + case "description": case "expense_description": return "EXPENSE_DESCRIPTION"; + case "amount": case "expense_amount": return "EXPENSE_AMOUNT"; + case "attachment": case "expense_attachment": return "EXPENSE_ATTACHMENT"; + default: return null; + } + } + + private String topLevelBinding(String customId, String label, String providerType, String type) { + if (BINDINGS.contains(customId)) return customId.toUpperCase(Locale.ROOT); + if (!StringUtils.hasText(customId)) { + if ("date".equals(providerType) && "报销日期".equals(label)) return "REIMBURSEMENT_DATE"; + if ("FORMULA".equals(type) && "总金额".equals(label)) return "TOTAL_AMOUNT"; + if ("EXPENSE_ITEMS".equals(type) && "明细".equals(label)) return "EXPENSE_ITEMS"; + } + return "CUSTOM"; + } + + private Set currencyRange(JsonNode raw) { + JsonNode range = null; + for (JsonNode container : Arrays.asList(raw.path("option"), raw.path("property"), raw.path("value"))) { + if (container.isObject()) { + range = first(container, "currencyRange", "currency_range"); + if (range != null) break; + } + } + if (range == null) range = first(raw, "currencyRange", "currency_range"); + if (range == null || !range.isArray()) return Collections.emptySet(); + Set result = new HashSet<>(); + for (JsonNode item : range) { + String value = item.isValueNode() ? item.asText() : firstText(item, "value", "currency", "code"); + if (StringUtils.hasText(value)) result.add(value.trim().toUpperCase(Locale.ROOT)); + } + return result; + } + + private void validateDateOnlyDefinition(JsonNode raw, String label) { + JsonNode format = first(raw, "format", "dateFormat", "date_format"); + if (format == null) for (JsonNode container : Arrays.asList(raw.path("option"), raw.path("property"), raw.path("value"))) { + if (container.isObject()) { + format = first(container, "format", "dateFormat", "date_format"); + if (format != null) break; + } + } + // The deployed template omits format and is Feishu's documented date-only default. + if (format != null && (!format.isTextual() || !"YYYY-MM-DD".equals(format.asText()))) + throw new BusinessException("飞书日期控件“" + label + "”仅支持 YYYY-MM-DD 日期格式", 409); + } + + private void validateUnambiguousSystemBindings(List fields) { + Map top = new HashMap<>(); + boolean deployedNoCustomTemplate = false; + for (ReimbursementFormField field : fields) { + if (!"CUSTOM".equals(field.getBinding())) top.put(field.getBinding(), top.getOrDefault(field.getBinding(), 0) + 1); + if ("EXPENSE_ITEMS".equals(field.getBinding())) { + if (!StringUtils.hasText(field.getCustomId()) && "明细".equals(field.getLabel())) deployedNoCustomTemplate = true; + Map children = new HashMap<>(); + for (ReimbursementFormField child : field.getChildren()) + if (!"CUSTOM".equals(child.getBinding())) children.put(child.getBinding(), children.getOrDefault(child.getBinding(), 0) + 1); + for (Map.Entry entry : children.entrySet()) if (entry.getValue() > 1) + throw new BusinessException("飞书费用明细包含重复绑定: " + entry.getKey(), 409); + } + } + for (Map.Entry entry : top.entrySet()) if (entry.getValue() > 1) + throw new BusinessException("飞书表单包含重复系统绑定: " + entry.getKey(), 409); + if (deployedNoCustomTemplate) { + for (String binding : Arrays.asList("APPLICANT_CONTACT", "APPLICANT_DEPARTMENT", + "REIMBURSEMENT_DATE", "EXPENSE_ITEMS", "TOTAL_AMOUNT")) + if (top.getOrDefault(binding, 0) != 1) + throw new BusinessException("无 custom_id 的报销模板缺少唯一必填结构: " + binding, 409); + ReimbursementFormField details = null; + for (ReimbursementFormField field : fields) if ("EXPENSE_ITEMS".equals(field.getBinding())) details = field; + Map childBindings = new HashMap<>(); + for (ReimbursementFormField child : details.getChildren()) + childBindings.put(child.getBinding(), childBindings.getOrDefault(child.getBinding(), 0) + 1); + for (String binding : Arrays.asList("EXPENSE_DESCRIPTION", "EXPENSE_DATE", "EXPENSE_AMOUNT", "EXPENSE_ATTACHMENT")) + if (childBindings.getOrDefault(binding, 0) != 1) + throw new BusinessException("无 custom_id 的报销模板明细缺少唯一必填结构: " + binding, 409); + } + } + + private boolean isApplicantContact(String customId, String label) { + if (APPLICANT_CONTACT_IDS.contains(customId)) return true; + // Compatibility is intentionally limited to the one deployed template label when it + // has no semantic custom_id. Any nonblank custom_id must use an explicit applicant alias + // above and is never silently reinterpreted from its display label. + return "报销人".equals(label) && !StringUtils.hasText(customId); + } + + private boolean isApplicantDepartment(String customId, String label) { + if (APPLICANT_DEPARTMENT_IDS.contains(customId)) return true; + // Do not reinterpret a control carrying any other semantic custom_id. + return "报销人所属部门".equals(label) && !StringUtils.hasText(customId); + } + + private boolean hasContent(JsonNode value) { + if (value == null || value.isNull() || value.isMissingNode()) return false; + if (value.isTextual()) return StringUtils.hasText(value.asText()); + if (value.isContainerNode()) return value.size() > 0; + return true; + } + + private boolean hasUsableField(List fields) { + for (ReimbursementFormField field : fields) { + if ("CONTACT".equals(field.getType()) || "DEPARTMENT".equals(field.getType()) + || (!field.isReadOnly() && !"DISPLAY".equals(field.getType()))) return true; + if (hasUsableField(field.getChildren())) return true; + } + return false; + } + + private String unsupported(JsonNode raw, boolean required, boolean readOnly, String label, String providerType) { + if (required && !readOnly) + throw new BusinessException("飞书必填控件“" + label + "”类型 " + providerType + " 暂不支持,请改为支持的控件后同步", 409); + return "DISPLAY"; + } + private List normalizeApprovers(JsonNode node) { JsonNode values = first(node, "approvers", "approver", "approver_list", "approverList", "assignees"); - List result = new ArrayList<>(); - if (values == null) return result; + List result = new ArrayList<>(); if (values == null) return result; Iterable iterable = values.isArray() ? values : Collections.singletonList(values); for (JsonNode value : iterable) { if (result.size() >= MAX_APPROVERS) throw new IllegalArgumentException("too many Feishu approvers"); if (value == null || value.isNull()) continue; - if (value.isTextual()) { - result.add(new NormalizedApprover("USER", value.asText(), value.asText(), false)); - continue; - } + if (value.isTextual()) { result.add(new NormalizedApprover("USER", value.asText(), value.asText(), false)); continue; } String type = firstText(value, "type", "approver_type", "approverType"); String ref = firstText(value, "user_id", "userId", "open_id", "role_id", "roleId", "id"); String label = displayText(first(value, "name", "user_name", "role_name", "label", "title")); boolean dynamic = !isFixedPerson(type, ref); if (!StringUtils.hasText(label)) label = dynamic ? dynamicLabel(type) : "指定审批人"; if (dynamic && !label.contains("提交时")) label += "(提交时由飞书解析)"; - result.add(new NormalizedApprover(bounded(type, 80), bounded(ref, 300), bounded(label, 300), dynamic)); + result.add(new NormalizedApprover(bounded(type,80), bounded(ref,300), bounded(label,300), dynamic)); } return result; } - private boolean isDynamicNode(JsonNode node, List approvers) { + private boolean isDynamicNode(JsonNode node, List values) { String type = firstText(node, "node_type", "nodeType", "type"); - if (type != null && (type.toUpperCase(Locale.ROOT).contains("CONDITION") - || type.toUpperCase(Locale.ROOT).contains("ROUTE"))) return true; - for (NormalizedApprover approver : approvers) if (approver.isDynamic()) return true; + if (type != null && (type.toUpperCase(Locale.ROOT).contains("CONDITION") || type.toUpperCase(Locale.ROOT).contains("ROUTE"))) return true; + for (NormalizedApprover value : values) if (value.isDynamic()) return true; return node.has("condition") || node.has("conditions") || node.has("control"); } + private boolean isFixedPerson(String type, String ref) { String v=type==null?"":type.toUpperCase(Locale.ROOT); return StringUtils.hasText(ref)&&(v.isEmpty()||v.contains("USER")||v.contains("PERSON")); } + private String dynamicLabel(String type) { String v=type==null?"":type.toUpperCase(Locale.ROOT); if(v.contains("MANAGER")||v.contains("LEADER"))return "部门负责人"; if(v.contains("ROLE"))return "角色审批人"; if(v.contains("FREE"))return "发起人选择审批人"; return "飞书动态审批人"; } + private JsonNode findNodeArray(JsonNode node,int depth){if(node==null||depth>5)return null;for(String k:Arrays.asList("node_list","nodeList","approval_nodes","approvalNodes","nodes")){JsonNode c=node.get(k);if(c!=null&&c.isArray())return c;}for(String k:Arrays.asList("approval","definition","process","flow","approval_definition")){JsonNode f=findNodeArray(node.get(k),depth+1);if(f!=null)return f;}return null;} + private JsonNode findDeep(JsonNode node,int depth,String...names){if(node==null||depth>5)return null;JsonNode d=first(node,names);if(d!=null)return d;for(String k:Arrays.asList("approval","definition","process","flow","approval_definition")){JsonNode f=findDeep(node.get(k),depth+1,names);if(f!=null)return f;}return null;} + private String fingerprint(NormalizedDefinition d){StringBuilder c=new StringBuilder();append(c,d.approvalCode);append(c,d.approvalName);for(NormalizedNode n:d.nodes){append(c,String.valueOf(n.order));append(c,n.nodeKey);append(c,n.nodeName);append(c,n.nodeType);append(c,n.approvalMode);append(c,String.valueOf(n.dynamic));for(NormalizedApprover a:n.approvers){append(c,a.type);append(c,a.ref);append(c,a.label);append(c,String.valueOf(a.dynamic));}}append(c,d.formFingerprint);return Sha256.hex(c.toString());} + private void append(StringBuilder t,String v){String s=v==null?"":v;t.append(s.length()).append(':').append(s).append('|');} + private JsonNode first(JsonNode n,String...names){if(n==null)return null;for(String k:names){JsonNode v=n.get(k);if(v!=null&&!v.isNull()&&!v.isMissingNode())return v;}return null;} + private String firstText(JsonNode n,String...names){return displayText(first(n,names));} + private String displayText(JsonNode v){if(v==null||v.isNull())return null;if(v.isValueNode())return v.asText();for(String k:Arrays.asList("zh_cn","zh-CN","text","value","name")){JsonNode x=v.get(k);if(x!=null&&x.isValueNode())return x.asText();}return null;} + private boolean booleanValue(JsonNode n,boolean fallback,String...names){JsonNode v=first(n,names);if(v==null)return fallback;if(v.isBoolean())return v.asBoolean();return "true".equalsIgnoreCase(v.asText())||"1".equals(v.asText());} + private int intValue(JsonNode n,String...names){JsonNode v=first(n,names);return v!=null&&v.canConvertToInt()?v.asInt():0;} + private String bounded(String v,int max){return v==null?null:v.substring(0,Math.min(max,v.length()));} + private static class Counter { int controls; int options; } - private boolean isFixedPerson(String type, String ref) { - if (!StringUtils.hasText(ref)) return false; - String normalized = type == null ? "" : type.toUpperCase(Locale.ROOT); - return normalized.isEmpty() || normalized.contains("USER") || normalized.contains("PERSON"); - } - - private String dynamicLabel(String type) { - String value = type == null ? "" : type.toUpperCase(Locale.ROOT); - if (value.contains("MANAGER") || value.contains("LEADER")) return "部门负责人"; - if (value.contains("ROLE")) return "角色审批人"; - if (value.contains("FREE")) return "发起人选择审批人"; - return "飞书动态审批人"; - } - - private JsonNode findNodeArray(JsonNode node, int depth) { - if (node == null || depth > 5) return null; - for (String key : Arrays.asList("node_list", "nodeList", "approval_nodes", "approvalNodes", "nodes")) { - JsonNode candidate = node.get(key); - if (candidate != null && candidate.isArray()) return candidate; - } - for (String key : Arrays.asList("approval", "definition", "process", "flow", "approval_definition")) { - JsonNode nested = node.get(key); - JsonNode found = findNodeArray(nested, depth + 1); - if (found != null) return found; - } - return null; - } - - private JsonNode findDeep(JsonNode node, int depth, String... names) { - if (node == null || depth > 5) return null; - JsonNode direct = first(node, names); - if (direct != null) return direct; - for (String key : Arrays.asList("approval", "definition", "process", "flow", "approval_definition")) { - JsonNode found = findDeep(node.get(key), depth + 1, names); - if (found != null) return found; - } - return null; - } - - private String fingerprint(NormalizedDefinition definition) { - StringBuilder canonical = new StringBuilder(); - append(canonical, definition.getApprovalCode()); - append(canonical, definition.getApprovalName()); - for (NormalizedNode node : definition.getNodes()) { - append(canonical, String.valueOf(node.getOrder())); append(canonical, node.getNodeKey()); - append(canonical, node.getNodeName()); append(canonical, node.getNodeType()); - append(canonical, node.getApprovalMode()); append(canonical, String.valueOf(node.isDynamic())); - for (NormalizedApprover approver : node.getApprovers()) { - append(canonical, approver.getType()); append(canonical, approver.getRef()); - append(canonical, approver.getLabel()); append(canonical, String.valueOf(approver.isDynamic())); - } - } - return Sha256.hex(canonical.toString()); - } - - private void append(StringBuilder target, String value) { - String safe = value == null ? "" : value; - target.append(safe.length()).append(':').append(safe).append('|'); - } - - private JsonNode first(JsonNode node, String... names) { - if (node == null) return null; - for (String name : names) { - JsonNode value = node.get(name); - if (value != null && !value.isNull() && !value.isMissingNode()) return value; - } - return null; - } - - private String firstText(JsonNode node, String... names) { return displayText(first(node, names)); } - - private String displayText(JsonNode value) { - if (value == null || value.isNull()) return null; - if (value.isValueNode()) return value.asText(); - for (String key : Arrays.asList("zh_cn", "zh-CN", "text", "value", "name")) { - JsonNode nested = value.get(key); - if (nested != null && nested.isValueNode()) return nested.asText(); - } - return null; - } - - private String bounded(String value, int max) { - return value == null ? null : value.substring(0, Math.min(max, value.length())); - } - - @Data @AllArgsConstructor - public static class NormalizedDefinition { - private String approvalCode; - private String approvalName; - private List nodes; - private String fingerprint; - } - @Data @AllArgsConstructor - public static class NormalizedNode { - private int order; private String nodeKey; private String nodeName; private String nodeType; - private String approvalMode; private boolean dynamic; private List approvers; - } - @Data @AllArgsConstructor - public static class NormalizedApprover { - private String type; private String ref; private String label; private boolean dynamic; + @Data @AllArgsConstructor public static class NormalizedDefinition { + private String approvalCode; private String approvalName; private List nodes; private String fingerprint; + private List formFields; private String formSchema; private String formFingerprint; } + @Data @AllArgsConstructor public static class NormalizedNode { private int order; private String nodeKey; private String nodeName; private String nodeType; private String approvalMode; private boolean dynamic; private List approvers; } + @Data @AllArgsConstructor public static class NormalizedApprover { private String type; private String ref; private String label; private boolean dynamic; } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java index 7c93b99..0d97b18 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSnapshotWriter.java @@ -20,6 +20,10 @@ public class FeishuDefinitionSnapshotWriter { private final FeishuApprovalDefinitionApproverRepository approvers; private final FeishuDefinitionSyncFenceRepository fences; + /** + * Persist form schema on the managed CURRENT row first (so readers never see a + * wiped snapshot), then replace route nodes when the definition fingerprint changes. + */ @Transactional public FeishuDefinitionSyncResult replace(NormalizedDefinition definition, LocalDateTime fetchedAt, long generation) { FeishuDefinitionSyncFence fence = fences.findByIdForUpdate(FeishuDefinitionSyncFence.SINGLETON_ID) @@ -27,50 +31,68 @@ public class FeishuDefinitionSnapshotWriter { if (!Objects.equals(fence.getGeneration(), generation)) { throw new BusinessException("本次同步已被更新的审批定义同步取代,请刷新后重试", 409); } + FeishuApprovalDefinitionSnapshot current = snapshots .findById(FeishuApprovalDefinitionSnapshot.CURRENT_ID).orElse(null); - if (current != null && definition.getFingerprint().equals(current.getFingerprint())) { - current.setFetchedAt(fetchedAt); - current.setUpdatedAt(fetchedAt); - current.setApprovalCode(definition.getApprovalCode()); - current.setApprovalName(definition.getApprovalName()); - snapshots.save(current); - return result(definition, fetchedAt, false); + boolean changed = current == null + || !definition.getFingerprint().equals(current.getFingerprint()); + + if (current == null) { + current = FeishuApprovalDefinitionSnapshot.builder() + .id(FeishuApprovalDefinitionSnapshot.CURRENT_ID) + .createdAt(fetchedAt) + .build(); } + current.setApprovalCode(definition.getApprovalCode()); + current.setApprovalName(definition.getApprovalName()); + current.setFingerprint(definition.getFingerprint()); + current.setFormFingerprint(definition.getFormFingerprint()); + current.setFormSchema(definition.getFormSchema()); + current.setFetchedAt(fetchedAt); + current.setUpdatedAt(fetchedAt); + if (current.getCreatedAt() == null) current.setCreatedAt(fetchedAt); + // Flush form schema before node surgery so a mid-TX failure still leaves a + // consistent form row on rollback, and commit publishes a complete form. + snapshots.saveAndFlush(current); - List oldNodes = nodes - .findBySnapshotIdOrderByNodeOrderAsc(FeishuApprovalDefinitionSnapshot.CURRENT_ID); - List oldIds = new ArrayList<>(); - for (FeishuApprovalDefinitionNode node : oldNodes) oldIds.add(node.getId()); - if (!oldIds.isEmpty()) approvers.deleteByNodeIdIn(oldIds); - nodes.deleteBySnapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID); + if (changed) { + List oldNodes = nodes + .findBySnapshotIdOrderByNodeOrderAsc(FeishuApprovalDefinitionSnapshot.CURRENT_ID); + List oldIds = new ArrayList<>(); + for (FeishuApprovalDefinitionNode node : oldNodes) oldIds.add(node.getId()); + if (!oldIds.isEmpty()) approvers.deleteByNodeIdIn(oldIds); + nodes.deleteBySnapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID); + approvers.flush(); + nodes.flush(); - LocalDateTime createdAt = current == null ? fetchedAt : current.getCreatedAt(); - snapshots.save(FeishuApprovalDefinitionSnapshot.builder() - .id(FeishuApprovalDefinitionSnapshot.CURRENT_ID) - .approvalCode(definition.getApprovalCode()).approvalName(definition.getApprovalName()) - .fingerprint(definition.getFingerprint()).fetchedAt(fetchedAt) - .createdAt(createdAt).updatedAt(fetchedAt).build()); - - for (NormalizedNode source : definition.getNodes()) { - FeishuApprovalDefinitionNode node = nodes.saveAndFlush(FeishuApprovalDefinitionNode.builder() - .snapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID).nodeOrder(source.getOrder()) - .nodeKey(source.getNodeKey()).nodeName(source.getNodeName()).nodeType(source.getNodeType()) - .approvalMode(source.getApprovalMode()).dynamic(source.isDynamic()).build()); - int order = 1; - for (NormalizedApprover sourceApprover : source.getApprovers()) { - approvers.save(FeishuApprovalDefinitionApprover.builder().nodeId(node.getId()) - .approverOrder(order++).approverType(sourceApprover.getType()) - .approverRef(sourceApprover.getRef()).approverLabel(sourceApprover.getLabel()) - .dynamic(sourceApprover.isDynamic()).build()); + for (NormalizedNode source : definition.getNodes()) { + FeishuApprovalDefinitionNode node = nodes.saveAndFlush(FeishuApprovalDefinitionNode.builder() + .snapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID).nodeOrder(source.getOrder()) + .nodeKey(source.getNodeKey()).nodeName(source.getNodeName()).nodeType(source.getNodeType()) + .approvalMode(source.getApprovalMode()).dynamic(source.isDynamic()).build()); + int order = 1; + for (NormalizedApprover sourceApprover : source.getApprovers()) { + approvers.save(FeishuApprovalDefinitionApprover.builder().nodeId(node.getId()) + .approverOrder(order++).approverType(sourceApprover.getType()) + .approverRef(sourceApprover.getRef()).approverLabel(sourceApprover.getLabel()) + .dynamic(sourceApprover.isDynamic()).build()); + } } } - return result(definition, fetchedAt, true); + return result(definition, fetchedAt, changed); } private FeishuDefinitionSyncResult result(NormalizedDefinition definition, LocalDateTime fetchedAt, boolean changed) { return FeishuDefinitionSyncResult.builder().fingerprint(definition.getFingerprint()) + .formFingerprint(definition.getFormFingerprint()).formFieldCount(countFields(definition.getFormFields())) .fetchedAt(fetchedAt).nodeCount(definition.getNodes().size()).changed(changed).build(); } + + private int countFields(List fields) { + int count = 0; + if (fields != null) for (com.finance.system.dto.ReimbursementFormField field : fields) + count += 1 + countFields(field.getChildren()); + return count; + } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java index 38f36be..897cce7 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java @@ -4,10 +4,17 @@ import com.fasterxml.jackson.databind.JsonNode; import com.finance.system.dto.FeishuDefinitionSyncResult; import com.finance.system.exception.BusinessException; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.time.LocalDateTime; +/** + * Network I/O completes before the transactional writer. Event subscription is + * best-effort after the snapshot is durable so 发起申请 can load the form even + * when Feishu subscribe is slow or fails. + */ +@Slf4j @Service @RequiredArgsConstructor public class FeishuDefinitionSyncService { @@ -16,23 +23,38 @@ public class FeishuDefinitionSyncService { private final FeishuDefinitionSnapshotWriter writer; private final FeishuDefinitionGenerationService generations; - /** Network I/O intentionally completes before the transactional writer is entered. */ public FeishuDefinitionSyncResult sync() { if (!remote.isApprovalEnabledAndConfigured()) { - throw new BusinessException("飞书审批未配置,无法同步", 409); + throw new BusinessException("飞书审批未配置,无法验证与同步", 409); } long generation = generations.reserve(); + FeishuDefinitionSyncResult result; try { JsonNode response = remote.fetchApprovalDefinitionJson(); FeishuDefinitionNormalizer.NormalizedDefinition definition = normalizer.normalize(response, remote.getConfiguredApprovalCode()); - return writer.replace(definition, LocalDateTime.now(), generation); + result = writer.replace(definition, LocalDateTime.now(), generation); + result.setApprovalCode(remote.getConfiguredApprovalCode()); } catch (BusinessException e) { throw e; + } catch (IllegalArgumentException e) { + throw new BusinessException("飞书审批定义无法使用: " + e.getMessage(), 409); } catch (Exception e) { - // The writer was never called (or its transaction rolled back), so the - // last known-good snapshot remains available. - throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502); + throw new BusinessException("飞书审批定义验证失败,请稍后重试", 502); } + + // Snapshot is already committed. Never let subscribe latency/failure block form loading. + try { + boolean newlySubscribed = remote.subscribeApprovalEvents(); + result.setEventSubscribed(newlySubscribed); + result.setMessage(newlySubscribed + ? "已验证审批定义并完成事件订阅;飞书审批状态变更将实时同步到本系统" + : "已验证审批定义;事件订阅已存在,飞书审批状态变更将实时同步到本系统"); + } catch (Exception e) { + log.warn("飞书审批定义已同步,但事件订阅失败: {}", e.toString()); + result.setEventSubscribed(false); + result.setMessage("已验证并同步审批定义(发起申请可用);事件订阅暂未成功,请检查飞书事件权限后再次同步"); + } + return result; } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java index 4e90026..8cb396c 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java @@ -55,10 +55,81 @@ public class FeishuDirectoryCurrentStore { } public Map read(){ - List> departments=new ArrayList<>();for(Mapr:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){Mapd=new LinkedHashMap<>();d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name")));d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order"))));d.put("memberCount",intValue(r.get("member_count")));departments.add(d);} - Map> memberships=new HashMap<>();for(Mapr:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department ORDER BY open_id,open_department_id"))memberships.computeIfAbsent(string(r.get("open_id")),k->new ArrayList<>()).add(string(r.get("open_department_id"))); - List>users=new ArrayList<>();for(Mapr:jdbc.queryForList("SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id")){Mapu=new LinkedHashMap<>();String open=string(r.get("open_id"));u.put("openId",open);u.put("userId",r.get("user_id")==null?null:string(r.get("user_id")));u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no"));u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile")));u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url")));u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u);} - Mapresult=new LinkedHashMap<>();result.put("departments",departments);result.put("users",users);return result; + Mapresult=new LinkedHashMap<>(); + result.put("departments",readDepartments()); + result.put("users",readUsers(null)); + return result; + } + + /** Departments only — used by the organization shell so the page can paint before members load. */ + public List> readDepartments(){ + List> departments=new ArrayList<>(); + for(Mapr:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){ + Mapd=new LinkedHashMap<>(); + d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name"))); + d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order")))); + d.put("memberCount",intValue(r.get("member_count")));departments.add(d); + } + return departments; + } + + /** + * Users optionally scoped to a set of department open IDs (direct membership). + * Null/empty {@code departmentIds} returns the full directory (legacy full payload). + */ + public List> readUsers(Collection departmentIds){ + Map> memberships=new HashMap<>(); + Set scope=null; + if(departmentIds!=null&&!departmentIds.isEmpty()){ + scope=new HashSet<>(); + for(String id:departmentIds){if(id!=null&&!id.trim().isEmpty())scope.add(id.trim());} + if(scope.isEmpty())return Collections.emptyList(); + } + String membershipSql=scope==null + ?"SELECT open_id,open_department_id FROM feishu_directory_user_department ORDER BY open_id,open_department_id" + :"SELECT open_id,open_department_id FROM feishu_directory_user_department WHERE open_department_id IN (" + +placeholders(scope.size())+") ORDER BY open_id,open_department_id"; + List> membershipRows=scope==null + ?jdbc.queryForList(membershipSql) + :jdbc.queryForList(membershipSql,scope.toArray()); + Set openIds=new LinkedHashSet<>(); + for(Mapr:membershipRows){ + String open=string(r.get("open_id")); + memberships.computeIfAbsent(open,k->new ArrayList<>()).add(string(r.get("open_department_id"))); + openIds.add(open); + } + if(scope!=null&&openIds.isEmpty())return Collections.emptyList(); + // For scoped reads, still attach every membership so the UI can show multi-department users accurately. + if(scope!=null){ + memberships.clear(); + List> allForUsers=jdbc.queryForList( + "SELECT open_id,open_department_id FROM feishu_directory_user_department WHERE open_id IN (" + +placeholders(openIds.size())+") ORDER BY open_id,open_department_id", + openIds.toArray()); + for(Mapr:allForUsers)memberships.computeIfAbsent(string(r.get("open_id")),k->new ArrayList<>()).add(string(r.get("open_department_id"))); + } + String userSql=scope==null + ?"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id" + :"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user WHERE open_id IN (" + +placeholders(openIds.size())+") ORDER BY open_id"; + List> userRows=scope==null?jdbc.queryForList(userSql):jdbc.queryForList(userSql,openIds.toArray()); + List>users=new ArrayList<>(); + for(Mapr:userRows){ + Mapu=new LinkedHashMap<>();String open=string(r.get("open_id")); + u.put("openId",open);u.put("userId",r.get("user_id")==null?null:string(r.get("user_id"))); + u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no")); + u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile"))); + u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url"))); + u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u); + } + return users; + } + + private static String placeholders(int count){ + if(count<1)throw new IllegalArgumentException("placeholder count"); + StringBuilder b=new StringBuilder("?"); + for(int i=1;iold,Setwanted){Listrows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM feishu_directory_user_department WHERE open_id=? AND open_department_id=?",rows);} private void batchDelete(String table,String column,Setold,Setwanted){Listrows=new ArrayList<>();for(String value:old)if(!wanted.contains(value))rows.add(new Object[]{value});batch("DELETE FROM "+table+" WHERE "+column+"=?",rows);} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java index ff479fb..61ce3ff 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java @@ -90,7 +90,10 @@ public class FeishuDirectoryService { result.put("lastRun",last);return result; } - public Map organization(){ + /** Default page load: departments only. Pass includeUsers=true for the legacy full payload. */ + public Map organization(){return organization(false);} + + public Map organization(boolean includeUsers){ Map unavailable=emptyOrganization(FeishuDirectoryPublication.unavailable(),null,"UNKNOWN"); if(!organizationPermits.tryAcquire())return unavailable; try{ @@ -100,8 +103,8 @@ public class FeishuDirectoryService { Instant success=publication.getSuccessfulAt(); Map result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN"); if(!publication.isAvailable())return new OrganizationSnapshot(publication,result); - Map organization=currentStore.read(); - if(organization!=null){result.put("departments",organization.get("departments"));result.put("users",organization.get("users"));} + result.put("departments",currentStore.readDepartments()); + if(includeUsers)result.put("users",currentStore.readUsers(null)); return new OrganizationSnapshot(publication,result); }); if(captured==null||!captured.publication.isAvailable())return captured==null?unavailable:captured.value; @@ -112,6 +115,57 @@ public class FeishuDirectoryService { finally{organizationPermits.release();} } + /** Members for one department (optionally including descendants). Same availability fence as organization(). */ + public Map organizationMembers(String departmentId,boolean includeDescendants){ + Map unavailable=emptyOrganization(FeishuDirectoryPublication.unavailable(),null,"UNKNOWN"); + unavailable.put("departmentId",departmentId==null?"":departmentId); + if(departmentId==null||departmentId.trim().isEmpty())return unavailable; + if(!organizationPermits.tryAcquire())return unavailable; + String target=departmentId.trim(); + try{ + OrganizationSnapshot captured=organizationSnapshot.execute(status->{ + Map state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1"); + FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time); + Instant success=publication.getSuccessfulAt(); + Map result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN"); + result.put("departmentId",target); + if(!publication.isAvailable())return new OrganizationSnapshot(publication,result); + List> departments=currentStore.readDepartments(); + Set scope=new LinkedHashSet<>(); + scope.add(target); + if(includeDescendants)scope.addAll(descendantIds(departments,target)); + result.put("departments",departments); + result.put("users",currentStore.readUsers(scope)); + return new OrganizationSnapshot(publication,result); + }); + if(captured==null||!captured.publication.isAvailable())return captured==null?unavailable:captured.value; + if(!revalidate(captured.publication))return unavailable; + captured.value.put("contextState",captured.publication.contextState(currentContext()).name()); + return captured.value; + }catch(Exception ignored){log.warn("Feishu organization members could not be read");return unavailable;} + finally{organizationPermits.release();} + } + + private static Set descendantIds(List> departments,String rootId){ + Map> children=new HashMap<>(); + for(Map department:departments){ + String id=String.valueOf(department.get("id")==null?"":department.get("id")); + String parent=String.valueOf(department.get("parentId")==null?"":department.get("parentId")); + if(id.isEmpty())continue; + children.computeIfAbsent(parent,k->new ArrayList<>()).add(id); + } + Set result=new LinkedHashSet<>(); + ArrayDeque queue=new ArrayDeque<>(); + queue.add(rootId); + while(!queue.isEmpty()){ + String current=queue.removeFirst(); + for(String child:children.getOrDefault(current,Collections.emptyList())){ + if(result.add(child))queue.add(child); + } + } + return result; + } + /** A separate READ_COMMITTED transaction observes publications committed during materialization. */ private boolean revalidate(FeishuDirectoryPublication captured){ Boolean stable=observation.execute(status->{ diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java index caef0f3..8dfec05 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java @@ -23,9 +23,32 @@ public class FeishuDirectorySyncDispatcher implements SmartLifecycle { private ScheduledFuture poller; public FeishuDirectorySyncDispatcher(FeishuDirectorySyncWorker worker, @Qualifier("feishuDirectoryWorkerExecutor") ScheduledExecutorService executor, Environment environment){this.worker=worker;this.executor=executor;this.testProfile=java.util.Arrays.stream(environment.getActiveProfiles()).anyMatch("test"::equalsIgnoreCase);} - @Override public void start(){if(running.compareAndSet(false,true)&&!testProfile)poller=executor.scheduleWithFixedDelay(this::drainSafely,0,1, TimeUnit.SECONDS);} + @Override public void start(){ + // Slight delay avoids racing ApplicationContext shutdown when port bind fails. + if(running.compareAndSet(false,true)&&!testProfile) + poller=executor.scheduleWithFixedDelay(this::drainSafely,1,1, TimeUnit.SECONDS); + } public void wake(){if(!running.get()||testProfile)return;try{executor.execute(this::drainSafely);}catch(RejectedExecutionException ignored){/* row remains durable */}} - private void drainSafely(){if(!running.get())return;try{while(running.get()&&worker.runOne()){} }catch(Throwable ignored){log.warn("Feishu directory dispatcher iteration failed");}} + private void drainSafely(){ + if(!running.get())return; + try{while(running.get()&&worker.runOne()){}} + catch(Throwable ex){ + // Context shutdown closes the shared Hibernate session/pool while a tick may still be in flight. + if(!running.get()||isShutdownNoise(ex))return; + log.warn("Feishu directory dispatcher iteration failed: {}", ex.toString()); + } + } + private static boolean isShutdownNoise(Throwable ex){ + for(Throwable current=ex;current!=null;current=current.getCause()){ + String name=current.getClass().getName(); + String message=current.getMessage()==null?"":current.getMessage(); + if(name.contains("CannotGetJdbcConnectionException"))return true; + if(message.contains("Session/EntityManager is closed"))return true; + if(message.contains("dataSource already closed")||message.contains("HikariDataSource has been closed"))return true; + if(message.contains("Pool has been closed")||message.contains("Connection is closed"))return true; + } + return false; + } @Override public void stop(){running.set(false);if(poller!=null)poller.cancel(false);} @Override public void stop(Runnable callback){stop();callback.run();} @Override public boolean isRunning(){return running.get();} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java index 44061a4..cef5136 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java @@ -20,9 +20,13 @@ public class FeishuTenantTokenService { private static final BigInteger SUCCESS_CODE = BigInteger.ZERO; private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L); private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); + /** Status/organization pages poll capture often; decrypt is the expensive part. */ + private static final long CAPTURE_CACHE_TTL_MS = 5_000L; private final IntegrationConfigReader config; private final FeishuDirectorySettings settings; private final RestTemplate http; + private final Object captureLock = new Object(); + private volatile CachedCapture cachedCapture; @Autowired public FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings) { @@ -39,7 +43,35 @@ public class FeishuTenantTokenService { return new RestTemplate(factory); } + /** Drop cached credentials after an admin config write. */ + public void invalidateCaptureCache() { cachedCapture = null; } + public Context capture() { + long now = System.currentTimeMillis(); + CachedCapture hit = cachedCapture; + if (hit != null && now - hit.atMs < CAPTURE_CACHE_TTL_MS) { + if (hit.failure != null) throw hit.failure; + return hit.context; + } + synchronized (captureLock) { + hit = cachedCapture; + now = System.currentTimeMillis(); + if (hit != null && now - hit.atMs < CAPTURE_CACHE_TTL_MS) { + if (hit.failure != null) throw hit.failure; + return hit.context; + } + try { + Context context = captureFresh(); + cachedCapture = new CachedCapture(context, null, now); + return context; + } catch (DiagnosticFailure failure) { + cachedCapture = new CachedCapture(null, failure, now); + throw failure; + } + } + } + + private Context captureFresh() { Map values; try { values = config.freshFeishu(); @@ -65,10 +97,11 @@ public class FeishuTenantTokenService { } public boolean syncEnabled() { - Map values; - try { values = config.freshFeishu(); } + try { + Map values = config.freshFeishu(); + return values != null && Boolean.parseBoolean(values.getOrDefault("syncOrgEnabled", "true")); + } catch (DiagnosticFailure ex) { throw ex; } catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); } - return values != null && Boolean.parseBoolean(values.getOrDefault("syncOrgEnabled", "true")); } public String getTenantAccessToken() { return token(capture()); } @@ -200,4 +233,13 @@ public class FeishuTenantTokenService { Context(String app, String secret, String fingerprint) { this.app = app; this.secret = secret; this.fingerprint = fingerprint; } // Deliberately no toString/getters for credentials. } + + private static final class CachedCapture { + private final Context context; + private final DiagnosticFailure failure; + private final long atMs; + private CachedCapture(Context context, DiagnosticFailure failure, long atMs) { + this.context = context; this.failure = failure; this.atMs = atMs; + } + } } diff --git a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java index 21ff7c2..e609d29 100644 --- a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java +++ b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java @@ -30,6 +30,10 @@ public final class ReimbursementCanonicalizer { field(out, "totalAmount", money(app.getTotalAmount())); field(out, "payeeName", app.getPayeeName()); field(out, "payeeBankId", app.getPayeeBankId()); + field(out, "feishuFormFingerprint", app.getFeishuFormFingerprint()); + field(out, "feishuFormSchema", app.getFeishuFormSchema()); + field(out, "feishuFormValues", app.getFeishuFormValues()); + field(out, "feishuFormDisplayValues", app.getFeishuFormDisplayValues()); field(out, "bankName", bank == null ? null : bank.getBankName()); field(out, "branchName", bank == null ? null : bank.getBranchName()); field(out, "accountName", bank == null ? null : bank.getAccountName()); diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java index 34bc45a..b3592a4 100644 --- a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java +++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java @@ -5,17 +5,19 @@ 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 com.finance.system.service.KingdeeAccountBindingService; +import com.finance.system.util.AuditUtil; 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.http.*; +import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import java.util.HashMap; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -33,6 +35,7 @@ public class KingdeeClient { private String sessionConfigFingerprint; private IntegrationConfigReader integrationConfigReader; private IntegrationConfigService integrationConfigService; + private KingdeeAccountBindingService kingdeeAccountBindingService; @Autowired(required = false) public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) { @@ -44,55 +47,30 @@ public class KingdeeClient { this.integrationConfigService = integrationConfigService; } + @Autowired(required = false) + public void setKingdeeAccountBindingService(@Lazy KingdeeAccountBindingService kingdeeAccountBindingService) { + this.kingdeeAccountBindingService = kingdeeAccountBindingService; + } + public boolean isEnabled() { return (integrationConfigReader == null ? kingdeeConfig.isEnabled() : integrationConfigReader.isEnabled("KINGDEE")) && hasText(baseUrl()); } - /** - * 登录金蝶云星空,获取Session - */ + /** System-account login used by sync/query and connection tests. */ 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 && loginSucceeded(body)) { - Map context = asMap(body.get("Context")); - Map result = asMap(body.get("Result")); - String token = text(context.get("SessionId")); - if (token == null) token = text(result.get("SessionId")); - if (token != null) { - this.sessionToken = token; - this.sessionExpireTime = System.currentTimeMillis() + 3600000; // 1小时过期 - this.sessionConfigFingerprint = configFingerprint(); - return this.sessionToken; - } - } - throw new BusinessException("金蝶登录失败"); - } catch (Exception e) { - // Never log the remote exception: it can contain the response body or account data. - log.error("金蝶云星空登录失败"); - throw new BusinessException("金蝶云星空连接失败"); - } + String token = authenticate(clientId(), clientSecret()); + this.sessionToken = token; + this.sessionExpireTime = System.currentTimeMillis() + 3600000; + this.sessionConfigFingerprint = configFingerprint(); + return token; + } + + /** Validates employee credentials without replacing the system session. */ + public void validateUserCredentials(String username, String password) { + authenticate(username, password); } - /** - * 获取有效的Session - */ private String getValidSession() { if (!isEnabled()) throw new BusinessException("金蝶集成未启用"); if (sessionToken == null || System.currentTimeMillis() > sessionExpireTime @@ -104,26 +82,27 @@ public class KingdeeClient { } /** - * 保存单据(创建/更新) + * Saves / updates a Kingdee financial document using the current operator's + * bound employee account. System account credentials are never used here. */ public Map save(String formId, Map data) { + if (kingdeeAccountBindingService == null) { + throw new BusinessException("金蝶员工账号绑定服务未配置"); + } + Long userId = AuditUtil.getCurrentUserId(); + KingdeeAccountBindingService.KingdeeCredentials credentials = + kingdeeAccountBindingService.requireCredentials(userId); String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc"; - return executeKingdeeApi(url, formId, data); + String userSession = authenticate(credentials.getUsername(), credentials.getPassword()); + return executeKingdeeApi(url, formId, data, userSession); } - /** - * 查看单据 - */ 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); - + HttpEntity> request = new HttpEntity<>(data, buildHeaders(getValidSession())); try { ResponseEntity response = restTemplate.postForEntity(url, request, Map.class); return response.getBody(); @@ -133,26 +112,13 @@ public class KingdeeClient { } } - /** - * 查询单据列表 - */ public List> query(String formId, String filterString) { return query(formId, filterString, "*", 0, 100); } - /** - * Queries a page of a Kingdee document. The old two argument method is - * deliberately kept as a compatibility wrapper because it is used by the - * outbound integration code and by older callers. - * - * @param fieldKeys comma separated Kingdee field keys (or *) - * @param startRow zero based offset - * @param topRowCount maximum number of rows to return - */ public List> query(String formId, String filterString, String fieldKeys, int startRow, int topRowCount) { - String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc"; - + String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc"; Map data = new HashMap<>(); data.put("FormId", formId); data.put("FieldKeys", fieldKeys == null || fieldKeys.trim().isEmpty() ? "*" : fieldKeys); @@ -160,33 +126,22 @@ public class KingdeeClient { data.put("OrderString", "FBillNo ASC"); data.put("StartRow", Math.max(0, startRow)); int boundedTop = Math.max(1, Math.min(100, topRowCount)); - // ExecuteBillQuery uses Limit for page size. TopRowCount must remain - // zero or some K3Cloud versions cap the entire result set at page one. data.put("TopRowCount", 0); data.put("Limit", boundedTop); - - HttpHeaders headers = buildHeaders(); - HttpEntity> request = new HttpEntity<>(data, headers); - + HttpEntity> request = new HttpEntity<>(data, buildHeaders(getValidSession())); try { - ResponseEntity response = restTemplate.postForEntity(url, request, Object.class); - return queryRows(response.getBody(), fieldKeys); + ResponseEntity response = restTemplate.postForEntity(url, request, Object.class); + return queryRows(response.getBody(), fieldKeys); } catch (Exception e) { log.error("金蝶查询单据失败: formId={}", formId); throw new BusinessException("金蝶单据查询失败"); } } - /** - * 执行金蝶API调用 - */ - private Map executeKingdeeApi(String url, String formId, Map data) { + private Map executeKingdeeApi(String url, String formId, Map data, String session) { Map requestData = new HashMap<>(data); requestData.put("FormId", formId); - - HttpHeaders headers = buildHeaders(); - HttpEntity> request = new HttpEntity<>(requestData, headers); - + HttpEntity> request = new HttpEntity<>(requestData, buildHeaders(session)); try { ResponseEntity response = restTemplate.postForEntity(url, request, Map.class); Map body = response.getBody(); @@ -194,18 +149,48 @@ public class KingdeeClient { throw new BusinessException("金蝶操作失败"); } return body; + } catch (BusinessException e) { + throw e; } catch (Exception e) { log.error("金蝶API调用失败: formId={}", formId); throw new BusinessException("金蝶云星空操作失败"); } } - private HttpHeaders buildHeaders() { + private String authenticate(String username, String password) { + if (!isEnabled()) throw new BusinessException("金蝶集成未启用或配置不完整"); + if (!hasText(username) || !hasText(password)) 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", username); + requestBody.put("password", password); + requestBody.put("lcid", 2052); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + try { + ResponseEntity response = restTemplate.postForEntity(url, new HttpEntity<>(requestBody, headers), Map.class); + Map body = response.getBody(); + if (body != null && loginSucceeded(body)) { + Map context = asMap(body.get("Context")); + Map result = asMap(body.get("Result")); + String token = text(context.get("SessionId")); + if (token == null) token = text(result.get("SessionId")); + if (token != null) return token; + } + throw new BusinessException("金蝶登录失败"); + } catch (BusinessException e) { + throw e; + } catch (Exception e) { + log.error("金蝶云星空登录失败"); + throw new BusinessException("金蝶云星空连接失败"); + } + } + + private HttpHeaders buildHeaders(String session) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - String session = getValidSession(); headers.set("kdservice-sessionid", session); - // Keep the legacy header for older K3Cloud gateways during migration. headers.set("SessionId", session); return headers; } @@ -221,9 +206,6 @@ public class KingdeeClient { Object rowsBody = body; for (int depth = 0; depth < 5 && rowsBody instanceof Map; depth++) { Map map = asMap(rowsBody); - // Only documented response envelopes carry operation status. - // Do not recursively inspect data rows: a form may legitimately - // contain a business field named IsSuccess with value false. if (envelopeFailed(map)) throw new BusinessException("金蝶单据查询失败"); if (map.containsKey("Result")) rowsBody = map.get("Result"); else if (map.containsKey("Data")) rowsBody = map.get("Data"); @@ -276,10 +258,16 @@ public class KingdeeClient { } 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 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()); } + 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/config/AsyncConfig.java b/src/main/java/com/finance/system/config/AsyncConfig.java new file mode 100644 index 0000000..971a425 --- /dev/null +++ b/src/main/java/com/finance/system/config/AsyncConfig.java @@ -0,0 +1,26 @@ +package com.finance.system.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@EnableAsync +public class AsyncConfig { + + @Bean(name = "apiAccessLogExecutor") + public Executor apiAccessLogExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(1); + executor.setMaxPoolSize(4); + executor.setQueueCapacity(2000); + executor.setThreadNamePrefix("api-access-log-"); + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); + executor.initialize(); + return executor; + } +} diff --git a/src/main/java/com/finance/system/config/SecurityConfig.java b/src/main/java/com/finance/system/config/SecurityConfig.java index 3e1ef38..88191c2 100644 --- a/src/main/java/com/finance/system/config/SecurityConfig.java +++ b/src/main/java/com/finance/system/config/SecurityConfig.java @@ -1,5 +1,6 @@ package com.finance.system.config; +import com.finance.system.security.ApiAccessLogFilter; import com.finance.system.security.JwtAuthenticationFilter; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; @@ -10,6 +11,7 @@ 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.boot.web.servlet.FilterRegistrationBean; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -24,6 +26,7 @@ import javax.servlet.http.HttpServletResponse; public class SecurityConfig { private final JwtAuthenticationFilter jwtAuthenticationFilter; + private final ApiAccessLogFilter apiAccessLogFilter; private final Environment environment; @Bean @@ -54,6 +57,7 @@ public class SecurityConfig { } )) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + .addFilterAfter(apiAccessLogFilter, UsernamePasswordAuthenticationFilter.class) .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); return http.build(); @@ -72,4 +76,12 @@ public class SecurityConfig { public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } + + /** Keep the filter only inside the security chain so each request is logged once. */ + @Bean + public FilterRegistrationBean disableApiAccessLogFilterRegistration(ApiAccessLogFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } } diff --git a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java index a299e95..0842aa1 100644 --- a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java +++ b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java @@ -4,7 +4,9 @@ import com.finance.system.adapter.feishu.FeishuDirectoryService; import com.finance.system.dto.ApiResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; +import com.finance.system.security.PermissionChecker; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.Map; @@ -13,6 +15,7 @@ import java.util.Map; @RequestMapping("/api/feishu/directory") public class FeishuDirectoryController { private final FeishuDirectoryService directory; + private final PermissionChecker permissions; @PostMapping("/sync") @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.feishu.directory.sync')") public ResponseEntity> sync() { @@ -24,8 +27,19 @@ public class FeishuDirectoryController { public ApiResponse> status() { return ApiResponse.success(directory.status()); } @GetMapping("/organization") + @PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')") + public ApiResponse> organization( + Authentication authentication, + @RequestParam(value = "includeUsers", defaultValue = "false") boolean includeUsers) { + boolean withUsers = includeUsers && permissions.has(authentication, "page.feishu-directory"); + return ApiResponse.success(directory.organization(withUsers)); + } + + @GetMapping("/organization/members") @PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory')") - public ApiResponse> organization() { - return ApiResponse.success(directory.organization()); + public ApiResponse> organizationMembers( + @RequestParam("departmentId") String departmentId, + @RequestParam(value = "includeDescendants", defaultValue = "true") boolean includeDescendants) { + return ApiResponse.success(directory.organizationMembers(departmentId, includeDescendants)); } } diff --git a/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java b/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java new file mode 100644 index 0000000..fa2dc57 --- /dev/null +++ b/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java @@ -0,0 +1,62 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.service.KingdeeAccountBindingService; +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; +import java.util.Map; + +@RestController +@RequestMapping("/api/kingdee/account-bindings") +@RequiredArgsConstructor +public class KingdeeAccountBindingController { + + private final KingdeeAccountBindingService service; + + @GetMapping + @PreAuthorize("@permissionChecker.hasAny(authentication, 'page.kingdee-account-binding', 'finance.kingdee.account.view-own', 'finance.kingdee.account.view-all')") + public ResponseEntity>>> list() { + return ResponseEntity.ok(ApiResponse.success(service.listBindings(AuditUtil.getCurrentUserId()))); + } + + @GetMapping("/me") + @PreAuthorize("@permissionChecker.hasAny(authentication, 'page.kingdee-account-binding', 'finance.kingdee.account.view-own', 'finance.kingdee.document.write')") + public ResponseEntity>> me() { + return ResponseEntity.ok(ApiResponse.success(service.myBinding(AuditUtil.getCurrentUserId()))); + } + + @PutMapping("/{userId}") + @PreAuthorize("@permissionChecker.hasAnyEdit(authentication, 'finance.kingdee.account.bind', 'finance.kingdee.account.bind-own')") + public ResponseEntity>> bind( + @PathVariable Long userId, + @RequestBody Map body) { + String username = body == null ? null : stringValue(body.get("kingdeeUsername")); + String password = body == null ? null : stringValue(body.get("kingdeePassword")); + boolean verify = body == null || body.get("verifyLogin") == null + || Boolean.parseBoolean(String.valueOf(body.get("verifyLogin"))); + return ResponseEntity.ok(ApiResponse.success( + service.bind(userId, username, password, AuditUtil.getCurrentUserId(), verify))); + } + + @DeleteMapping("/{userId}") + @PreAuthorize("@permissionChecker.hasAnyEdit(authentication, 'finance.kingdee.account.unbind', 'finance.kingdee.account.unbind-own')") + public ResponseEntity> unbind(@PathVariable Long userId) { + service.unbind(userId, AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success()); + } + + @PostMapping("/{userId}/test") + @PreAuthorize("@permissionChecker.hasAnyEdit(authentication, 'finance.kingdee.account.bind', 'finance.kingdee.account.bind-own')") + public ResponseEntity>> test(@PathVariable Long userId) { + return ResponseEntity.ok(ApiResponse.success(service.testBinding(userId, AuditUtil.getCurrentUserId()))); + } + + private String stringValue(Object value) { + return value == null ? null : String.valueOf(value); + } +} diff --git a/src/main/java/com/finance/system/controller/LogController.java b/src/main/java/com/finance/system/controller/LogController.java index 0cb7c97..0e0cfba 100644 --- a/src/main/java/com/finance/system/controller/LogController.java +++ b/src/main/java/com/finance/system/controller/LogController.java @@ -1,15 +1,24 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; -import com.finance.system.security.UserPrincipal; +import com.finance.system.service.ApiAccessLogService; +import com.finance.system.service.RoleService; import com.finance.system.util.AuditUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; -import java.util.*; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; @Slf4j @RestController @@ -17,82 +26,60 @@ import java.util.*; @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", " "); - } + private final ApiAccessLogService apiAccessLogService; + private final RoleService roleService; /** - * 获取操作日志列表 + * Lists persisted API access logs for the in-app operation log page. + * view-all sees everyone; view-own (or page only) is limited to the current operator. */ @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.operation-log')") + @PreAuthorize("@permissionChecker.hasAny(authentication, 'page.operation-log', 'system.operation-log.view-own', 'system.operation-log.view-all')") public ResponseEntity>>> listLogs( @RequestParam(required = false) String category, @RequestParam(required = false) String operator, - @RequestParam(defaultValue = "50") int limit) { + @RequestParam(defaultValue = "200") int limit) { try { - List> result = new ArrayList<>(MOCK_LOGS); + Long userId = AuditUtil.getCurrentUserId(); + boolean viewAll = roleService.hasPermission(userId, "system.operation-log.view-all"); + boolean viewOwn = roleService.hasPermission(userId, "system.operation-log.view-own") + || roleService.hasPermission(userId, "page.operation-log"); + if (!viewAll && !viewOwn) throw new AccessDeniedException("无权查看操作日志"); - if (category != null && !category.isEmpty()) { - result.removeIf(log -> !category.equals(log.get("category"))); + String scopedOperator = operator; + if (!viewAll) { + String selfName = AuditUtil.getCurrentUserRealName(); + if (StringUtils.hasText(operator) && selfName != null + && !"系统".equals(selfName) + && !operator.trim().equalsIgnoreCase(selfName.trim())) { + throw new AccessDeniedException("当前权限仅可查看本人操作日志"); + } + scopedOperator = "系统".equals(selfName) ? null : selfName; } - if (operator != null && !operator.isEmpty()) { - result.removeIf(log -> !operator.equals(log.get("operator"))); + List> rows = apiAccessLogService.list(category, scopedOperator, limit); + if (!viewAll && userId != null) { + String selfName = AuditUtil.getCurrentUserRealName(); + rows = rows.stream() + .filter(row -> Objects.equals(userId, asLong(row.get("operatorId"))) + || (selfName != null && selfName.equals(String.valueOf(row.get("operator"))))) + .collect(Collectors.toList()); } - - // 按时间倒序排列 - 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)); + return ResponseEntity.ok(ApiResponse.success(rows)); + } catch (AccessDeniedException e) { + throw e; } catch (Exception e) { log.error("获取操作日志列表失败", e); return ResponseEntity.ok(ApiResponse.error(500, "获取操作日志列表失败: " + e.getMessage())); } } + + private Long asLong(Object value) { + if (value instanceof Number) return ((Number) value).longValue(); + if (value == null) return null; + try { + return Long.parseLong(String.valueOf(value)); + } catch (NumberFormatException e) { + return null; + } + } } diff --git a/src/main/java/com/finance/system/controller/MetadataController.java b/src/main/java/com/finance/system/controller/MetadataController.java index b0875c6..c03a51e 100644 --- a/src/main/java/com/finance/system/controller/MetadataController.java +++ b/src/main/java/com/finance/system/controller/MetadataController.java @@ -1,6 +1,7 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; +import com.finance.system.repository.SysExpenseTypeRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; @@ -16,60 +17,7 @@ import java.util.stream.Collectors; @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); - } + private final SysExpenseTypeRepository expenseTypeRepository; /** * Mock数据 - 收款人 @@ -111,12 +59,17 @@ public class MetadataController { @GetMapping("/expense-types") @PreAuthorize("@permissionChecker.has(authentication, 'page.expense-types') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')") public ResponseEntity>>> getExpenseTypes() { - try { - return ResponseEntity.ok(ApiResponse.success(EXPENSE_TYPES)); - } catch (Exception e) { - log.error("获取费用类型列表失败", e); - return ResponseEntity.ok(ApiResponse.error(500, "获取费用类型列表失败: " + e.getMessage())); - } + List> result = expenseTypeRepository + .findByStatusIgnoreCaseOrderBySortOrderAscIdAsc("ACTIVE").stream().map(type -> { + Map value = new LinkedHashMap<>(); + value.put("id", type.getId()); + value.put("code", type.getTypeCode()); + value.put("name", type.getTypeName()); + value.put("category", type.getCategory()); + value.put("description", null); + return value; + }).collect(Collectors.toList()); + return ResponseEntity.ok(ApiResponse.success(result)); } /** diff --git a/src/main/java/com/finance/system/controller/ReimApplicationController.java b/src/main/java/com/finance/system/controller/ReimApplicationController.java index 380870c..d58b013 100644 --- a/src/main/java/com/finance/system/controller/ReimApplicationController.java +++ b/src/main/java/com/finance/system/controller/ReimApplicationController.java @@ -12,6 +12,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.http.MediaType; @RestController @RequestMapping("/api/v1/reimbursements") @@ -19,6 +21,32 @@ import org.springframework.web.bind.annotation.*; public class ReimApplicationController { private final ReimApplicationService reimApplicationService; + private final com.finance.system.service.ReimbursementFormService reimbursementFormService; + private final com.finance.system.service.ReimbursementAttachmentService reimbursementAttachmentService; + + @PostMapping(value = "/form-attachments", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.create') || @permissionChecker.hasEdit(authentication, 'reimbursement.application.edit')") + public ResponseEntity> uploadFormAttachment( + @RequestParam("file") MultipartFile file, + @RequestParam String formFingerprint, + @RequestParam String controlId) { + AttachmentDto value = reimbursementAttachmentService.upload(file, formFingerprint, controlId, + AuditUtil.getCurrentUserId()); + return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(value)); + } + + @DeleteMapping("/form-attachments/{id}") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.create') || @permissionChecker.hasEdit(authentication, 'reimbursement.application.edit')") + public ResponseEntity> deleteFormAttachment(@PathVariable Long id) { + reimbursementAttachmentService.remove(id, AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success()); + } + + @GetMapping("/form-definition") + @PreAuthorize("@permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')") + public ResponseEntity> formDefinition() { + return ResponseEntity.ok(ApiResponse.success(reimbursementFormService.currentDefinition())); + } @GetMapping("/workbench") @PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')" diff --git a/src/main/java/com/finance/system/dto/AttachmentDto.java b/src/main/java/com/finance/system/dto/AttachmentDto.java index 8958d93..106aa43 100644 --- a/src/main/java/com/finance/system/dto/AttachmentDto.java +++ b/src/main/java/com/finance/system/dto/AttachmentDto.java @@ -4,14 +4,18 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import com.fasterxml.jackson.annotation.JsonInclude; @Data @Builder @NoArgsConstructor @AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) public class AttachmentDto { private Long id; private String fileName; private String fileType; - private String fileUrl; -} \ No newline at end of file + private String contentType; + private Long fileSize; + private Long expenseItemId; +} diff --git a/src/main/java/com/finance/system/dto/CreateApplicationRequest.java b/src/main/java/com/finance/system/dto/CreateApplicationRequest.java index 93597ed..3859ed5 100644 --- a/src/main/java/com/finance/system/dto/CreateApplicationRequest.java +++ b/src/main/java/com/finance/system/dto/CreateApplicationRequest.java @@ -4,6 +4,7 @@ import lombok.Data; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; +import java.util.Map; @Data public class CreateApplicationRequest { @@ -15,4 +16,6 @@ public class CreateApplicationRequest { private String payeeName; private Long payeeBankId; private List items; -} \ No newline at end of file + private String formFingerprint; + private Map formValues; +} diff --git a/src/main/java/com/finance/system/dto/ExpenseItemDto.java b/src/main/java/com/finance/system/dto/ExpenseItemDto.java index b6ca4a2..a8d3520 100644 --- a/src/main/java/com/finance/system/dto/ExpenseItemDto.java +++ b/src/main/java/com/finance/system/dto/ExpenseItemDto.java @@ -6,6 +6,8 @@ import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; @Data @Builder @@ -18,4 +20,9 @@ public class ExpenseItemDto { private String category; private String description; private BigDecimal amount; -} \ No newline at end of file + @Builder.Default + private List attachmentIds = new ArrayList<>(); + /** Safe display metadata for attachments claimed by this expense row. */ + @Builder.Default + private List attachments = new ArrayList<>(); +} diff --git a/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java b/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java index 838ff2b..56f339e 100644 --- a/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java +++ b/src/main/java/com/finance/system/dto/FeishuDefinitionSyncResult.java @@ -8,5 +8,12 @@ public class FeishuDefinitionSyncResult { private String fingerprint; private LocalDateTime fetchedAt; private int nodeCount; + private String formFingerprint; + private int formFieldCount; private boolean changed; + /** Human-readable outcome for 配置管理 UI. */ + private String message; + private String approvalCode; + /** true when subscribe API newly registered; false when already subscribed. */ + private Boolean eventSubscribed; } diff --git a/src/main/java/com/finance/system/dto/ReimApplicationDetail.java b/src/main/java/com/finance/system/dto/ReimApplicationDetail.java index a8aa94e..c55d685 100644 --- a/src/main/java/com/finance/system/dto/ReimApplicationDetail.java +++ b/src/main/java/com/finance/system/dto/ReimApplicationDetail.java @@ -8,6 +8,7 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; @Data @Builder @@ -54,4 +55,13 @@ public class ReimApplicationDetail { private List attachments; private List approvalRecords; private List payments; -} \ No newline at end of file + private FormSnapshot formSnapshot; + + @Data @Builder @NoArgsConstructor @AllArgsConstructor + public static class FormSnapshot { + private String mode; + private String fingerprint; + private List fields; + private Map values; + } +} diff --git a/src/main/java/com/finance/system/dto/ReimbursementFormDefinition.java b/src/main/java/com/finance/system/dto/ReimbursementFormDefinition.java new file mode 100644 index 0000000..3ba6f7c --- /dev/null +++ b/src/main/java/com/finance/system/dto/ReimbursementFormDefinition.java @@ -0,0 +1,15 @@ +package com.finance.system.dto; + +import lombok.*; +import java.time.LocalDateTime; +import java.util.*; + +@Data @Builder @NoArgsConstructor @AllArgsConstructor +public class ReimbursementFormDefinition { + private String mode; + private String approvalCode; + private String definitionFingerprint; + private String formFingerprint; + private LocalDateTime fetchedAt; + @Builder.Default private List fields = new ArrayList<>(); +} diff --git a/src/main/java/com/finance/system/dto/ReimbursementFormField.java b/src/main/java/com/finance/system/dto/ReimbursementFormField.java new file mode 100644 index 0000000..e49f83f --- /dev/null +++ b/src/main/java/com/finance/system/dto/ReimbursementFormField.java @@ -0,0 +1,30 @@ +package com.finance.system.dto; + +import lombok.*; +import java.util.*; + +/** Sanitized, provider-neutral form control. No raw Feishu response is retained. */ +@Data @Builder @NoArgsConstructor @AllArgsConstructor +public class ReimbursementFormField { + private String id; + private String customId; + /** Stable request value key: custom_id for top-level custom controls, otherwise provider id. */ + private String valueKey; + private String providerType; + private String type; + private String binding; + private String label; + private boolean required; + private boolean readOnly; + private Integer maxLength; + /** Fixed system currency for an amount control; currently only CNY is supported. */ + private String currency; + @Builder.Default private List