审批接入
This commit is contained in:
1 parent
3a3f0d2585
commit
52fb651e3e
58 files changed
+4414
-744
No files matched your search
@@ -112,6 +112,12 @@
|
|||||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -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<String,Object> 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<JsonNode> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,82 +1,354 @@
|
|||||||
package com.finance.system.adapter.feishu;
|
package com.finance.system.adapter.feishu;
|
||||||
|
|
||||||
import com.finance.system.entity.ReimApplication;
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
import com.finance.system.entity.ReimExpenseItem;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.finance.system.entity.SysUser;
|
import com.finance.system.dto.ReimbursementFormField;
|
||||||
import com.finance.system.entity.SysDepartment;
|
import com.finance.system.entity.*;
|
||||||
import com.finance.system.entity.SysExpenseType;
|
import com.finance.system.exception.BusinessException;
|
||||||
|
import com.finance.system.util.Sha256;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.util.LinkedHashMap;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.List;
|
import java.time.*;
|
||||||
import java.util.Map;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.stream.Collectors;
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/** 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;
|
||||||
public class FeishuApprovalFormBuilder {
|
private FeishuApprovalFormBuilder() { }
|
||||||
|
|
||||||
/**
|
public static String buildFormJson(ReimApplication app) {
|
||||||
* 构建审批表单数据
|
if (!StringUtils.hasText(app.getFeishuFormFingerprint()) || !StringUtils.hasText(app.getFeishuFormSchema()))
|
||||||
*/
|
throw new BusinessException("报销申请缺少已固定的飞书表单快照,禁止创建远程审批", 409);
|
||||||
public static Map<String, String> buildForm(ReimApplication app, SysUser applicant,
|
if (!app.getFeishuFormFingerprint().equals(Sha256.hex(app.getFeishuFormSchema())))
|
||||||
SysDepartment department, SysExpenseType expenseType,
|
throw new BusinessException("报销申请的飞书表单快照校验失败", 409);
|
||||||
List<ReimExpenseItem> items) {
|
if (!StringUtils.hasText(app.getFeishuFormDisplayValues()))
|
||||||
Map<String, String> form = new LinkedHashMap<>();
|
throw new BusinessException("报销申请缺少不可变的飞书展示值快照", 409);
|
||||||
|
try {
|
||||||
// 基本字段
|
requireSize(app.getFeishuFormSchema(), "飞书表单快照过大");
|
||||||
form.put("application_no", app.getApplicationNo());
|
requireSize(app.getFeishuFormValues(), "飞书自定义表单值过大");
|
||||||
form.put("title", app.getTitle());
|
requireSize(app.getFeishuFormDisplayValues(), "飞书展示值快照过大");
|
||||||
form.put("applicant_name", applicant != null ? applicant.getRealName() : "");
|
List<ReimbursementFormField> fields = JSON.readValue(app.getFeishuFormSchema(),
|
||||||
form.put("department", department != null ? department.getDeptName() : "");
|
new TypeReference<List<ReimbursementFormField>>() { });
|
||||||
form.put("expense_type", expenseType != null ? expenseType.getTypeName() : "");
|
Map<String,Object> custom = StringUtils.hasText(app.getFeishuFormValues())
|
||||||
form.put("total_amount", app.getTotalAmount() != null ? app.getTotalAmount().toString() : "0");
|
? JSON.readValue(app.getFeishuFormValues(), new TypeReference<LinkedHashMap<String,Object>>() { })
|
||||||
form.put("description", app.getDescription() != null ? app.getDescription() : "");
|
: Collections.emptyMap();
|
||||||
form.put("source_doc_no", app.getSourceDocNo() != null ? app.getSourceDocNo() : "");
|
Map<String,Object> display = JSON.readValue(app.getFeishuFormDisplayValues(),
|
||||||
|
new TypeReference<LinkedHashMap<String,Object>>() { });
|
||||||
// 费用明细(多行文本展示)
|
validateDisplaySnapshot(fields, display);
|
||||||
if (items != null && !items.isEmpty()) {
|
validateTotals(fields, display, app.getTotalAmount());
|
||||||
String itemDetail = ReimbursementCanonicalizer.orderedItems(items).stream()
|
List<Map<String,Object>> controls = new ArrayList<>();
|
||||||
.map(item -> String.format("%s | %s | ¥%.2f",
|
appendControls(controls, fields, custom, display);
|
||||||
item.getExpenseDate() != null ? item.getExpenseDate().toString() : "",
|
String result = JSON.writeValueAsString(controls);
|
||||||
item.getDescription() != null ? item.getDescription() : "",
|
requireSize(result, "飞书审批表单过大");
|
||||||
item.getAmount() != null ? item.getAmount() : BigDecimal.ZERO))
|
return result;
|
||||||
.collect(Collectors.joining("\n"));
|
} catch (BusinessException e) { throw e; }
|
||||||
form.put("expense_items", itemDetail);
|
catch (Exception e) { throw new BusinessException("报销申请的飞书表单快照无效", 409); }
|
||||||
}
|
}
|
||||||
|
|
||||||
return form;
|
/** Compatibility overload; mutable master data and line entities are deliberately ignored. */
|
||||||
|
public static String buildFormJson(ReimApplication app, SysUser applicant, SysDepartment department,
|
||||||
|
SysExpenseType expenseType, List<ReimExpenseItem> items) {
|
||||||
|
return buildFormJson(app);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private static void appendControls(List<Map<String,Object>> out, List<ReimbursementFormField> fields,
|
||||||
* 构建飞书审批表单(用于创建审批实例的API请求)
|
Map<String,Object> custom, Map<String,Object> display) {
|
||||||
*/
|
for (ReimbursementFormField field : fields) {
|
||||||
public static String buildFormJson(Map<String, String> formData) {
|
boolean bound = !"CUSTOM".equals(field.getBinding());
|
||||||
StringBuilder json = new StringBuilder("{");
|
if ((field.isReadOnly() && !"CONTACT".equals(field.getType()) && !"DEPARTMENT".equals(field.getType())
|
||||||
boolean first = true;
|
&& !"FORMULA".equals(field.getType())) || "DISPLAY".equals(field.getType())
|
||||||
for (Map.Entry<String, String> entry : formData.entrySet()) {
|
|| "text".equalsIgnoreCase(field.getProviderType())) continue;
|
||||||
if (!first) {
|
Object value = bound ? display.get(field.getValueKey()) : custom.get(field.getValueKey());
|
||||||
json.append(",");
|
if (isEmpty(value)) {
|
||||||
|
if (field.isRequired() || "CONTACT".equals(field.getType()) || "DEPARTMENT".equals(field.getType()))
|
||||||
|
throw new BusinessException("飞书必填表单字段缺少快照值: " + field.getLabel(), 409);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
json.append("\"")
|
requireIdentity(field);
|
||||||
.append(escapeJson(entry.getKey()))
|
if ("CONTACT".equals(field.getType())) {
|
||||||
.append("\":\"")
|
out.add(contactControl(field, value));
|
||||||
.append(escapeJson(entry.getValue() != null ? entry.getValue() : ""))
|
continue;
|
||||||
.append("\"");
|
}
|
||||||
first = false;
|
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<String,Object> 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) {
|
private static List<List<Map<String,Object>>> expenseRows(ReimbursementFormField parent, Object snapshot, Map<String,Object> custom) {
|
||||||
if (value == null) return "";
|
if (!(snapshot instanceof List)) throw new BusinessException("费用明细展示值快照无效", 409);
|
||||||
return value.replace("\\", "\\\\")
|
List<List<Map<String,Object>>> result = new ArrayList<>();
|
||||||
.replace("\"", "\\\"")
|
for (Object rowValue : (List<?>)snapshot) {
|
||||||
.replace("\n", "\\n")
|
if (!(rowValue instanceof Map)) throw new BusinessException("费用明细展示值快照无效", 409);
|
||||||
.replace("\r", "\\r")
|
Map<?,?> source = (Map<?,?>)rowValue; List<Map<String,Object>> row = new ArrayList<>();
|
||||||
.replace("\t", "\\t");
|
for (ReimbursementFormField child : parent.getChildren() == null
|
||||||
|
? Collections.<ReimbursementFormField>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<String,Object> 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<ReimbursementFormField> fields, Map<String,Object> display) {
|
||||||
|
if (fields == null || display == null) throw new BusinessException("飞书展示值快照无效", 409);
|
||||||
|
Map<String,ReimbursementFormField> 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<String,ReimbursementFormField> 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<String> 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<String> optionValues(ReimbursementFormField field) {
|
||||||
|
Set<String> 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<String> attachmentCodes(ReimbursementFormField field, Object value) {
|
||||||
|
if (!(value instanceof List) || ((List<?>)value).size() > 50) throw invalid(field);
|
||||||
|
List<String> codes = new ArrayList<>();
|
||||||
|
Set<String> 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<ReimbursementFormField> fields, Map<String,Object> 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<String,Object> contactControl(ReimbursementFormField field, Object snapshot) {
|
||||||
|
Map<?,?> contact = validateContactSnapshot(field, snapshot);
|
||||||
|
Map<String,Object> 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<String,Object> departmentControl(ReimbursementFormField field, Object snapshot) {
|
||||||
|
Map<?,?> department = validateDepartmentSnapshot(field, snapshot);
|
||||||
|
List<Map<String,Object>> providerValue = new ArrayList<>();
|
||||||
|
for (Object id : (List<?>)department.get("open_department_ids")) {
|
||||||
|
Map<String,Object> item = new LinkedHashMap<>();
|
||||||
|
item.put("open_id", id);
|
||||||
|
providerValue.add(item);
|
||||||
|
}
|
||||||
|
Map<String,Object> 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<String> 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); }
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.finance.system.adapter.feishu;
|
package com.finance.system.adapter.feishu;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
@@ -13,7 +14,7 @@ import java.util.List;
|
|||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class FeishuApprovalResponse {
|
public class FeishuApprovalResponse {
|
||||||
|
|
||||||
private int code;
|
private Integer code;
|
||||||
private String msg;
|
private String msg;
|
||||||
private Data data;
|
private Data data;
|
||||||
|
|
||||||
@@ -22,10 +23,12 @@ public class FeishuApprovalResponse {
|
|||||||
public static class Data {
|
public static class Data {
|
||||||
/** 审批实例编码 */
|
/** 审批实例编码 */
|
||||||
@JsonProperty("instance_code")
|
@JsonProperty("instance_code")
|
||||||
|
@JsonAlias({"instance_id", "instanceCode"})
|
||||||
private String instanceCode;
|
private String instanceCode;
|
||||||
|
|
||||||
/** 审批定义编码 */
|
/** 审批定义编码 */
|
||||||
@JsonProperty("approval_code")
|
@JsonProperty("approval_code")
|
||||||
|
@JsonAlias("approvalCode")
|
||||||
private String approvalCode;
|
private String approvalCode;
|
||||||
|
|
||||||
/** 审批状态 PENDING/APPROVED/REJECTED/CANCELED/TERMINATED */
|
/** 审批状态 PENDING/APPROVED/REJECTED/CANCELED/TERMINATED */
|
||||||
@@ -41,6 +44,10 @@ public class FeishuApprovalResponse {
|
|||||||
/** 审批时间线 */
|
/** 审批时间线 */
|
||||||
private List<TimelineNode> timeline;
|
private List<TimelineNode> timeline;
|
||||||
|
|
||||||
|
/** v4 审批任务列表,作为审批进度的结构化来源。 */
|
||||||
|
@JsonProperty("task_list")
|
||||||
|
private List<ApprovalTask> taskList;
|
||||||
|
|
||||||
/** 审批定义名称 */
|
/** 审批定义名称 */
|
||||||
@JsonProperty("approval_name")
|
@JsonProperty("approval_name")
|
||||||
private String approvalName;
|
private String approvalName;
|
||||||
@@ -49,16 +56,56 @@ public class FeishuApprovalResponse {
|
|||||||
private Object form;
|
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
|
@lombok.Data
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public static class ApprovalNode {
|
public static class ApprovalNode {
|
||||||
|
@JsonProperty("node_id")
|
||||||
|
@JsonAlias({"id", "nodeId"})
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
|
@JsonProperty("node_name")
|
||||||
|
@JsonAlias({"name", "nodeName"})
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
/** AND/OR */
|
/** AND/OR */
|
||||||
|
@JsonProperty("node_type")
|
||||||
|
@JsonAlias({"type", "nodeType"})
|
||||||
private String type;
|
private String type;
|
||||||
|
|
||||||
/** 审批人列表 */
|
/** 审批人列表 */
|
||||||
@@ -124,6 +171,32 @@ public class FeishuApprovalResponse {
|
|||||||
|
|
||||||
/** 审批时间 */
|
/** 审批时间 */
|
||||||
@JsonProperty("action_time")
|
@JsonProperty("action_time")
|
||||||
|
@JsonAlias({"create_time", "actionTime"})
|
||||||
private String 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<String> userIdList;
|
||||||
|
|
||||||
|
@JsonProperty("open_id_list")
|
||||||
|
private List<String> openIdList;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,9 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
import org.springframework.web.client.RestClientResponseException;
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.util.UriComponentsBuilder;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -37,9 +39,6 @@ public class FeishuApprovalService {
|
|||||||
private final FeishuConfig feishuConfig;
|
private final FeishuConfig feishuConfig;
|
||||||
private final FeishuAuthService feishuAuthService;
|
private final FeishuAuthService feishuAuthService;
|
||||||
private final SysUserRepository sysUserRepository;
|
private final SysUserRepository sysUserRepository;
|
||||||
private final SysDepartmentRepository sysDepartmentRepository;
|
|
||||||
private final SysExpenseTypeRepository sysExpenseTypeRepository;
|
|
||||||
private final ReimExpenseItemRepository reimExpenseItemRepository;
|
|
||||||
private final IntFeishuApprovalRepository intFeishuApprovalRepository;
|
private final IntFeishuApprovalRepository intFeishuApprovalRepository;
|
||||||
private final ReimApplicationRepository reimApplicationRepository;
|
private final ReimApplicationRepository reimApplicationRepository;
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
@@ -86,52 +85,52 @@ public class FeishuApprovalService {
|
|||||||
* 包括审批流程的所有节点、审批人配置、表单定义
|
* 包括审批流程的所有节点、审批人配置、表单定义
|
||||||
*/
|
*/
|
||||||
public FeishuApprovalResponse getApprovalDefinition() {
|
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<String, String> requestBody = new HashMap<>();
|
|
||||||
requestBody.put("approval_code", approvalCode());
|
|
||||||
|
|
||||||
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ResponseEntity<FeishuApprovalResponse> response = restTemplate.exchange(
|
return JSON.treeToValue(fetchApprovalDefinitionResponse(), FeishuApprovalResponse.class);
|
||||||
url, HttpMethod.POST, request, FeishuApprovalResponse.class);
|
} catch (BusinessException e) {
|
||||||
FeishuApprovalResponse resp = response.getBody();
|
throw e;
|
||||||
if (resp != null && resp.getCode() != 0) {
|
|
||||||
throw new BusinessException("获取飞书审批定义失败: " + resp.getMsg());
|
|
||||||
}
|
|
||||||
return resp;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取飞书审批定义失败", e);
|
log.warn("飞书审批定义响应解析失败: httpStatus=200, providerCode=0, requestId=unknown");
|
||||||
throw new BusinessException("获取审批节点信息失败,请检查飞书权限配置");
|
throw new BusinessException("飞书审批定义响应格式无效", 502);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Raw transport response for server-side normalization only. Never expose this from a controller. */
|
/** Raw transport response for server-side normalization only. Never expose this from a controller. */
|
||||||
public JsonNode fetchApprovalDefinitionJson() {
|
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();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
headers.setBearerAuth(token);
|
headers.setBearerAuth(feishuAuthService.getTenantAccessToken());
|
||||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||||
Map<String, String> body = Collections.singletonMap("approval_code", approvalCode());
|
|
||||||
try {
|
try {
|
||||||
ResponseEntity<JsonNode> response = restTemplate.exchange(
|
ResponseEntity<JsonNode> response = restTemplate.exchange(
|
||||||
FEISHU_OPEN_API + "/approval/openapi/v2/approval/get", HttpMethod.POST,
|
uri, HttpMethod.GET, new HttpEntity<Void>(headers), JsonNode.class);
|
||||||
new HttpEntity<>(body, headers), JsonNode.class);
|
|
||||||
JsonNode value = response.getBody();
|
JsonNode value = response.getBody();
|
||||||
if (value == null || value.path("code").asInt(-1) != 0) {
|
Integer providerCode = providerCode(value);
|
||||||
throw new BusinessException("飞书审批定义同步失败", 502);
|
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;
|
return value;
|
||||||
} catch (BusinessException e) {
|
} catch (BusinessException e) {
|
||||||
throw 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) {
|
} catch (Exception e) {
|
||||||
log.warn("飞书审批定义请求失败: {}", e.getClass().getSimpleName());
|
logDefinitionFailure(null, null, null);
|
||||||
throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502);
|
throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,6 +139,51 @@ public class FeishuApprovalService {
|
|||||||
return approvalCode();
|
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<JsonNode> response = restTemplate.exchange(
|
||||||
|
uri, HttpMethod.POST, new HttpEntity<Void>(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. */
|
/** Built in Phase A while the application row is locked, then persisted verbatim. */
|
||||||
public String buildCreatePayload(Long applicationId, String requestUuid, String intendedApprovalCode) {
|
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)
|
ReimApplication application = reimApplicationRepository.findById(applicationId)
|
||||||
.orElseThrow(() -> new BusinessException("报销申请不存在,无法创建飞书审批", 400));
|
.orElseThrow(() -> new BusinessException("报销申请不存在,无法创建飞书审批", 400));
|
||||||
SysUser applicant = application.getApplicantId() == null ? null
|
SysUser applicant = application.getApplicantId() == null ? null
|
||||||
@@ -169,17 +216,15 @@ public class FeishuApprovalService {
|
|||||||
if (applicant == null || (!StringUtils.hasText(applicant.getFeishuUserId())
|
if (applicant == null || (!StringUtils.hasText(applicant.getFeishuUserId())
|
||||||
&& !StringUtils.hasText(applicant.getFeishuOpenId())))
|
&& !StringUtils.hasText(applicant.getFeishuOpenId())))
|
||||||
throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 400);
|
throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 400);
|
||||||
SysDepartment department = application.getDepartmentId() == null ? null
|
String formJson = FeishuApprovalFormBuilder.buildFormJson(application);
|
||||||
: sysDepartmentRepository.findById(application.getDepartmentId()).orElse(null);
|
|
||||||
SysExpenseType expenseType = application.getExpenseTypeId() == null ? null
|
|
||||||
: sysExpenseTypeRepository.findById(application.getExpenseTypeId()).orElse(null);
|
|
||||||
List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(applicationId);
|
|
||||||
String formJson = FeishuApprovalFormBuilder.buildFormJson(
|
|
||||||
FeishuApprovalFormBuilder.buildForm(application, applicant, department, expenseType, items));
|
|
||||||
Map<String, Object> body = new LinkedHashMap<>();
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
body.put("approval_code", intendedApprovalCode);
|
body.put("approval_code", normalizedApprovalCode);
|
||||||
body.put("user_id", applicant.getFeishuUserId() == null ? "" : applicant.getFeishuUserId());
|
if (StringUtils.hasText(applicant.getFeishuUserId())) {
|
||||||
body.put("open_id", applicant.getFeishuOpenId() == null ? "" : applicant.getFeishuOpenId());
|
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);
|
body.put("form", formJson); body.put("uuid", requestUuid);
|
||||||
try {
|
try {
|
||||||
String json = JSON.writeValueAsString(body);
|
String json = JSON.writeValueAsString(body);
|
||||||
@@ -197,33 +242,51 @@ public class FeishuApprovalService {
|
|||||||
try { body = JSON.readValue(persistedPayload, new TypeReference<Map<String,Object>>() {}); }
|
try { body = JSON.readValue(persistedPayload, new TypeReference<Map<String,Object>>() {}); }
|
||||||
catch (Exception e) { throw new BusinessException("飞书审批创建载荷无效", 500); }
|
catch (Exception e) { throw new BusinessException("飞书审批创建载荷无效", 500); }
|
||||||
if (!Objects.equals(requestUuid, body.get("uuid"))) 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());
|
HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(feishuAuthService.getTenantAccessToken());
|
||||||
headers.setContentType(MediaType.APPLICATION_JSON); headers.set("X-Request-ID", requestUuid);
|
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 {
|
try {
|
||||||
ResponseEntity<FeishuApprovalResponse> response = restTemplate.exchange(
|
ResponseEntity<JsonNode> response = restTemplate.exchange(
|
||||||
FEISHU_OPEN_API + "/approval/openapi/v2/instance/create", HttpMethod.POST,
|
uri, HttpMethod.POST,
|
||||||
new HttpEntity<>(body, headers), FeishuApprovalResponse.class);
|
new HttpEntity<>(body, headers), JsonNode.class);
|
||||||
FeishuApprovalResponse value = response.getBody();
|
JsonNode value = response.getBody();
|
||||||
if (value == null) throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试");
|
Integer code = providerCode(value);
|
||||||
if (value.getCode() != 0) throw new BusinessException("创建飞书审批失败: " + value.getMsg(), 502);
|
String responseRequestId = requestId(response.getHeaders(), value);
|
||||||
if (value.getData() == null || !StringUtils.hasText(value.getData().getInstanceCode()))
|
if (value == null || code == null) {
|
||||||
|
logProviderFailure("create", response.getStatusCodeValue(), code, responseRequestId);
|
||||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试");
|
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("飞书已响应创建但实例标识无效,禁止修改原申请");
|
throw new FeishuCreateOutcomeUnknownException("飞书已响应创建但实例标识无效,禁止修改原申请");
|
||||||
|
}
|
||||||
return instance;
|
return instance;
|
||||||
} catch (FeishuCreateOutcomeUnknownException e) {
|
} catch (FeishuCreateOutcomeUnknownException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (BusinessException e) { throw e;
|
} catch (BusinessException e) { throw e;
|
||||||
} catch (RestClientResponseException e) {
|
} catch (RestClientResponseException e) {
|
||||||
int status = e.getRawStatusCode();
|
int status = e.getRawStatusCode();
|
||||||
if (status == 408 || status == 409 || status == 425 || status == 429 || status >= 500)
|
JsonNode error = parseJson(e.getResponseBodyAsString(StandardCharsets.UTF_8));
|
||||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
Integer code = providerCode(error);
|
||||||
if (status >= 400 && status < 500)
|
logProviderFailure("create", status, code, requestId(e.getResponseHeaders(), error));
|
||||||
throw new BusinessException("飞书拒绝创建审批实例", 502);
|
throw classifyCreateFailure(status, code, e);
|
||||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("飞书审批远程创建失败: {}", e.getClass().getSimpleName());
|
logProviderFailure("create", null, null, null);
|
||||||
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
throw new FeishuCreateOutcomeUnknownException("飞书创建结果未知,请使用原请求重试", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,29 +298,46 @@ public class FeishuApprovalService {
|
|||||||
* 包含审批进度、各节点状态、审批意见
|
* 包含审批进度、各节点状态、审批意见
|
||||||
*/
|
*/
|
||||||
public FeishuApprovalResponse getApprovalInstanceDetail(String instanceCode) {
|
public FeishuApprovalResponse getApprovalInstanceDetail(String instanceCode) {
|
||||||
String token = feishuAuthService.getTenantAccessToken();
|
if (!StringUtils.hasText(instanceCode)) throw new BusinessException("飞书审批实例标识不能为空", 400);
|
||||||
String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/get";
|
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();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
headers.setBearerAuth(token);
|
headers.setBearerAuth(feishuAuthService.getTenantAccessToken());
|
||||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||||
|
|
||||||
Map<String, String> requestBody = new HashMap<>();
|
|
||||||
requestBody.put("instance_code", instanceCode);
|
|
||||||
|
|
||||||
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ResponseEntity<FeishuApprovalResponse> response = restTemplate.exchange(
|
ResponseEntity<JsonNode> response = restTemplate.exchange(
|
||||||
url, HttpMethod.POST, request, FeishuApprovalResponse.class);
|
uri, HttpMethod.GET, new HttpEntity<Void>(headers), JsonNode.class);
|
||||||
FeishuApprovalResponse resp = response.getBody();
|
JsonNode value = response.getBody();
|
||||||
if (resp != null && resp.getCode() != 0) {
|
Integer code = providerCode(value);
|
||||||
throw new BusinessException("获取审批实例详情失败: " + resp.getMsg());
|
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) {
|
} catch (Exception e) {
|
||||||
log.error("获取审批实例详情失败: instanceCode={}", instanceCode, e);
|
logProviderFailure("detail", response.getStatusCodeValue(), code,
|
||||||
throw new BusinessException("获取审批进度失败");
|
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) {
|
||||||
|
logProviderFailure("detail", null, null, null);
|
||||||
|
throw new BusinessException("获取飞书审批进度失败,请稍后重试", 502);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,7 +347,11 @@ public class FeishuApprovalService {
|
|||||||
public List<FeishuApprovalResponse.TimelineNode> getApprovalTimeline(String instanceCode) {
|
public List<FeishuApprovalResponse.TimelineNode> getApprovalTimeline(String instanceCode) {
|
||||||
FeishuApprovalResponse detail = getApprovalInstanceDetail(instanceCode);
|
FeishuApprovalResponse detail = getApprovalInstanceDetail(instanceCode);
|
||||||
if (detail != null && detail.getData() != null) {
|
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();
|
return Collections.emptyList();
|
||||||
}
|
}
|
||||||
@@ -513,6 +597,172 @@ public class FeishuApprovalService {
|
|||||||
return integrationConfigReader == null ? fallback : integrationConfigReader.get("FEISHU", "approvalCode");
|
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<FeishuApprovalResponse.TimelineNode> taskProgress(
|
||||||
|
List<FeishuApprovalResponse.ApprovalTask> tasks,
|
||||||
|
List<FeishuApprovalResponse.TimelineNode> timeline) {
|
||||||
|
List<FeishuApprovalResponse.TimelineNode> progress = new ArrayList<>(
|
||||||
|
tasks.size() + (timeline == null ? 0 : timeline.size()));
|
||||||
|
Map<String, FeishuApprovalResponse.TimelineNode> taskTemplates = new LinkedHashMap<>();
|
||||||
|
Map<String, FeishuApprovalResponse.TimelineNode> 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<String> 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) {
|
private String configValue(String key, String fallback) {
|
||||||
if (integrationConfigReader == null) return fallback;
|
if (integrationConfigReader == null) return fallback;
|
||||||
String value = integrationConfigReader.get("FEISHU", key);
|
String value = integrationConfigReader.get("FEISHU", key);
|
||||||
@@ -527,7 +777,10 @@ public class FeishuApprovalService {
|
|||||||
private String normalizeApprovalStatus(String status) {
|
private String normalizeApprovalStatus(String status) {
|
||||||
if (!StringUtils.hasText(status)) return null;
|
if (!StringUtils.hasText(status)) return null;
|
||||||
String normalized = status.trim().toUpperCase(Locale.ROOT);
|
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()) {
|
for (ApprovalStatus known : ApprovalStatus.values()) {
|
||||||
if (known.name().equals(normalized)) return normalized;
|
if (known.name().equals(normalized)) return normalized;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,13 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
@ConfigurationProperties(prefix = "feishu")
|
@ConfigurationProperties(prefix = "feishu")
|
||||||
public class FeishuConfig {
|
public class FeishuConfig {
|
||||||
|
/** Master switch for Feishu OAuth / approval / directory token use. */
|
||||||
|
private boolean enabled = true;
|
||||||
private String appId;
|
private String appId;
|
||||||
private String appSecret;
|
private String appSecret;
|
||||||
private String redirectUri;
|
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
|
* Legacy setting retained for configuration compatibility. OAuth no
|
||||||
* longer has a local bootstrap exception and always provisions an
|
* longer has a local bootstrap exception and always provisions an
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.finance.system.adapter.feishu;
|
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 com.finance.system.util.Sha256;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -8,69 +10,363 @@ import org.springframework.util.StringUtils;
|
|||||||
|
|
||||||
import java.util.*;
|
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
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class FeishuDefinitionNormalizer {
|
public class FeishuDefinitionNormalizer {
|
||||||
private static final int MAX_NODES = 100;
|
private static final int MAX_NODES = 100, MAX_APPROVERS = 50;
|
||||||
private static final int MAX_APPROVERS = 50;
|
private static final int MAX_CONTROLS = 200, MAX_DEPTH = 5, MAX_OPTIONS = 500;
|
||||||
|
private static final Set<String> 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<String> APPLICANT_CONTACT_IDS = new HashSet<>(Arrays.asList(
|
||||||
|
"applicant", "applicant_user", "applicant_name", "applicant_contact",
|
||||||
|
"reimbursement_applicant"));
|
||||||
|
private static final Set<String> 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) {
|
public NormalizedDefinition normalize(JsonNode response, String configuredApprovalCode) {
|
||||||
JsonNode data = response == null ? null : response.path("data");
|
JsonNode data = response == null ? null : response.path("data");
|
||||||
if (data == null || data.isMissingNode() || data.isNull()) data = response;
|
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);
|
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");
|
throw new IllegalArgumentException("Feishu approval definition has no usable nodes");
|
||||||
}
|
|
||||||
String code = displayText(findDeep(data, 0, "approval_code", "approvalCode"));
|
String code = displayText(findDeep(data, 0, "approval_code", "approvalCode"));
|
||||||
if (!StringUtils.hasText(code)) code = configuredApprovalCode;
|
if (!StringUtils.hasText(code)) code = configuredApprovalCode;
|
||||||
if (!StringUtils.hasText(code)) throw new IllegalArgumentException("Feishu approval code is missing");
|
if (!StringUtils.hasText(code)) throw new IllegalArgumentException("Feishu approval code is missing");
|
||||||
String name = displayText(findDeep(data, 0, "approval_name", "approvalName"));
|
String name = displayText(findDeep(data, 0, "approval_name", "approvalName"));
|
||||||
code = bounded(code, 200);
|
code = bounded(code, 200); name = bounded(name, 300);
|
||||||
name = bounded(name, 300);
|
|
||||||
|
|
||||||
List<NormalizedNode> nodes = new ArrayList<>();
|
List<NormalizedNode> nodes = new ArrayList<>(); int order = 1;
|
||||||
int order = 1;
|
|
||||||
for (JsonNode raw : nodesJson) {
|
for (JsonNode raw : nodesJson) {
|
||||||
if (order > MAX_NODES) throw new IllegalArgumentException("too many Feishu approval nodes");
|
if (order > MAX_NODES) throw new IllegalArgumentException("too many Feishu approval nodes");
|
||||||
if (!raw.isObject()) continue;
|
if (!raw.isObject()) continue;
|
||||||
String key = firstText(raw, "node_id", "nodeId", "id", "key", "node_key");
|
String key = firstText(raw, "node_id", "nodeId", "id", "key", "node_key");
|
||||||
if (!StringUtils.hasText(key)) key = "node-" + order;
|
if (!StringUtils.hasText(key)) key = "node-" + order;
|
||||||
key = bounded(key, 300);
|
|
||||||
String nodeName = displayText(first(raw, "node_name", "nodeName", "name", "title"));
|
String nodeName = displayText(first(raw, "node_name", "nodeName", "name", "title"));
|
||||||
if (!StringUtils.hasText(nodeName)) nodeName = "审批节点 " + order;
|
if (!StringUtils.hasText(nodeName)) nodeName = "审批节点 " + order;
|
||||||
nodeName = bounded(nodeName, 300);
|
|
||||||
String rawType = firstText(raw, "node_type", "nodeType", "type");
|
String rawType = firstText(raw, "node_type", "nodeType", "type");
|
||||||
String mode = firstText(raw, "approval_mode", "approvalMode", "mode");
|
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);
|
mode = rawType.toUpperCase(Locale.ROOT);
|
||||||
}
|
List<NormalizedApprover> nodeApprovers = normalizeApprovers(raw);
|
||||||
List<NormalizedApprover> approvers = normalizeApprovers(raw);
|
boolean dynamic = isDynamicNode(raw, nodeApprovers);
|
||||||
boolean dynamic = isDynamicNode(raw, approvers);
|
if (nodeApprovers.isEmpty()) {
|
||||||
if (approvers.isEmpty()) {
|
nodeApprovers.add(new NormalizedApprover("FEISHU", null, "提交时由飞书解析", true));
|
||||||
approvers.add(new NormalizedApprover("FEISHU", null,
|
|
||||||
"提交时由飞书解析", true));
|
|
||||||
dynamic = 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");
|
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<ReimbursementFormField> 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));
|
definition.setFingerprint(fingerprint(definition));
|
||||||
return definition;
|
return definition;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<ReimbursementFormField> 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<String> ids = new HashSet<>(); Set<String> valueKeys = new HashSet<>();
|
||||||
|
List<ReimbursementFormField> 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<String> ids, Set<String> 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<ReimbursementFormField.Option> 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<String> 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<String> 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<ReimbursementFormField> 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<String> 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<String> 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<ReimbursementFormField> fields) {
|
||||||
|
Map<String,Integer> 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<String,Integer> 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<String,Integer> entry : children.entrySet()) if (entry.getValue() > 1)
|
||||||
|
throw new BusinessException("飞书费用明细包含重复绑定: " + entry.getKey(), 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Map.Entry<String,Integer> 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<String,Integer> 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<ReimbursementFormField> 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<NormalizedApprover> normalizeApprovers(JsonNode node) {
|
private List<NormalizedApprover> normalizeApprovers(JsonNode node) {
|
||||||
JsonNode values = first(node, "approvers", "approver", "approver_list", "approverList", "assignees");
|
JsonNode values = first(node, "approvers", "approver", "approver_list", "approverList", "assignees");
|
||||||
List<NormalizedApprover> result = new ArrayList<>();
|
List<NormalizedApprover> result = new ArrayList<>(); if (values == null) return result;
|
||||||
if (values == null) return result;
|
|
||||||
Iterable<JsonNode> iterable = values.isArray() ? values : Collections.singletonList(values);
|
Iterable<JsonNode> iterable = values.isArray() ? values : Collections.singletonList(values);
|
||||||
for (JsonNode value : iterable) {
|
for (JsonNode value : iterable) {
|
||||||
if (result.size() >= MAX_APPROVERS) throw new IllegalArgumentException("too many Feishu approvers");
|
if (result.size() >= MAX_APPROVERS) throw new IllegalArgumentException("too many Feishu approvers");
|
||||||
if (value == null || value.isNull()) continue;
|
if (value == null || value.isNull()) continue;
|
||||||
if (value.isTextual()) {
|
if (value.isTextual()) { result.add(new NormalizedApprover("USER", value.asText(), value.asText(), false)); continue; }
|
||||||
result.add(new NormalizedApprover("USER", value.asText(), value.asText(), false));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String type = firstText(value, "type", "approver_type", "approverType");
|
String type = firstText(value, "type", "approver_type", "approverType");
|
||||||
String ref = firstText(value, "user_id", "userId", "open_id", "role_id", "roleId", "id");
|
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"));
|
String label = displayText(first(value, "name", "user_name", "role_name", "label", "title"));
|
||||||
@@ -82,113 +378,30 @@ public class FeishuDefinitionNormalizer {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isDynamicNode(JsonNode node, List<NormalizedApprover> approvers) {
|
private boolean isDynamicNode(JsonNode node, List<NormalizedApprover> values) {
|
||||||
String type = firstText(node, "node_type", "nodeType", "type");
|
String type = firstText(node, "node_type", "nodeType", "type");
|
||||||
if (type != null && (type.toUpperCase(Locale.ROOT).contains("CONDITION")
|
if (type != null && (type.toUpperCase(Locale.ROOT).contains("CONDITION") || type.toUpperCase(Locale.ROOT).contains("ROUTE"))) return true;
|
||||||
|| type.toUpperCase(Locale.ROOT).contains("ROUTE"))) return true;
|
for (NormalizedApprover value : values) if (value.isDynamic()) return true;
|
||||||
for (NormalizedApprover approver : approvers) if (approver.isDynamic()) return true;
|
|
||||||
return node.has("condition") || node.has("conditions") || node.has("control");
|
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) {
|
@Data @AllArgsConstructor public static class NormalizedDefinition {
|
||||||
if (!StringUtils.hasText(ref)) return false;
|
private String approvalCode; private String approvalName; private List<NormalizedNode> nodes; private String fingerprint;
|
||||||
String normalized = type == null ? "" : type.toUpperCase(Locale.ROOT);
|
private List<ReimbursementFormField> formFields; private String formSchema; private String formFingerprint;
|
||||||
return normalized.isEmpty() || normalized.contains("USER") || normalized.contains("PERSON");
|
|
||||||
}
|
|
||||||
|
|
||||||
private String dynamicLabel(String type) {
|
|
||||||
String value = type == null ? "" : type.toUpperCase(Locale.ROOT);
|
|
||||||
if (value.contains("MANAGER") || value.contains("LEADER")) return "部门负责人";
|
|
||||||
if (value.contains("ROLE")) return "角色审批人";
|
|
||||||
if (value.contains("FREE")) return "发起人选择审批人";
|
|
||||||
return "飞书动态审批人";
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonNode findNodeArray(JsonNode node, int depth) {
|
|
||||||
if (node == null || depth > 5) return null;
|
|
||||||
for (String key : Arrays.asList("node_list", "nodeList", "approval_nodes", "approvalNodes", "nodes")) {
|
|
||||||
JsonNode candidate = node.get(key);
|
|
||||||
if (candidate != null && candidate.isArray()) return candidate;
|
|
||||||
}
|
|
||||||
for (String key : Arrays.asList("approval", "definition", "process", "flow", "approval_definition")) {
|
|
||||||
JsonNode nested = node.get(key);
|
|
||||||
JsonNode found = findNodeArray(nested, depth + 1);
|
|
||||||
if (found != null) return found;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonNode findDeep(JsonNode node, int depth, String... names) {
|
|
||||||
if (node == null || depth > 5) return null;
|
|
||||||
JsonNode direct = first(node, names);
|
|
||||||
if (direct != null) return direct;
|
|
||||||
for (String key : Arrays.asList("approval", "definition", "process", "flow", "approval_definition")) {
|
|
||||||
JsonNode found = findDeep(node.get(key), depth + 1, names);
|
|
||||||
if (found != null) return found;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String fingerprint(NormalizedDefinition definition) {
|
|
||||||
StringBuilder canonical = new StringBuilder();
|
|
||||||
append(canonical, definition.getApprovalCode());
|
|
||||||
append(canonical, definition.getApprovalName());
|
|
||||||
for (NormalizedNode node : definition.getNodes()) {
|
|
||||||
append(canonical, String.valueOf(node.getOrder())); append(canonical, node.getNodeKey());
|
|
||||||
append(canonical, node.getNodeName()); append(canonical, node.getNodeType());
|
|
||||||
append(canonical, node.getApprovalMode()); append(canonical, String.valueOf(node.isDynamic()));
|
|
||||||
for (NormalizedApprover approver : node.getApprovers()) {
|
|
||||||
append(canonical, approver.getType()); append(canonical, approver.getRef());
|
|
||||||
append(canonical, approver.getLabel()); append(canonical, String.valueOf(approver.isDynamic()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Sha256.hex(canonical.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void append(StringBuilder target, String value) {
|
|
||||||
String safe = value == null ? "" : value;
|
|
||||||
target.append(safe.length()).append(':').append(safe).append('|');
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonNode first(JsonNode node, String... names) {
|
|
||||||
if (node == null) return null;
|
|
||||||
for (String name : names) {
|
|
||||||
JsonNode value = node.get(name);
|
|
||||||
if (value != null && !value.isNull() && !value.isMissingNode()) return value;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstText(JsonNode node, String... names) { return displayText(first(node, names)); }
|
|
||||||
|
|
||||||
private String displayText(JsonNode value) {
|
|
||||||
if (value == null || value.isNull()) return null;
|
|
||||||
if (value.isValueNode()) return value.asText();
|
|
||||||
for (String key : Arrays.asList("zh_cn", "zh-CN", "text", "value", "name")) {
|
|
||||||
JsonNode nested = value.get(key);
|
|
||||||
if (nested != null && nested.isValueNode()) return nested.asText();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String bounded(String value, int max) {
|
|
||||||
return value == null ? null : value.substring(0, Math.min(max, value.length()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Data @AllArgsConstructor
|
|
||||||
public static class NormalizedDefinition {
|
|
||||||
private String approvalCode;
|
|
||||||
private String approvalName;
|
|
||||||
private List<NormalizedNode> nodes;
|
|
||||||
private String fingerprint;
|
|
||||||
}
|
|
||||||
@Data @AllArgsConstructor
|
|
||||||
public static class NormalizedNode {
|
|
||||||
private int order; private String nodeKey; private String nodeName; private String nodeType;
|
|
||||||
private String approvalMode; private boolean dynamic; private List<NormalizedApprover> approvers;
|
|
||||||
}
|
|
||||||
@Data @AllArgsConstructor
|
|
||||||
public static class NormalizedApprover {
|
|
||||||
private String type; private String ref; private String label; private boolean dynamic;
|
|
||||||
}
|
}
|
||||||
|
@Data @AllArgsConstructor public static class NormalizedNode { private int order; private String nodeKey; private String nodeName; private String nodeType; private String approvalMode; private boolean dynamic; private List<NormalizedApprover> approvers; }
|
||||||
|
@Data @AllArgsConstructor public static class NormalizedApprover { private String type; private String ref; private String label; private boolean dynamic; }
|
||||||
}
|
}
|
||||||
+36
-14
@@ -20,6 +20,10 @@ public class FeishuDefinitionSnapshotWriter {
|
|||||||
private final FeishuApprovalDefinitionApproverRepository approvers;
|
private final FeishuApprovalDefinitionApproverRepository approvers;
|
||||||
private final FeishuDefinitionSyncFenceRepository fences;
|
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
|
@Transactional
|
||||||
public FeishuDefinitionSyncResult replace(NormalizedDefinition definition, LocalDateTime fetchedAt, long generation) {
|
public FeishuDefinitionSyncResult replace(NormalizedDefinition definition, LocalDateTime fetchedAt, long generation) {
|
||||||
FeishuDefinitionSyncFence fence = fences.findByIdForUpdate(FeishuDefinitionSyncFence.SINGLETON_ID)
|
FeishuDefinitionSyncFence fence = fences.findByIdForUpdate(FeishuDefinitionSyncFence.SINGLETON_ID)
|
||||||
@@ -27,30 +31,39 @@ public class FeishuDefinitionSnapshotWriter {
|
|||||||
if (!Objects.equals(fence.getGeneration(), generation)) {
|
if (!Objects.equals(fence.getGeneration(), generation)) {
|
||||||
throw new BusinessException("本次同步已被更新的审批定义同步取代,请刷新后重试", 409);
|
throw new BusinessException("本次同步已被更新的审批定义同步取代,请刷新后重试", 409);
|
||||||
}
|
}
|
||||||
|
|
||||||
FeishuApprovalDefinitionSnapshot current = snapshots
|
FeishuApprovalDefinitionSnapshot current = snapshots
|
||||||
.findById(FeishuApprovalDefinitionSnapshot.CURRENT_ID).orElse(null);
|
.findById(FeishuApprovalDefinitionSnapshot.CURRENT_ID).orElse(null);
|
||||||
if (current != null && definition.getFingerprint().equals(current.getFingerprint())) {
|
boolean changed = current == null
|
||||||
current.setFetchedAt(fetchedAt);
|
|| !definition.getFingerprint().equals(current.getFingerprint());
|
||||||
current.setUpdatedAt(fetchedAt);
|
|
||||||
|
if (current == null) {
|
||||||
|
current = FeishuApprovalDefinitionSnapshot.builder()
|
||||||
|
.id(FeishuApprovalDefinitionSnapshot.CURRENT_ID)
|
||||||
|
.createdAt(fetchedAt)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
current.setApprovalCode(definition.getApprovalCode());
|
current.setApprovalCode(definition.getApprovalCode());
|
||||||
current.setApprovalName(definition.getApprovalName());
|
current.setApprovalName(definition.getApprovalName());
|
||||||
snapshots.save(current);
|
current.setFingerprint(definition.getFingerprint());
|
||||||
return result(definition, fetchedAt, false);
|
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);
|
||||||
|
|
||||||
|
if (changed) {
|
||||||
List<FeishuApprovalDefinitionNode> oldNodes = nodes
|
List<FeishuApprovalDefinitionNode> oldNodes = nodes
|
||||||
.findBySnapshotIdOrderByNodeOrderAsc(FeishuApprovalDefinitionSnapshot.CURRENT_ID);
|
.findBySnapshotIdOrderByNodeOrderAsc(FeishuApprovalDefinitionSnapshot.CURRENT_ID);
|
||||||
List<Long> oldIds = new ArrayList<>();
|
List<Long> oldIds = new ArrayList<>();
|
||||||
for (FeishuApprovalDefinitionNode node : oldNodes) oldIds.add(node.getId());
|
for (FeishuApprovalDefinitionNode node : oldNodes) oldIds.add(node.getId());
|
||||||
if (!oldIds.isEmpty()) approvers.deleteByNodeIdIn(oldIds);
|
if (!oldIds.isEmpty()) approvers.deleteByNodeIdIn(oldIds);
|
||||||
nodes.deleteBySnapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID);
|
nodes.deleteBySnapshotId(FeishuApprovalDefinitionSnapshot.CURRENT_ID);
|
||||||
|
approvers.flush();
|
||||||
LocalDateTime createdAt = current == null ? fetchedAt : current.getCreatedAt();
|
nodes.flush();
|
||||||
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()) {
|
for (NormalizedNode source : definition.getNodes()) {
|
||||||
FeishuApprovalDefinitionNode node = nodes.saveAndFlush(FeishuApprovalDefinitionNode.builder()
|
FeishuApprovalDefinitionNode node = nodes.saveAndFlush(FeishuApprovalDefinitionNode.builder()
|
||||||
@@ -65,12 +78,21 @@ public class FeishuDefinitionSnapshotWriter {
|
|||||||
.dynamic(sourceApprover.isDynamic()).build());
|
.dynamic(sourceApprover.isDynamic()).build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result(definition, fetchedAt, true);
|
}
|
||||||
|
return result(definition, fetchedAt, changed);
|
||||||
}
|
}
|
||||||
|
|
||||||
private FeishuDefinitionSyncResult result(NormalizedDefinition definition,
|
private FeishuDefinitionSyncResult result(NormalizedDefinition definition,
|
||||||
LocalDateTime fetchedAt, boolean changed) {
|
LocalDateTime fetchedAt, boolean changed) {
|
||||||
return FeishuDefinitionSyncResult.builder().fingerprint(definition.getFingerprint())
|
return FeishuDefinitionSyncResult.builder().fingerprint(definition.getFingerprint())
|
||||||
|
.formFingerprint(definition.getFormFingerprint()).formFieldCount(countFields(definition.getFormFields()))
|
||||||
.fetchedAt(fetchedAt).nodeCount(definition.getNodes().size()).changed(changed).build();
|
.fetchedAt(fetchedAt).nodeCount(definition.getNodes().size()).changed(changed).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int countFields(List<com.finance.system.dto.ReimbursementFormField> fields) {
|
||||||
|
int count = 0;
|
||||||
|
if (fields != null) for (com.finance.system.dto.ReimbursementFormField field : fields)
|
||||||
|
count += 1 + countFields(field.getChildren());
|
||||||
|
return count;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,10 +4,17 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.finance.system.dto.FeishuDefinitionSyncResult;
|
import com.finance.system.dto.FeishuDefinitionSyncResult;
|
||||||
import com.finance.system.exception.BusinessException;
|
import com.finance.system.exception.BusinessException;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
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
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class FeishuDefinitionSyncService {
|
public class FeishuDefinitionSyncService {
|
||||||
@@ -16,23 +23,38 @@ public class FeishuDefinitionSyncService {
|
|||||||
private final FeishuDefinitionSnapshotWriter writer;
|
private final FeishuDefinitionSnapshotWriter writer;
|
||||||
private final FeishuDefinitionGenerationService generations;
|
private final FeishuDefinitionGenerationService generations;
|
||||||
|
|
||||||
/** Network I/O intentionally completes before the transactional writer is entered. */
|
|
||||||
public FeishuDefinitionSyncResult sync() {
|
public FeishuDefinitionSyncResult sync() {
|
||||||
if (!remote.isApprovalEnabledAndConfigured()) {
|
if (!remote.isApprovalEnabledAndConfigured()) {
|
||||||
throw new BusinessException("飞书审批未配置,无法同步", 409);
|
throw new BusinessException("飞书审批未配置,无法验证与同步", 409);
|
||||||
}
|
}
|
||||||
long generation = generations.reserve();
|
long generation = generations.reserve();
|
||||||
|
FeishuDefinitionSyncResult result;
|
||||||
try {
|
try {
|
||||||
JsonNode response = remote.fetchApprovalDefinitionJson();
|
JsonNode response = remote.fetchApprovalDefinitionJson();
|
||||||
FeishuDefinitionNormalizer.NormalizedDefinition definition =
|
FeishuDefinitionNormalizer.NormalizedDefinition definition =
|
||||||
normalizer.normalize(response, remote.getConfiguredApprovalCode());
|
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) {
|
} catch (BusinessException e) {
|
||||||
throw e;
|
throw e;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new BusinessException("飞书审批定义无法使用: " + e.getMessage(), 409);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// The writer was never called (or its transaction rolled back), so the
|
throw new BusinessException("飞书审批定义验证失败,请稍后重试", 502);
|
||||||
// last known-good snapshot remains available.
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -55,10 +55,81 @@ public class FeishuDirectoryCurrentStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Map<String,Object> read(){
|
public Map<String,Object> read(){
|
||||||
List<Map<String,Object>> departments=new ArrayList<>();for(Map<String,Object>r:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){Map<String,Object>d=new LinkedHashMap<>();d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name")));d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order"))));d.put("memberCount",intValue(r.get("member_count")));departments.add(d);}
|
Map<String,Object>result=new LinkedHashMap<>();
|
||||||
Map<String,List<String>> memberships=new HashMap<>();for(Map<String,Object>r:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department ORDER BY open_id,open_department_id"))memberships.computeIfAbsent(string(r.get("open_id")),k->new ArrayList<>()).add(string(r.get("open_department_id")));
|
result.put("departments",readDepartments());
|
||||||
List<Map<String,Object>>users=new ArrayList<>();for(Map<String,Object>r:jdbc.queryForList("SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id")){Map<String,Object>u=new LinkedHashMap<>();String open=string(r.get("open_id"));u.put("openId",open);u.put("userId",r.get("user_id")==null?null:string(r.get("user_id")));u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no"));u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile")));u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url")));u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u);}
|
result.put("users",readUsers(null));
|
||||||
Map<String,Object>result=new LinkedHashMap<>();result.put("departments",departments);result.put("users",users);return result;
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Departments only — used by the organization shell so the page can paint before members load. */
|
||||||
|
public List<Map<String,Object>> readDepartments(){
|
||||||
|
List<Map<String,Object>> departments=new ArrayList<>();
|
||||||
|
for(Map<String,Object>r:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){
|
||||||
|
Map<String,Object>d=new LinkedHashMap<>();
|
||||||
|
d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name")));
|
||||||
|
d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order"))));
|
||||||
|
d.put("memberCount",intValue(r.get("member_count")));departments.add(d);
|
||||||
|
}
|
||||||
|
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<Map<String,Object>> readUsers(Collection<String> departmentIds){
|
||||||
|
Map<String,List<String>> memberships=new HashMap<>();
|
||||||
|
Set<String> 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<Map<String,Object>> membershipRows=scope==null
|
||||||
|
?jdbc.queryForList(membershipSql)
|
||||||
|
:jdbc.queryForList(membershipSql,scope.toArray());
|
||||||
|
Set<String> openIds=new LinkedHashSet<>();
|
||||||
|
for(Map<String,Object>r: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<Map<String,Object>> 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(Map<String,Object>r: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<Map<String,Object>> userRows=scope==null?jdbc.queryForList(userSql):jdbc.queryForList(userSql,openIds.toArray());
|
||||||
|
List<Map<String,Object>>users=new ArrayList<>();
|
||||||
|
for(Map<String,Object>r:userRows){
|
||||||
|
Map<String,Object>u=new LinkedHashMap<>();String open=string(r.get("open_id"));
|
||||||
|
u.put("openId",open);u.put("userId",r.get("user_id")==null?null:string(r.get("user_id")));
|
||||||
|
u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no"));
|
||||||
|
u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile")));
|
||||||
|
u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url")));
|
||||||
|
u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u);
|
||||||
|
}
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String placeholders(int count){
|
||||||
|
if(count<1)throw new IllegalArgumentException("placeholder count");
|
||||||
|
StringBuilder b=new StringBuilder("?");
|
||||||
|
for(int i=1;i<count;i++)b.append(",?");
|
||||||
|
return b.toString();
|
||||||
}
|
}
|
||||||
private void batchDeleteMemberships(Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM feishu_directory_user_department WHERE open_id=? AND open_department_id=?",rows);}
|
private void batchDeleteMemberships(Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM feishu_directory_user_department WHERE open_id=? AND open_department_id=?",rows);}
|
||||||
private void batchDelete(String table,String column,Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value))rows.add(new Object[]{value});batch("DELETE FROM "+table+" WHERE "+column+"=?",rows);}
|
private void batchDelete(String table,String column,Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value))rows.add(new Object[]{value});batch("DELETE FROM "+table+" WHERE "+column+"=?",rows);}
|
||||||
|
|||||||
@@ -90,7 +90,10 @@ public class FeishuDirectoryService {
|
|||||||
result.put("lastRun",last);return result;
|
result.put("lastRun",last);return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String,Object> organization(){
|
/** Default page load: departments only. Pass includeUsers=true for the legacy full payload. */
|
||||||
|
public Map<String,Object> organization(){return organization(false);}
|
||||||
|
|
||||||
|
public Map<String,Object> organization(boolean includeUsers){
|
||||||
Map<String,Object> unavailable=emptyOrganization(FeishuDirectoryPublication.unavailable(),null,"UNKNOWN");
|
Map<String,Object> unavailable=emptyOrganization(FeishuDirectoryPublication.unavailable(),null,"UNKNOWN");
|
||||||
if(!organizationPermits.tryAcquire())return unavailable;
|
if(!organizationPermits.tryAcquire())return unavailable;
|
||||||
try{
|
try{
|
||||||
@@ -100,8 +103,8 @@ public class FeishuDirectoryService {
|
|||||||
Instant success=publication.getSuccessfulAt();
|
Instant success=publication.getSuccessfulAt();
|
||||||
Map<String,Object> result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN");
|
Map<String,Object> result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN");
|
||||||
if(!publication.isAvailable())return new OrganizationSnapshot(publication,result);
|
if(!publication.isAvailable())return new OrganizationSnapshot(publication,result);
|
||||||
Map<String,Object> organization=currentStore.read();
|
result.put("departments",currentStore.readDepartments());
|
||||||
if(organization!=null){result.put("departments",organization.get("departments"));result.put("users",organization.get("users"));}
|
if(includeUsers)result.put("users",currentStore.readUsers(null));
|
||||||
return new OrganizationSnapshot(publication,result);
|
return new OrganizationSnapshot(publication,result);
|
||||||
});
|
});
|
||||||
if(captured==null||!captured.publication.isAvailable())return captured==null?unavailable:captured.value;
|
if(captured==null||!captured.publication.isAvailable())return captured==null?unavailable:captured.value;
|
||||||
@@ -112,6 +115,57 @@ public class FeishuDirectoryService {
|
|||||||
finally{organizationPermits.release();}
|
finally{organizationPermits.release();}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Members for one department (optionally including descendants). Same availability fence as organization(). */
|
||||||
|
public Map<String,Object> organizationMembers(String departmentId,boolean includeDescendants){
|
||||||
|
Map<String,Object> 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<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
|
||||||
|
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
|
||||||
|
Instant success=publication.getSuccessfulAt();
|
||||||
|
Map<String,Object> result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN");
|
||||||
|
result.put("departmentId",target);
|
||||||
|
if(!publication.isAvailable())return new OrganizationSnapshot(publication,result);
|
||||||
|
List<Map<String,Object>> departments=currentStore.readDepartments();
|
||||||
|
Set<String> 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<String> descendantIds(List<Map<String,Object>> departments,String rootId){
|
||||||
|
Map<String,List<String>> children=new HashMap<>();
|
||||||
|
for(Map<String,Object> 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<String> result=new LinkedHashSet<>();
|
||||||
|
ArrayDeque<String> 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. */
|
/** A separate READ_COMMITTED transaction observes publications committed during materialization. */
|
||||||
private boolean revalidate(FeishuDirectoryPublication captured){
|
private boolean revalidate(FeishuDirectoryPublication captured){
|
||||||
Boolean stable=observation.execute(status->{
|
Boolean stable=observation.execute(status->{
|
||||||
|
|||||||
@@ -23,9 +23,32 @@ public class FeishuDirectorySyncDispatcher implements SmartLifecycle {
|
|||||||
private ScheduledFuture<?> poller;
|
private ScheduledFuture<?> poller;
|
||||||
public FeishuDirectorySyncDispatcher(FeishuDirectorySyncWorker worker,
|
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);}
|
@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 */}}
|
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(){running.set(false);if(poller!=null)poller.cancel(false);}
|
||||||
@Override public void stop(Runnable callback){stop();callback.run();}
|
@Override public void stop(Runnable callback){stop();callback.run();}
|
||||||
@Override public boolean isRunning(){return running.get();}
|
@Override public boolean isRunning(){return running.get();}
|
||||||
|
|||||||
@@ -20,9 +20,13 @@ public class FeishuTenantTokenService {
|
|||||||
private static final BigInteger SUCCESS_CODE = BigInteger.ZERO;
|
private static final BigInteger SUCCESS_CODE = BigInteger.ZERO;
|
||||||
private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L);
|
private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L);
|
||||||
private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
|
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 IntegrationConfigReader config;
|
||||||
private final FeishuDirectorySettings settings;
|
private final FeishuDirectorySettings settings;
|
||||||
private final RestTemplate http;
|
private final RestTemplate http;
|
||||||
|
private final Object captureLock = new Object();
|
||||||
|
private volatile CachedCapture cachedCapture;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings) {
|
public FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings) {
|
||||||
@@ -39,7 +43,35 @@ public class FeishuTenantTokenService {
|
|||||||
return new RestTemplate(factory);
|
return new RestTemplate(factory);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Drop cached credentials after an admin config write. */
|
||||||
|
public void invalidateCaptureCache() { cachedCapture = null; }
|
||||||
|
|
||||||
public Context capture() {
|
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<String,String> values;
|
Map<String,String> values;
|
||||||
try {
|
try {
|
||||||
values = config.freshFeishu();
|
values = config.freshFeishu();
|
||||||
@@ -65,10 +97,11 @@ public class FeishuTenantTokenService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean syncEnabled() {
|
public boolean syncEnabled() {
|
||||||
Map<String,String> values;
|
try {
|
||||||
try { values = config.freshFeishu(); }
|
Map<String,String> values = config.freshFeishu();
|
||||||
catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); }
|
|
||||||
return values != null && Boolean.parseBoolean(values.getOrDefault("syncOrgEnabled", "true"));
|
return values != null && Boolean.parseBoolean(values.getOrDefault("syncOrgEnabled", "true"));
|
||||||
|
} catch (DiagnosticFailure ex) { throw ex; }
|
||||||
|
catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); }
|
||||||
}
|
}
|
||||||
public String getTenantAccessToken() { return token(capture()); }
|
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; }
|
Context(String app, String secret, String fingerprint) { this.app = app; this.secret = secret; this.fingerprint = fingerprint; }
|
||||||
// Deliberately no toString/getters for credentials.
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -30,6 +30,10 @@ public final class ReimbursementCanonicalizer {
|
|||||||
field(out, "totalAmount", money(app.getTotalAmount()));
|
field(out, "totalAmount", money(app.getTotalAmount()));
|
||||||
field(out, "payeeName", app.getPayeeName());
|
field(out, "payeeName", app.getPayeeName());
|
||||||
field(out, "payeeBankId", app.getPayeeBankId());
|
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, "bankName", bank == null ? null : bank.getBankName());
|
||||||
field(out, "branchName", bank == null ? null : bank.getBranchName());
|
field(out, "branchName", bank == null ? null : bank.getBranchName());
|
||||||
field(out, "accountName", bank == null ? null : bank.getAccountName());
|
field(out, "accountName", bank == null ? null : bank.getAccountName());
|
||||||
|
|||||||
@@ -5,17 +5,19 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
import com.finance.system.exception.BusinessException;
|
import com.finance.system.exception.BusinessException;
|
||||||
import com.finance.system.service.IntegrationConfigReader;
|
import com.finance.system.service.IntegrationConfigReader;
|
||||||
import com.finance.system.service.IntegrationConfigService;
|
import com.finance.system.service.IntegrationConfigService;
|
||||||
|
import com.finance.system.service.KingdeeAccountBindingService;
|
||||||
|
import com.finance.system.util.AuditUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.*;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Lazy;
|
import org.springframework.context.annotation.Lazy;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -33,6 +35,7 @@ public class KingdeeClient {
|
|||||||
private String sessionConfigFingerprint;
|
private String sessionConfigFingerprint;
|
||||||
private IntegrationConfigReader integrationConfigReader;
|
private IntegrationConfigReader integrationConfigReader;
|
||||||
private IntegrationConfigService integrationConfigService;
|
private IntegrationConfigService integrationConfigService;
|
||||||
|
private KingdeeAccountBindingService kingdeeAccountBindingService;
|
||||||
|
|
||||||
@Autowired(required = false)
|
@Autowired(required = false)
|
||||||
public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) {
|
public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) {
|
||||||
@@ -44,55 +47,30 @@ public class KingdeeClient {
|
|||||||
this.integrationConfigService = integrationConfigService;
|
this.integrationConfigService = integrationConfigService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Autowired(required = false)
|
||||||
|
public void setKingdeeAccountBindingService(@Lazy KingdeeAccountBindingService kingdeeAccountBindingService) {
|
||||||
|
this.kingdeeAccountBindingService = kingdeeAccountBindingService;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isEnabled() {
|
public boolean isEnabled() {
|
||||||
return (integrationConfigReader == null ? kingdeeConfig.isEnabled() : integrationConfigReader.isEnabled("KINGDEE"))
|
return (integrationConfigReader == null ? kingdeeConfig.isEnabled() : integrationConfigReader.isEnabled("KINGDEE"))
|
||||||
&& hasText(baseUrl());
|
&& hasText(baseUrl());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** System-account login used by sync/query and connection tests. */
|
||||||
* 登录金蝶云星空,获取Session
|
|
||||||
*/
|
|
||||||
public String login() {
|
public String login() {
|
||||||
if (!isEnabled()) throw new BusinessException("金蝶集成未启用或配置不完整");
|
String token = authenticate(clientId(), clientSecret());
|
||||||
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
|
|
||||||
|
|
||||||
Map<String, Object> 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<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
|
|
||||||
|
|
||||||
try {
|
|
||||||
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
|
|
||||||
Map<String, Object> body = response.getBody();
|
|
||||||
if (body != null && loginSucceeded(body)) {
|
|
||||||
Map<String, Object> context = asMap(body.get("Context"));
|
|
||||||
Map<String, Object> result = asMap(body.get("Result"));
|
|
||||||
String token = text(context.get("SessionId"));
|
|
||||||
if (token == null) token = text(result.get("SessionId"));
|
|
||||||
if (token != null) {
|
|
||||||
this.sessionToken = token;
|
this.sessionToken = token;
|
||||||
this.sessionExpireTime = System.currentTimeMillis() + 3600000; // 1小时过期
|
this.sessionExpireTime = System.currentTimeMillis() + 3600000;
|
||||||
this.sessionConfigFingerprint = configFingerprint();
|
this.sessionConfigFingerprint = configFingerprint();
|
||||||
return this.sessionToken;
|
return token;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
throw new BusinessException("金蝶登录失败");
|
/** Validates employee credentials without replacing the system session. */
|
||||||
} catch (Exception e) {
|
public void validateUserCredentials(String username, String password) {
|
||||||
// Never log the remote exception: it can contain the response body or account data.
|
authenticate(username, password);
|
||||||
log.error("金蝶云星空登录失败");
|
|
||||||
throw new BusinessException("金蝶云星空连接失败");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取有效的Session
|
|
||||||
*/
|
|
||||||
private String getValidSession() {
|
private String getValidSession() {
|
||||||
if (!isEnabled()) throw new BusinessException("金蝶集成未启用");
|
if (!isEnabled()) throw new BusinessException("金蝶集成未启用");
|
||||||
if (sessionToken == null || System.currentTimeMillis() > sessionExpireTime
|
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<String, Object> save(String formId, Map<String, Object> data) {
|
public Map<String, Object> save(String formId, Map<String, Object> 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";
|
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<String, Object> view(String formId, String billNo) {
|
public Map<String, Object> view(String formId, String billNo) {
|
||||||
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc";
|
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc";
|
||||||
|
|
||||||
Map<String, Object> data = new HashMap<>();
|
Map<String, Object> data = new HashMap<>();
|
||||||
data.put("FormId", formId);
|
data.put("FormId", formId);
|
||||||
data.put("Number", billNo);
|
data.put("Number", billNo);
|
||||||
|
HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, buildHeaders(getValidSession()));
|
||||||
HttpHeaders headers = buildHeaders();
|
|
||||||
HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
|
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
|
||||||
return response.getBody();
|
return response.getBody();
|
||||||
@@ -133,26 +112,13 @@ public class KingdeeClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询单据列表
|
|
||||||
*/
|
|
||||||
public List<Map<String, Object>> query(String formId, String filterString) {
|
public List<Map<String, Object>> query(String formId, String filterString) {
|
||||||
return query(formId, filterString, "*", 0, 100);
|
return query(formId, filterString, "*", 0, 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Queries a page of a Kingdee document. The old two argument method is
|
|
||||||
* deliberately kept as a compatibility wrapper because it is used by the
|
|
||||||
* outbound integration code and by older callers.
|
|
||||||
*
|
|
||||||
* @param fieldKeys comma separated Kingdee field keys (or *)
|
|
||||||
* @param startRow zero based offset
|
|
||||||
* @param topRowCount maximum number of rows to return
|
|
||||||
*/
|
|
||||||
public List<Map<String, Object>> query(String formId, String filterString,
|
public List<Map<String, Object>> query(String formId, String filterString,
|
||||||
String fieldKeys, int startRow, int topRowCount) {
|
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<String, Object> data = new HashMap<>();
|
Map<String, Object> data = new HashMap<>();
|
||||||
data.put("FormId", formId);
|
data.put("FormId", formId);
|
||||||
data.put("FieldKeys", fieldKeys == null || fieldKeys.trim().isEmpty() ? "*" : fieldKeys);
|
data.put("FieldKeys", fieldKeys == null || fieldKeys.trim().isEmpty() ? "*" : fieldKeys);
|
||||||
@@ -160,14 +126,9 @@ public class KingdeeClient {
|
|||||||
data.put("OrderString", "FBillNo ASC");
|
data.put("OrderString", "FBillNo ASC");
|
||||||
data.put("StartRow", Math.max(0, startRow));
|
data.put("StartRow", Math.max(0, startRow));
|
||||||
int boundedTop = Math.max(1, Math.min(100, topRowCount));
|
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("TopRowCount", 0);
|
||||||
data.put("Limit", boundedTop);
|
data.put("Limit", boundedTop);
|
||||||
|
HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, buildHeaders(getValidSession()));
|
||||||
HttpHeaders headers = buildHeaders();
|
|
||||||
HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ResponseEntity<Object> response = restTemplate.postForEntity(url, request, Object.class);
|
ResponseEntity<Object> response = restTemplate.postForEntity(url, request, Object.class);
|
||||||
return queryRows(response.getBody(), fieldKeys);
|
return queryRows(response.getBody(), fieldKeys);
|
||||||
@@ -177,16 +138,10 @@ public class KingdeeClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private Map<String, Object> executeKingdeeApi(String url, String formId, Map<String, Object> data, String session) {
|
||||||
* 执行金蝶API调用
|
|
||||||
*/
|
|
||||||
private Map<String, Object> executeKingdeeApi(String url, String formId, Map<String, Object> data) {
|
|
||||||
Map<String, Object> requestData = new HashMap<>(data);
|
Map<String, Object> requestData = new HashMap<>(data);
|
||||||
requestData.put("FormId", formId);
|
requestData.put("FormId", formId);
|
||||||
|
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestData, buildHeaders(session));
|
||||||
HttpHeaders headers = buildHeaders();
|
|
||||||
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestData, headers);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
|
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
|
||||||
Map<String, Object> body = response.getBody();
|
Map<String, Object> body = response.getBody();
|
||||||
@@ -194,18 +149,48 @@ public class KingdeeClient {
|
|||||||
throw new BusinessException("金蝶操作失败");
|
throw new BusinessException("金蝶操作失败");
|
||||||
}
|
}
|
||||||
return body;
|
return body;
|
||||||
|
} catch (BusinessException e) {
|
||||||
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("金蝶API调用失败: formId={}", formId);
|
log.error("金蝶API调用失败: formId={}", formId);
|
||||||
throw new BusinessException("金蝶云星空操作失败");
|
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<String, Object> 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<Map> response = restTemplate.postForEntity(url, new HttpEntity<>(requestBody, headers), Map.class);
|
||||||
|
Map<String, Object> body = response.getBody();
|
||||||
|
if (body != null && loginSucceeded(body)) {
|
||||||
|
Map<String, Object> context = asMap(body.get("Context"));
|
||||||
|
Map<String, Object> result = asMap(body.get("Result"));
|
||||||
|
String token = text(context.get("SessionId"));
|
||||||
|
if (token == null) token = text(result.get("SessionId"));
|
||||||
|
if (token != null) 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();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
String session = getValidSession();
|
|
||||||
headers.set("kdservice-sessionid", session);
|
headers.set("kdservice-sessionid", session);
|
||||||
// Keep the legacy header for older K3Cloud gateways during migration.
|
|
||||||
headers.set("SessionId", session);
|
headers.set("SessionId", session);
|
||||||
return headers;
|
return headers;
|
||||||
}
|
}
|
||||||
@@ -221,9 +206,6 @@ public class KingdeeClient {
|
|||||||
Object rowsBody = body;
|
Object rowsBody = body;
|
||||||
for (int depth = 0; depth < 5 && rowsBody instanceof Map; depth++) {
|
for (int depth = 0; depth < 5 && rowsBody instanceof Map; depth++) {
|
||||||
Map<String, Object> map = asMap(rowsBody);
|
Map<String, Object> map = asMap(rowsBody);
|
||||||
// Only documented response envelopes carry operation status.
|
|
||||||
// Do not recursively inspect data rows: a form may legitimately
|
|
||||||
// contain a business field named IsSuccess with value false.
|
|
||||||
if (envelopeFailed(map)) throw new BusinessException("金蝶单据查询失败");
|
if (envelopeFailed(map)) throw new BusinessException("金蝶单据查询失败");
|
||||||
if (map.containsKey("Result")) rowsBody = map.get("Result");
|
if (map.containsKey("Result")) rowsBody = map.get("Result");
|
||||||
else if (map.containsKey("Data")) rowsBody = map.get("Data");
|
else if (map.containsKey("Data")) rowsBody = map.get("Data");
|
||||||
@@ -276,10 +258,16 @@ public class KingdeeClient {
|
|||||||
}
|
}
|
||||||
return integrationConfigService.validateAndNormalizeKingdeeBaseUrl(raw);
|
return integrationConfigService.validateAndNormalizeKingdeeBaseUrl(raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String clientId() { return configured("clientId", kingdeeConfig.getClientId()); }
|
private String clientId() { return configured("clientId", kingdeeConfig.getClientId()); }
|
||||||
private String clientSecret() { return configured("clientSecret", kingdeeConfig.getClientSecret()); }
|
private String clientSecret() { return configured("clientSecret", kingdeeConfig.getClientSecret()); }
|
||||||
private String dbId() { return configured("dbId", kingdeeConfig.getDbId()); }
|
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 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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.finance.system.config;
|
package com.finance.system.config;
|
||||||
|
|
||||||
|
import com.finance.system.security.ApiAccessLogFilter;
|
||||||
import com.finance.system.security.JwtAuthenticationFilter;
|
import com.finance.system.security.JwtAuthenticationFilter;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.context.annotation.Bean;
|
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.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
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.SecurityFilterChain;
|
||||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
@@ -24,6 +26,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||||||
public class SecurityConfig {
|
public class SecurityConfig {
|
||||||
|
|
||||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||||
|
private final ApiAccessLogFilter apiAccessLogFilter;
|
||||||
private final Environment environment;
|
private final Environment environment;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -54,6 +57,7 @@ public class SecurityConfig {
|
|||||||
}
|
}
|
||||||
))
|
))
|
||||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
|
.addFilterAfter(apiAccessLogFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()));
|
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()));
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
@@ -72,4 +76,12 @@ public class SecurityConfig {
|
|||||||
public PasswordEncoder passwordEncoder() {
|
public PasswordEncoder passwordEncoder() {
|
||||||
return new BCryptPasswordEncoder();
|
return new BCryptPasswordEncoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Keep the filter only inside the security chain so each request is logged once. */
|
||||||
|
@Bean
|
||||||
|
public FilterRegistrationBean<ApiAccessLogFilter> disableApiAccessLogFilterRegistration(ApiAccessLogFilter filter) {
|
||||||
|
FilterRegistrationBean<ApiAccessLogFilter> registration = new FilterRegistrationBean<>(filter);
|
||||||
|
registration.setEnabled(false);
|
||||||
|
return registration;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,9 @@ import com.finance.system.adapter.feishu.FeishuDirectoryService;
|
|||||||
import com.finance.system.dto.ApiResponse;
|
import com.finance.system.dto.ApiResponse;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import com.finance.system.security.PermissionChecker;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -13,6 +15,7 @@ import java.util.Map;
|
|||||||
@RequestMapping("/api/feishu/directory")
|
@RequestMapping("/api/feishu/directory")
|
||||||
public class FeishuDirectoryController {
|
public class FeishuDirectoryController {
|
||||||
private final FeishuDirectoryService directory;
|
private final FeishuDirectoryService directory;
|
||||||
|
private final PermissionChecker permissions;
|
||||||
@PostMapping("/sync")
|
@PostMapping("/sync")
|
||||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.feishu.directory.sync')")
|
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.feishu.directory.sync')")
|
||||||
public ResponseEntity<ApiResponse<FeishuDirectoryService.Run>> sync() {
|
public ResponseEntity<ApiResponse<FeishuDirectoryService.Run>> sync() {
|
||||||
@@ -24,8 +27,19 @@ public class FeishuDirectoryController {
|
|||||||
public ApiResponse<Map<String,Object>> status() { return ApiResponse.success(directory.status()); }
|
public ApiResponse<Map<String,Object>> status() { return ApiResponse.success(directory.status()); }
|
||||||
|
|
||||||
@GetMapping("/organization")
|
@GetMapping("/organization")
|
||||||
|
@PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||||
|
public ApiResponse<Map<String,Object>> 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')")
|
@PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory')")
|
||||||
public ApiResponse<Map<String,Object>> organization() {
|
public ApiResponse<Map<String,Object>> organizationMembers(
|
||||||
return ApiResponse.success(directory.organization());
|
@RequestParam("departmentId") String departmentId,
|
||||||
|
@RequestParam(value = "includeDescendants", defaultValue = "true") boolean includeDescendants) {
|
||||||
|
return ApiResponse.success(directory.organizationMembers(departmentId, includeDescendants));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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<ApiResponse<List<Map<String, Object>>>> 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<ApiResponse<Map<String, Object>>> 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<ApiResponse<Map<String, Object>>> bind(
|
||||||
|
@PathVariable Long userId,
|
||||||
|
@RequestBody Map<String, Object> 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<ApiResponse<Void>> 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<ApiResponse<Map<String, Object>>> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,24 @@
|
|||||||
package com.finance.system.controller;
|
package com.finance.system.controller;
|
||||||
|
|
||||||
import com.finance.system.dto.ApiResponse;
|
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 com.finance.system.util.AuditUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
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
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@@ -17,82 +26,60 @@ import java.util.*;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class LogController {
|
public class LogController {
|
||||||
|
|
||||||
/**
|
private final ApiAccessLogService apiAccessLogService;
|
||||||
* Mock数据 - 操作日志
|
private final RoleService roleService;
|
||||||
*/
|
|
||||||
private static final List<Map<String, Object>> 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<String, Object> 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", " ");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取操作日志列表
|
* 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
|
@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<ApiResponse<List<Map<String, Object>>>> listLogs(
|
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listLogs(
|
||||||
@RequestParam(required = false) String category,
|
@RequestParam(required = false) String category,
|
||||||
@RequestParam(required = false) String operator,
|
@RequestParam(required = false) String operator,
|
||||||
@RequestParam(defaultValue = "50") int limit) {
|
@RequestParam(defaultValue = "200") int limit) {
|
||||||
try {
|
try {
|
||||||
List<Map<String, Object>> 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()) {
|
String scopedOperator = operator;
|
||||||
result.removeIf(log -> !category.equals(log.get("category")));
|
if (!viewAll) {
|
||||||
|
String selfName = AuditUtil.getCurrentUserRealName();
|
||||||
|
if (StringUtils.hasText(operator) && selfName != null
|
||||||
|
&& !"系统".equals(selfName)
|
||||||
|
&& !operator.trim().equalsIgnoreCase(selfName.trim())) {
|
||||||
|
throw new AccessDeniedException("当前权限仅可查看本人操作日志");
|
||||||
}
|
}
|
||||||
if (operator != null && !operator.isEmpty()) {
|
scopedOperator = "系统".equals(selfName) ? null : selfName;
|
||||||
result.removeIf(log -> !operator.equals(log.get("operator")));
|
|
||||||
}
|
}
|
||||||
|
List<Map<String, Object>> rows = apiAccessLogService.list(category, scopedOperator, limit);
|
||||||
// 按时间倒序排列
|
if (!viewAll && userId != null) {
|
||||||
result.sort((a, b) -> {
|
String selfName = AuditUtil.getCurrentUserRealName();
|
||||||
String timeA = (String) a.get("time");
|
rows = rows.stream()
|
||||||
String timeB = (String) b.get("time");
|
.filter(row -> Objects.equals(userId, asLong(row.get("operatorId")))
|
||||||
return timeB.compareTo(timeA);
|
|| (selfName != null && selfName.equals(String.valueOf(row.get("operator")))))
|
||||||
});
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
// 限制数量
|
|
||||||
if (result.size() > limit) {
|
|
||||||
result = result.subList(0, limit);
|
|
||||||
}
|
}
|
||||||
|
return ResponseEntity.ok(ApiResponse.success(rows));
|
||||||
return ResponseEntity.ok(ApiResponse.success(result));
|
} catch (AccessDeniedException e) {
|
||||||
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取操作日志列表失败", e);
|
log.error("获取操作日志列表失败", e);
|
||||||
return ResponseEntity.ok(ApiResponse.error(500, "获取操作日志列表失败: " + e.getMessage()));
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.finance.system.controller;
|
package com.finance.system.controller;
|
||||||
|
|
||||||
import com.finance.system.dto.ApiResponse;
|
import com.finance.system.dto.ApiResponse;
|
||||||
|
import com.finance.system.repository.SysExpenseTypeRepository;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -16,60 +17,7 @@ import java.util.stream.Collectors;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class MetadataController {
|
public class MetadataController {
|
||||||
|
|
||||||
/**
|
private final SysExpenseTypeRepository expenseTypeRepository;
|
||||||
* Mock数据 - 费用类型
|
|
||||||
*/
|
|
||||||
private static final List<Map<String, Object>> EXPENSE_TYPES = new ArrayList<>();
|
|
||||||
|
|
||||||
static {
|
|
||||||
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> et6 = new LinkedHashMap<>();
|
|
||||||
et6.put("id", 6);
|
|
||||||
et6.put("code", "OFFICE_EXPENSE");
|
|
||||||
et6.put("name", "办公费用");
|
|
||||||
et6.put("category", "办公费用");
|
|
||||||
et6.put("description", "办公用品、耗材等费用");
|
|
||||||
EXPENSE_TYPES.add(et6);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mock数据 - 收款人
|
* Mock数据 - 收款人
|
||||||
@@ -111,12 +59,17 @@ public class MetadataController {
|
|||||||
@GetMapping("/expense-types")
|
@GetMapping("/expense-types")
|
||||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.expense-types') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
@PreAuthorize("@permissionChecker.has(authentication, 'page.expense-types') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExpenseTypes() {
|
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExpenseTypes() {
|
||||||
try {
|
List<Map<String,Object>> result = expenseTypeRepository
|
||||||
return ResponseEntity.ok(ApiResponse.success(EXPENSE_TYPES));
|
.findByStatusIgnoreCaseOrderBySortOrderAscIdAsc("ACTIVE").stream().map(type -> {
|
||||||
} catch (Exception e) {
|
Map<String,Object> value = new LinkedHashMap<>();
|
||||||
log.error("获取费用类型列表失败", e);
|
value.put("id", type.getId());
|
||||||
return ResponseEntity.ok(ApiResponse.error(500, "获取费用类型列表失败: " + e.getMessage()));
|
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));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import org.springframework.http.HttpStatus;
|
|||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/reimbursements")
|
@RequestMapping("/api/v1/reimbursements")
|
||||||
@@ -19,6 +21,32 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
public class ReimApplicationController {
|
public class ReimApplicationController {
|
||||||
|
|
||||||
private final ReimApplicationService reimApplicationService;
|
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<ApiResponse<AttachmentDto>> 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<ApiResponse<Void>> 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<ApiResponse<ReimbursementFormDefinition>> formDefinition() {
|
||||||
|
return ResponseEntity.ok(ApiResponse.success(reimbursementFormService.currentDefinition()));
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/workbench")
|
@GetMapping("/workbench")
|
||||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')"
|
@PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')"
|
||||||
|
|||||||
@@ -4,14 +4,18 @@ import lombok.AllArgsConstructor;
|
|||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Builder
|
@Builder
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
public class AttachmentDto {
|
public class AttachmentDto {
|
||||||
private Long id;
|
private Long id;
|
||||||
private String fileName;
|
private String fileName;
|
||||||
private String fileType;
|
private String fileType;
|
||||||
private String fileUrl;
|
private String contentType;
|
||||||
|
private Long fileSize;
|
||||||
|
private Long expenseItemId;
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@ import lombok.Data;
|
|||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class CreateApplicationRequest {
|
public class CreateApplicationRequest {
|
||||||
@@ -15,4 +16,6 @@ public class CreateApplicationRequest {
|
|||||||
private String payeeName;
|
private String payeeName;
|
||||||
private Long payeeBankId;
|
private Long payeeBankId;
|
||||||
private List<ExpenseItemDto> items;
|
private List<ExpenseItemDto> items;
|
||||||
|
private String formFingerprint;
|
||||||
|
private Map<String, Object> formValues;
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,8 @@ import lombok.Data;
|
|||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Builder
|
@Builder
|
||||||
@@ -18,4 +20,9 @@ public class ExpenseItemDto {
|
|||||||
private String category;
|
private String category;
|
||||||
private String description;
|
private String description;
|
||||||
private BigDecimal amount;
|
private BigDecimal amount;
|
||||||
|
@Builder.Default
|
||||||
|
private List<Long> attachmentIds = new ArrayList<>();
|
||||||
|
/** Safe display metadata for attachments claimed by this expense row. */
|
||||||
|
@Builder.Default
|
||||||
|
private List<AttachmentDto> attachments = new ArrayList<>();
|
||||||
}
|
}
|
||||||
@@ -8,5 +8,12 @@ public class FeishuDefinitionSyncResult {
|
|||||||
private String fingerprint;
|
private String fingerprint;
|
||||||
private LocalDateTime fetchedAt;
|
private LocalDateTime fetchedAt;
|
||||||
private int nodeCount;
|
private int nodeCount;
|
||||||
|
private String formFingerprint;
|
||||||
|
private int formFieldCount;
|
||||||
private boolean changed;
|
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;
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ import java.math.BigDecimal;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Builder
|
@Builder
|
||||||
@@ -54,4 +55,13 @@ public class ReimApplicationDetail {
|
|||||||
private List<AttachmentDto> attachments;
|
private List<AttachmentDto> attachments;
|
||||||
private List<ApprovalRecordDto> approvalRecords;
|
private List<ApprovalRecordDto> approvalRecords;
|
||||||
private List<PaymentRecordDto> payments;
|
private List<PaymentRecordDto> payments;
|
||||||
|
private FormSnapshot formSnapshot;
|
||||||
|
|
||||||
|
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||||
|
public static class FormSnapshot {
|
||||||
|
private String mode;
|
||||||
|
private String fingerprint;
|
||||||
|
private List<ReimbursementFormField> fields;
|
||||||
|
private Map<String, Object> values;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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<ReimbursementFormField> fields = new ArrayList<>();
|
||||||
|
}
|
||||||
@@ -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<Option> options = new ArrayList<>();
|
||||||
|
@Builder.Default private List<ReimbursementFormField> children = new ArrayList<>();
|
||||||
|
|
||||||
|
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||||
|
public static class Option {
|
||||||
|
private String value;
|
||||||
|
private String label;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,8 @@ public class FeishuApprovalDefinitionSnapshot {
|
|||||||
@Column(name = "approval_code", nullable = false, length = 200) private String approvalCode;
|
@Column(name = "approval_code", nullable = false, length = 200) private String approvalCode;
|
||||||
@Column(name = "approval_name", length = 300) private String approvalName;
|
@Column(name = "approval_name", length = 300) private String approvalName;
|
||||||
@Column(nullable = false, length = 64) private String fingerprint;
|
@Column(nullable = false, length = 64) private String fingerprint;
|
||||||
|
@Column(name = "form_fingerprint", nullable = false, length = 64) private String formFingerprint;
|
||||||
|
@Lob @Column(name = "form_schema", nullable = false, columnDefinition = "MEDIUMTEXT") private String formSchema;
|
||||||
@Column(name = "fetched_at", nullable = false) private LocalDateTime fetchedAt;
|
@Column(name = "fetched_at", nullable = false) private LocalDateTime fetchedAt;
|
||||||
@Column(name = "created_at", nullable = false) private LocalDateTime createdAt;
|
@Column(name = "created_at", nullable = false) private LocalDateTime createdAt;
|
||||||
@Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
|
@Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
|
||||||
|
|||||||
@@ -85,6 +85,18 @@ public class ReimApplication {
|
|||||||
@Column(name = "source_status", length = 30)
|
@Column(name = "source_status", length = 30)
|
||||||
private String sourceStatus;
|
private String sourceStatus;
|
||||||
|
|
||||||
|
@Column(name = "feishu_form_fingerprint", length = 64)
|
||||||
|
private String feishuFormFingerprint;
|
||||||
|
|
||||||
|
@Lob @Column(name = "feishu_form_schema", columnDefinition = "MEDIUMTEXT")
|
||||||
|
private String feishuFormSchema;
|
||||||
|
|
||||||
|
@Lob @Column(name = "feishu_form_values", columnDefinition = "MEDIUMTEXT")
|
||||||
|
private String feishuFormValues;
|
||||||
|
|
||||||
|
@Lob @Column(name = "feishu_form_display_values", columnDefinition = "MEDIUMTEXT")
|
||||||
|
private String feishuFormDisplayValues;
|
||||||
|
|
||||||
@Column(name = "payee_name", length = 200)
|
@Column(name = "payee_name", length = 200)
|
||||||
private String payeeName;
|
private String payeeName;
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import lombok.Data;
|
|||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Entity
|
@Entity
|
||||||
@@ -15,21 +16,25 @@ import java.time.LocalDateTime;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Table(name = "reim_attachment")
|
@Table(name = "reim_attachment")
|
||||||
public class ReimAttachment {
|
public class ReimAttachment {
|
||||||
|
private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai");
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@Column(name = "application_id", nullable = false)
|
@Column(name = "application_id")
|
||||||
private Long applicationId;
|
private Long applicationId;
|
||||||
|
|
||||||
|
@Column(name = "expense_item_id")
|
||||||
|
private Long expenseItemId;
|
||||||
|
|
||||||
@Column(name = "file_name", length = 500, nullable = false)
|
@Column(name = "file_name", length = 500, nullable = false)
|
||||||
private String fileName;
|
private String fileName;
|
||||||
|
|
||||||
@Column(name = "file_type", length = 100)
|
@Column(name = "file_type", length = 100)
|
||||||
private String fileType;
|
private String fileType;
|
||||||
|
|
||||||
@Column(name = "file_url", length = 500, nullable = false)
|
@Column(name = "file_url", length = 500)
|
||||||
private String fileUrl;
|
private String fileUrl;
|
||||||
|
|
||||||
@Column(name = "file_size")
|
@Column(name = "file_size")
|
||||||
@@ -41,11 +46,23 @@ public class ReimAttachment {
|
|||||||
@Column(name = "uploader_id", nullable = false)
|
@Column(name = "uploader_id", nullable = false)
|
||||||
private Long uploaderId;
|
private Long uploaderId;
|
||||||
|
|
||||||
|
@Column(name = "form_control_id", length = 300, nullable = false)
|
||||||
|
private String formControlId;
|
||||||
|
|
||||||
|
@Column(name = "form_fingerprint", length = 64, nullable = false)
|
||||||
|
private String formFingerprint;
|
||||||
|
|
||||||
|
@Column(name = "feishu_file_code", length = 500, nullable = false)
|
||||||
|
private String feishuFileCode;
|
||||||
|
|
||||||
|
@Column(name = "upload_status", length = 30, nullable = false)
|
||||||
|
private String uploadStatus;
|
||||||
|
|
||||||
@Column(name = "created_at")
|
@Column(name = "created_at")
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = LocalDateTime.now();
|
if (createdAt == null) createdAt = LocalDateTime.now(SHANGHAI);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.finance.system.entity;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Entity
|
||||||
|
@Table(name = "sys_api_access_log")
|
||||||
|
public class SysApiAccessLog {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(name = "request_id", length = 64)
|
||||||
|
private String requestId;
|
||||||
|
|
||||||
|
@Column(name = "http_method", nullable = false, length = 16)
|
||||||
|
private String httpMethod;
|
||||||
|
|
||||||
|
@Column(name = "request_path", nullable = false, length = 500)
|
||||||
|
private String requestPath;
|
||||||
|
|
||||||
|
@Column(name = "query_string", length = 1000)
|
||||||
|
private String queryString;
|
||||||
|
|
||||||
|
@Column(nullable = false, length = 80)
|
||||||
|
private String category;
|
||||||
|
|
||||||
|
@Column(name = "operator_id")
|
||||||
|
private Long operatorId;
|
||||||
|
|
||||||
|
@Column(name = "operator_name", nullable = false, length = 100)
|
||||||
|
private String operatorName;
|
||||||
|
|
||||||
|
@Column(name = "status_code", nullable = false)
|
||||||
|
private Integer statusCode;
|
||||||
|
|
||||||
|
@Column(name = "duration_ms", nullable = false)
|
||||||
|
private Integer durationMs;
|
||||||
|
|
||||||
|
@Column(name = "client_ip", length = 64)
|
||||||
|
private String clientIp;
|
||||||
|
|
||||||
|
@Column(name = "user_agent", length = 500)
|
||||||
|
private String userAgent;
|
||||||
|
|
||||||
|
@Column(name = "error_message", length = 1000)
|
||||||
|
private String errorMessage;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
if (createdAt == null) {
|
||||||
|
createdAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.finance.system.entity;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Entity
|
||||||
|
@Table(name = "sys_user_kingdee_account")
|
||||||
|
public class SysUserKingdeeAccount {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "user_id")
|
||||||
|
private Long userId;
|
||||||
|
|
||||||
|
@Column(name = "kingdee_username", nullable = false, length = 120, unique = true)
|
||||||
|
private String kingdeeUsername;
|
||||||
|
|
||||||
|
/** Encrypted with IntegrationConfigCrypto; never log or return to clients. */
|
||||||
|
@Column(name = "kingdee_password", nullable = false, length = 2000)
|
||||||
|
private String kingdeePassword;
|
||||||
|
|
||||||
|
@Column(name = "bound_by")
|
||||||
|
private Long boundBy;
|
||||||
|
|
||||||
|
@Column(name = "bound_at", nullable = false)
|
||||||
|
private LocalDateTime boundAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at", nullable = false)
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
if (boundAt == null) boundAt = now;
|
||||||
|
updatedAt = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
|
|||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
import org.springframework.dao.DataIntegrityViolationException;
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
|
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -81,6 +82,12 @@ public class GlobalExceptionHandler {
|
|||||||
.body(ApiResponse.error(409, "数据冲突,请刷新后重试"));
|
.body(ApiResponse.error(409, "数据冲突,请刷新后重试"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||||
|
public ResponseEntity<ApiResponse<Void>> handleMaxUploadSize(MaxUploadSizeExceededException e) {
|
||||||
|
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
|
||||||
|
.body(ApiResponse.error(413, "附件不能超过 50MB"));
|
||||||
|
}
|
||||||
|
|
||||||
@ExceptionHandler(Exception.class)
|
@ExceptionHandler(Exception.class)
|
||||||
public ResponseEntity<ApiResponse<Void>> handleGeneral(Exception e) {
|
public ResponseEntity<ApiResponse<Void>> handleGeneral(Exception e) {
|
||||||
log.error("Unexpected error", e);
|
log.error("Unexpected error", e);
|
||||||
|
|||||||
+48
@@ -0,0 +1,48 @@
|
|||||||
|
package com.finance.system.repository;
|
||||||
|
|
||||||
|
import lombok.Value;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/** Reads the atomically published current Feishu directory for form snapshotting. */
|
||||||
|
@Repository
|
||||||
|
public class ApplicantDepartmentDirectoryRepository {
|
||||||
|
private static final String ROOT_DEPARTMENT_ID = "0";
|
||||||
|
private final JdbcTemplate jdbc;
|
||||||
|
|
||||||
|
public ApplicantDepartmentDirectoryRepository(JdbcTemplate jdbc) {
|
||||||
|
this.jdbc = jdbc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<DirectoryDepartment> findPreferredNonRootByOpenId(String openId) {
|
||||||
|
List<DirectoryDepartment> values = jdbc.query(
|
||||||
|
"SELECT d.open_department_id,d.name "
|
||||||
|
+ "FROM feishu_directory_user_department ud "
|
||||||
|
+ "JOIN feishu_directory_department d ON d.open_department_id=ud.open_department_id "
|
||||||
|
+ "WHERE ud.open_id=? AND d.open_department_id<>? "
|
||||||
|
+ "ORDER BY d.sort_order,d.open_department_id LIMIT 1",
|
||||||
|
(rs, rowNum) -> new DirectoryDepartment(
|
||||||
|
rs.getString("open_department_id"), rs.getString("name")),
|
||||||
|
openId, ROOT_DEPARTMENT_ID);
|
||||||
|
return values.stream().findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<DirectoryDepartment> findByOpenDepartmentId(String openDepartmentId) {
|
||||||
|
List<DirectoryDepartment> values = jdbc.query(
|
||||||
|
"SELECT open_department_id,name FROM feishu_directory_department "
|
||||||
|
+ "WHERE open_department_id=? AND open_department_id<>? LIMIT 1",
|
||||||
|
(rs, rowNum) -> new DirectoryDepartment(
|
||||||
|
rs.getString("open_department_id"), rs.getString("name")),
|
||||||
|
openDepartmentId, ROOT_DEPARTMENT_ID);
|
||||||
|
return values.stream().findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Value
|
||||||
|
public static class DirectoryDepartment {
|
||||||
|
String openDepartmentId;
|
||||||
|
String displayLabel;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,11 +3,43 @@ package com.finance.system.repository;
|
|||||||
import com.finance.system.entity.ReimAttachment;
|
import com.finance.system.entity.ReimAttachment;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
import org.springframework.data.jpa.repository.Lock;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import javax.persistence.LockModeType;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface ReimAttachmentRepository extends JpaRepository<ReimAttachment, Long> {
|
public interface ReimAttachmentRepository extends JpaRepository<ReimAttachment, Long> {
|
||||||
|
|
||||||
List<ReimAttachment> findByApplicationId(Long applicationId);
|
List<ReimAttachment> findByApplicationIdAndExpenseItemIdIsNotNullAndUploadStatus(
|
||||||
|
Long applicationId, String uploadStatus);
|
||||||
|
|
||||||
|
List<ReimAttachment> findByExpenseItemIdAndApplicationIdIsNotNullAndUploadStatusOrderByIdAsc(
|
||||||
|
Long expenseItemId, String uploadStatus);
|
||||||
|
|
||||||
|
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||||
|
@Query("select a from ReimAttachment a where a.id = :id")
|
||||||
|
Optional<ReimAttachment> findByIdForUpdate(@Param("id") Long id);
|
||||||
|
|
||||||
|
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||||
|
@Query("select a from ReimAttachment a where a.id in :ids")
|
||||||
|
List<ReimAttachment> findAllByIdInForUpdate(@Param("ids") Collection<Long> ids);
|
||||||
|
|
||||||
|
long countByUploaderIdAndApplicationIdIsNullAndUploadStatus(Long uploaderId, String uploadStatus);
|
||||||
|
|
||||||
|
@Query("select coalesce(sum(a.fileSize), 0) from ReimAttachment a "
|
||||||
|
+ "where a.uploaderId = :uploaderId and a.applicationId is null and a.uploadStatus = :uploadStatus")
|
||||||
|
Long sumStagedBytes(@Param("uploaderId") Long uploaderId, @Param("uploadStatus") String uploadStatus);
|
||||||
|
|
||||||
|
long countByUploaderIdAndCreatedAtGreaterThanEqual(Long uploaderId, LocalDateTime createdAt);
|
||||||
|
|
||||||
|
@Query("select coalesce(sum(a.fileSize), 0) from ReimAttachment a "
|
||||||
|
+ "where a.uploaderId = :uploaderId and a.createdAt >= :createdAt")
|
||||||
|
Long sumUploadedBytesSince(@Param("uploaderId") Long uploaderId,
|
||||||
|
@Param("createdAt") LocalDateTime createdAt);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.finance.system.repository;
|
||||||
|
|
||||||
|
import com.finance.system.entity.SysApiAccessLog;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface SysApiAccessLogRepository extends JpaRepository<SysApiAccessLog, Long> {
|
||||||
|
|
||||||
|
@Query("select l from SysApiAccessLog l "
|
||||||
|
+ "where (:category is null or :category = '' or l.category = :category) "
|
||||||
|
+ "and (:operator is null or :operator = '' or l.operatorName = :operator) "
|
||||||
|
+ "order by l.createdAt desc, l.id desc")
|
||||||
|
List<SysApiAccessLog> search(
|
||||||
|
@Param("category") String category,
|
||||||
|
@Param("operator") String operator,
|
||||||
|
Pageable pageable);
|
||||||
|
}
|
||||||
@@ -14,4 +14,6 @@ public interface SysExpenseTypeRepository extends JpaRepository<SysExpenseType,
|
|||||||
List<SysExpenseType> findByCategory(String category);
|
List<SysExpenseType> findByCategory(String category);
|
||||||
|
|
||||||
List<SysExpenseType> findByStatus(String status);
|
List<SysExpenseType> findByStatus(String status);
|
||||||
|
|
||||||
|
List<SysExpenseType> findByStatusIgnoreCaseOrderBySortOrderAscIdAsc(String status);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.finance.system.repository;
|
||||||
|
|
||||||
|
import com.finance.system.entity.SysUserKingdeeAccount;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface SysUserKingdeeAccountRepository extends JpaRepository<SysUserKingdeeAccount, Long> {
|
||||||
|
Optional<SysUserKingdeeAccount> findByKingdeeUsername(String kingdeeUsername);
|
||||||
|
boolean existsByUserId(Long userId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package com.finance.system.security;
|
||||||
|
|
||||||
|
import com.finance.system.entity.SysApiAccessLog;
|
||||||
|
import com.finance.system.service.ApiAccessLogService;
|
||||||
|
import com.finance.system.util.AuditUtil;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import javax.servlet.FilterChain;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records every /api/** call for the in-app operation log. Persistence is
|
||||||
|
* asynchronous so request latency is not tied to the logging write path.
|
||||||
|
* Authorization headers and known secret query keys are never stored.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ApiAccessLogFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private static final Set<String> REDACT_QUERY_KEYS = new HashSet<>(Arrays.asList(
|
||||||
|
"password", "passwd", "secret", "token", "access_token", "refresh_token",
|
||||||
|
"authorization", "code", "client_secret", "app_secret", "jwt"));
|
||||||
|
|
||||||
|
private final ApiAccessLogService apiAccessLogService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||||
|
String path = path(request);
|
||||||
|
if (!path.startsWith("/api/")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
String method = request.getMethod();
|
||||||
|
// View/read traffic is intentionally not persisted — only mutating calls are logged.
|
||||||
|
if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method) || "OPTIONS".equalsIgnoreCase(method)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
long started = System.currentTimeMillis();
|
||||||
|
String requestId = resolveRequestId(request);
|
||||||
|
response.setHeader("X-Request-Id", requestId);
|
||||||
|
try {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
apiAccessLogService.recordAsync(buildEntry(request, response, requestId, started));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// Logging must never break the original request/response path.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysApiAccessLog buildEntry(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
String requestId, long started) {
|
||||||
|
String requestPath = truncate(path(request), 500);
|
||||||
|
UserPrincipal user = AuditUtil.getCurrentUser();
|
||||||
|
String operatorName = user != null && StringUtils.hasText(user.getRealName())
|
||||||
|
? user.getRealName()
|
||||||
|
: (user != null && StringUtils.hasText(user.getEmployeeNo()) ? user.getEmployeeNo() : "匿名");
|
||||||
|
int status = response.getStatus();
|
||||||
|
return SysApiAccessLog.builder()
|
||||||
|
.requestId(requestId)
|
||||||
|
.httpMethod(truncate(request.getMethod(), 16))
|
||||||
|
.requestPath(requestPath)
|
||||||
|
.queryString(sanitizeQuery(request.getQueryString()))
|
||||||
|
.category(ApiAccessLogService.categorize(requestPath))
|
||||||
|
.operatorId(user == null ? null : user.getId())
|
||||||
|
.operatorName(truncate(operatorName, 100))
|
||||||
|
.statusCode(status)
|
||||||
|
.durationMs((int) Math.min(Integer.MAX_VALUE, Math.max(0, System.currentTimeMillis() - started)))
|
||||||
|
.clientIp(truncate(clientIp(request), 64))
|
||||||
|
.userAgent(truncate(request.getHeader("User-Agent"), 500))
|
||||||
|
.errorMessage(status >= 400 ? truncate("HTTP " + status, 1000) : null)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveRequestId(HttpServletRequest request) {
|
||||||
|
String incoming = request.getHeader("X-Request-Id");
|
||||||
|
if (StringUtils.hasText(incoming)) {
|
||||||
|
return truncate(incoming.trim(), 64);
|
||||||
|
}
|
||||||
|
return UUID.randomUUID().toString().replace("-", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String path(HttpServletRequest request) {
|
||||||
|
String uri = request.getRequestURI();
|
||||||
|
String context = request.getContextPath();
|
||||||
|
if (StringUtils.hasText(context) && uri != null && uri.startsWith(context)) {
|
||||||
|
uri = uri.substring(context.length());
|
||||||
|
}
|
||||||
|
return uri == null || uri.isEmpty() ? "/" : uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String clientIp(HttpServletRequest request) {
|
||||||
|
String forwarded = request.getHeader("X-Forwarded-For");
|
||||||
|
if (StringUtils.hasText(forwarded)) {
|
||||||
|
int comma = forwarded.indexOf(',');
|
||||||
|
return (comma >= 0 ? forwarded.substring(0, comma) : forwarded).trim();
|
||||||
|
}
|
||||||
|
String realIp = request.getHeader("X-Real-IP");
|
||||||
|
if (StringUtils.hasText(realIp)) {
|
||||||
|
return realIp.trim();
|
||||||
|
}
|
||||||
|
return request.getRemoteAddr();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String sanitizeQuery(String query) {
|
||||||
|
if (!StringUtils.hasText(query)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
StringBuilder sanitized = new StringBuilder();
|
||||||
|
for (String part : query.split("&")) {
|
||||||
|
if (!StringUtils.hasText(part)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (sanitized.length() > 0) {
|
||||||
|
sanitized.append('&');
|
||||||
|
}
|
||||||
|
int eq = part.indexOf('=');
|
||||||
|
String key = eq >= 0 ? part.substring(0, eq) : part;
|
||||||
|
String value = eq >= 0 ? part.substring(eq + 1) : "";
|
||||||
|
if (REDACT_QUERY_KEYS.contains(key.toLowerCase(Locale.ROOT))) {
|
||||||
|
sanitized.append(key).append('=').append("***");
|
||||||
|
} else {
|
||||||
|
sanitized.append(key);
|
||||||
|
if (eq >= 0) {
|
||||||
|
sanitized.append('=').append(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return truncate(sanitized.toString(), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String truncate(String value, int max) {
|
||||||
|
if (!StringUtils.hasText(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
String trimmed = value.trim();
|
||||||
|
return trimmed.length() <= max ? trimmed : trimmed.substring(0, max);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,4 +33,22 @@ public class PermissionChecker {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** True if the principal has any of the given permission codes (READ or EDIT). */
|
||||||
|
public boolean hasAny(Authentication authentication, String... permissionCodes) {
|
||||||
|
if (permissionCodes == null) return false;
|
||||||
|
for (String code : permissionCodes) {
|
||||||
|
if (has(authentication, code)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True if the principal has EDIT on any of the given permission codes. */
|
||||||
|
public boolean hasAnyEdit(Authentication authentication, String... permissionCodes) {
|
||||||
|
if (permissionCodes == null) return false;
|
||||||
|
for (String code : permissionCodes) {
|
||||||
|
if (hasEdit(authentication, code)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package com.finance.system.service;
|
||||||
|
|
||||||
|
import com.finance.system.entity.SysApiAccessLog;
|
||||||
|
import com.finance.system.repository.SysApiAccessLogRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ApiAccessLogService {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||||
|
private static final int MAX_LIST = 500;
|
||||||
|
|
||||||
|
private final SysApiAccessLogRepository repository;
|
||||||
|
|
||||||
|
@Async("apiAccessLogExecutor")
|
||||||
|
@Transactional
|
||||||
|
public void recordAsync(SysApiAccessLog entry) {
|
||||||
|
try {
|
||||||
|
if (entry.getCreatedAt() == null) {
|
||||||
|
entry.setCreatedAt(LocalDateTime.now());
|
||||||
|
}
|
||||||
|
repository.save(entry);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to persist API access log: {} {}", entry.getHttpMethod(), entry.getRequestPath(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Map<String, Object>> list(String category, String operator, int limit) {
|
||||||
|
int pageSize = Math.max(1, Math.min(limit > 0 ? limit : 50, MAX_LIST));
|
||||||
|
List<SysApiAccessLog> rows = repository.search(
|
||||||
|
StringUtils.hasText(category) ? category.trim() : null,
|
||||||
|
StringUtils.hasText(operator) ? operator.trim() : null,
|
||||||
|
PageRequest.of(0, pageSize));
|
||||||
|
List<Map<String, Object>> result = new ArrayList<>(rows.size());
|
||||||
|
for (SysApiAccessLog row : rows) {
|
||||||
|
result.add(toView(row));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String categorize(String path) {
|
||||||
|
String value = path == null ? "" : path.toLowerCase(Locale.ROOT);
|
||||||
|
if (value.startsWith("/api/logs")) return "系统日志";
|
||||||
|
if (value.startsWith("/api/auth") || value.contains("/login") || value.contains("/callback")) return "认证登录";
|
||||||
|
if (value.startsWith("/api/applications") || value.startsWith("/api/reim") || value.contains("/attachment")) return "报销申请";
|
||||||
|
if (value.startsWith("/api/payments") || value.contains("/payment")) return "付款操作";
|
||||||
|
if (value.contains("/finance") || value.contains("/receipt")) return "收单操作";
|
||||||
|
if (value.contains("/feishu/directory")) return "飞书通讯录";
|
||||||
|
if (value.startsWith("/api/feishu")) return "飞书集成";
|
||||||
|
if (value.contains("/integration") || value.contains("/kingdee")) return "配置管理";
|
||||||
|
if (value.contains("/group") || value.contains("/role") || value.contains("/permission") || value.contains("/users")) return "人员权限";
|
||||||
|
if (value.contains("/expense-type") || value.contains("/payee") || value.contains("/source")) return "主数据";
|
||||||
|
if (value.contains("/scheduled")) return "自动任务";
|
||||||
|
return "接口访问";
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> toView(SysApiAccessLog row) {
|
||||||
|
Map<String, Object> view = new LinkedHashMap<>();
|
||||||
|
String action = row.getHttpMethod() + " " + row.getRequestPath();
|
||||||
|
String detail = "状态 " + row.getStatusCode()
|
||||||
|
+ " · 耗时 " + row.getDurationMs() + "ms"
|
||||||
|
+ (StringUtils.hasText(row.getClientIp()) ? " · IP " + row.getClientIp() : "")
|
||||||
|
+ (StringUtils.hasText(row.getQueryString()) ? " · " + row.getQueryString() : "")
|
||||||
|
+ (StringUtils.hasText(row.getErrorMessage()) ? " · " + row.getErrorMessage() : "");
|
||||||
|
view.put("id", row.getId());
|
||||||
|
view.put("requestId", row.getRequestId());
|
||||||
|
view.put("operator", row.getOperatorName());
|
||||||
|
view.put("operatorId", row.getOperatorId());
|
||||||
|
view.put("action", action);
|
||||||
|
view.put("detail", detail);
|
||||||
|
view.put("category", row.getCategory());
|
||||||
|
view.put("method", row.getHttpMethod());
|
||||||
|
view.put("path", row.getRequestPath());
|
||||||
|
view.put("query", row.getQueryString());
|
||||||
|
view.put("statusCode", row.getStatusCode());
|
||||||
|
view.put("durationMs", row.getDurationMs());
|
||||||
|
view.put("clientIp", row.getClientIp());
|
||||||
|
view.put("userAgent", row.getUserAgent());
|
||||||
|
view.put("errorMessage", row.getErrorMessage());
|
||||||
|
view.put("time", row.getCreatedAt() == null ? "" : TIME_FORMAT.format(row.getCreatedAt()));
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,82 +5,90 @@ import com.finance.system.adapter.kingdee.KingdeeConfig;
|
|||||||
import com.finance.system.entity.SysIntegrationConfig;
|
import com.finance.system.entity.SysIntegrationConfig;
|
||||||
import com.finance.system.repository.SysIntegrationConfigRepository;
|
import com.finance.system.repository.SysIntegrationConfigRepository;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.HashMap;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/** Read-through DB configuration with environment-property fallback. */
|
/**
|
||||||
|
* Feishu/Kingdee system credentials come from application.yml / env.
|
||||||
|
* Only the Feishu approval definition code may be overridden from
|
||||||
|
* {@code sys_integration_config} via 配置管理.
|
||||||
|
*/
|
||||||
@Component
|
@Component
|
||||||
public class IntegrationConfigReader {
|
public class IntegrationConfigReader {
|
||||||
/** Internal persistence key; it is never part of the public allow-list. */
|
/** Internal persistence key retained for compatibility with older callers. */
|
||||||
public static final String INTERNAL_ENABLED_KEY = "__enabled";
|
public static final String INTERNAL_ENABLED_KEY = "__enabled";
|
||||||
private final SysIntegrationConfigRepository repository;
|
|
||||||
private final FeishuConfig feishuConfig;
|
private final FeishuConfig feishuConfig;
|
||||||
private final KingdeeConfig kingdeeConfig;
|
private final KingdeeConfig kingdeeConfig;
|
||||||
private IntegrationConfigCrypto integrationConfigCrypto;
|
private final SysIntegrationConfigRepository integrationConfigRepository;
|
||||||
@Autowired private org.springframework.jdbc.core.JdbcTemplate jdbc;
|
|
||||||
|
|
||||||
/** One database statement, bypassing the JPA first-level cache. Call under the
|
public IntegrationConfigReader(
|
||||||
* directory mutex when using the result for a publication/login write.
|
FeishuConfig feishuConfig,
|
||||||
* The result is internal credential material: never log or serialize it.
|
KingdeeConfig kingdeeConfig,
|
||||||
*/
|
SysIntegrationConfigRepository integrationConfigRepository) {
|
||||||
public java.util.Map<String,String> freshFeishu() {
|
|
||||||
List<SysIntegrationConfig> rows = jdbc.query("SELECT config_key,config_value,secret,enabled FROM sys_integration_config WHERE provider='FEISHU'", (rs, n) -> {
|
|
||||||
SysIntegrationConfig row = new SysIntegrationConfig(); row.setConfigKey(rs.getString("config_key"));
|
|
||||||
row.setConfigValue(rs.getString("config_value")); row.setSecret(rs.getBoolean("secret")); row.setEnabled(rs.getBoolean("enabled")); return row;
|
|
||||||
});
|
|
||||||
java.util.Map<String,String> result = new java.util.HashMap<>();
|
|
||||||
result.put("appId", feishuConfig.getAppId()); result.put("appSecret", feishuConfig.getAppSecret());
|
|
||||||
boolean anyEnabled = false;
|
|
||||||
for (SysIntegrationConfig row : rows) {
|
|
||||||
anyEnabled |= Boolean.TRUE.equals(row.getEnabled());
|
|
||||||
if (StringUtils.hasText(row.getConfigValue())) result.put(row.getConfigKey(), storedValue(row));
|
|
||||||
}
|
|
||||||
if (!result.containsKey(INTERNAL_ENABLED_KEY)) result.put(INTERNAL_ENABLED_KEY,
|
|
||||||
String.valueOf(rows.isEmpty() ? StringUtils.hasText(result.get("appId")) && StringUtils.hasText(result.get("appSecret")) : anyEnabled));
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IntegrationConfigReader(SysIntegrationConfigRepository repository,
|
|
||||||
FeishuConfig feishuConfig, KingdeeConfig kingdeeConfig) {
|
|
||||||
this.repository = repository;
|
|
||||||
this.feishuConfig = feishuConfig;
|
this.feishuConfig = feishuConfig;
|
||||||
this.kingdeeConfig = kingdeeConfig;
|
this.kingdeeConfig = kingdeeConfig;
|
||||||
|
this.integrationConfigRepository = integrationConfigRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Autowired(required = false)
|
/**
|
||||||
public void setIntegrationConfigCrypto(IntegrationConfigCrypto integrationConfigCrypto) {
|
* Feishu credential snapshot used by directory/token adapters.
|
||||||
this.integrationConfigCrypto = integrationConfigCrypto;
|
* Never log or serialize the returned secret values.
|
||||||
|
*/
|
||||||
|
public Map<String, String> freshFeishu() {
|
||||||
|
Map<String, String> result = new HashMap<>();
|
||||||
|
result.put("appId", feishuConfig.getAppId());
|
||||||
|
result.put("appSecret", feishuConfig.getAppSecret());
|
||||||
|
result.put("redirectUri", feishuConfig.getRedirectUri());
|
||||||
|
result.put("syncOrgEnabled", String.valueOf(feishuConfig.isSyncOrgEnabled()));
|
||||||
|
FeishuConfig.Approval approval = feishuConfig.getApproval();
|
||||||
|
if (approval != null) {
|
||||||
|
result.put("approvalCode", resolveApprovalCode(approval.getApprovalCode()));
|
||||||
|
result.put("verificationToken", approval.getVerificationToken());
|
||||||
|
result.put("encryptKey", approval.getEncryptKey());
|
||||||
|
} else {
|
||||||
|
result.put("approvalCode", resolveApprovalCode(null));
|
||||||
|
}
|
||||||
|
result.put(INTERNAL_ENABLED_KEY, String.valueOf(isEnabled("FEISHU")));
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String get(String provider, String key) {
|
public String get(String provider, String key) {
|
||||||
String normalized = normalize(provider);
|
String normalized = normalize(provider);
|
||||||
Optional<SysIntegrationConfig> stored = repository.findByProviderAndConfigKey(normalized, key);
|
if ("FEISHU".equals(normalized) && "approvalCode".equals(key)) {
|
||||||
if (stored.isPresent() && StringUtils.hasText(stored.get().getConfigValue())) {
|
return resolveApprovalCode(environmentValue(normalized, key));
|
||||||
return storedValue(stored.get());
|
|
||||||
}
|
}
|
||||||
return environmentValue(normalized, key);
|
return environmentValue(normalized, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** DB override wins when present; otherwise fall back to yml/env. */
|
||||||
|
private String resolveApprovalCode(String envFallback) {
|
||||||
|
Optional<SysIntegrationConfig> stored = integrationConfigRepository
|
||||||
|
.findByProviderAndConfigKey("FEISHU", "approvalCode");
|
||||||
|
if (stored.isPresent() && StringUtils.hasText(stored.get().getConfigValue())) {
|
||||||
|
return stored.get().getConfigValue().trim();
|
||||||
|
}
|
||||||
|
return StringUtils.hasText(envFallback) ? envFallback.trim() : envFallback;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean getBoolean(String provider, String key, boolean defaultValue) {
|
public boolean getBoolean(String provider, String key, boolean defaultValue) {
|
||||||
String value = get(provider, key);
|
String value = get(provider, key);
|
||||||
return StringUtils.hasText(value) ? Boolean.parseBoolean(value.trim()) : defaultValue;
|
return StringUtils.hasText(value) ? Boolean.parseBoolean(value.trim()) : defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A persisted enable flag is authoritative, including persisted false. */
|
|
||||||
public boolean isEnabled(String provider) {
|
public boolean isEnabled(String provider) {
|
||||||
String normalized = normalize(provider);
|
String normalized = normalize(provider);
|
||||||
List<SysIntegrationConfig> stored = repository.findByProviderOrderByConfigKeyAsc(normalized);
|
|
||||||
Optional<SysIntegrationConfig> explicitEnabled = repository.findByProviderAndConfigKey(normalized, INTERNAL_ENABLED_KEY);
|
|
||||||
if (explicitEnabled.isPresent() && StringUtils.hasText(explicitEnabled.get().getConfigValue())) {
|
|
||||||
return Boolean.parseBoolean(explicitEnabled.get().getConfigValue().trim());
|
|
||||||
}
|
|
||||||
if (stored != null && !stored.isEmpty()) return stored.stream().anyMatch(x -> Boolean.TRUE.equals(x.getEnabled()));
|
|
||||||
if ("KINGDEE".equals(normalized)) return kingdeeConfig.isEnabled();
|
if ("KINGDEE".equals(normalized)) return kingdeeConfig.isEnabled();
|
||||||
return StringUtils.hasText(get("FEISHU", "appId")) && StringUtils.hasText(get("FEISHU", "appSecret"));
|
if ("FEISHU".equals(normalized)) {
|
||||||
|
return feishuConfig.isEnabled()
|
||||||
|
&& StringUtils.hasText(feishuConfig.getAppId())
|
||||||
|
&& StringUtils.hasText(feishuConfig.getAppSecret());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String environmentValue(String provider, String key) {
|
private String environmentValue(String provider, String key) {
|
||||||
@@ -88,13 +96,15 @@ public class IntegrationConfigReader {
|
|||||||
if ("appId".equals(key)) return feishuConfig.getAppId();
|
if ("appId".equals(key)) return feishuConfig.getAppId();
|
||||||
if ("appSecret".equals(key)) return feishuConfig.getAppSecret();
|
if ("appSecret".equals(key)) return feishuConfig.getAppSecret();
|
||||||
if ("redirectUri".equals(key)) return feishuConfig.getRedirectUri();
|
if ("redirectUri".equals(key)) return feishuConfig.getRedirectUri();
|
||||||
|
if ("syncOrgEnabled".equals(key)) return String.valueOf(feishuConfig.isSyncOrgEnabled());
|
||||||
|
if ("enabled".equals(key) || INTERNAL_ENABLED_KEY.equals(key)) return String.valueOf(isEnabled("FEISHU"));
|
||||||
FeishuConfig.Approval approval = feishuConfig.getApproval();
|
FeishuConfig.Approval approval = feishuConfig.getApproval();
|
||||||
if (approval == null) return null;
|
if (approval == null) return null;
|
||||||
if ("approvalCode".equals(key)) return approval.getApprovalCode();
|
if ("approvalCode".equals(key)) return approval.getApprovalCode();
|
||||||
if ("verificationToken".equals(key)) return approval.getVerificationToken();
|
if ("verificationToken".equals(key)) return approval.getVerificationToken();
|
||||||
if ("encryptKey".equals(key)) return approval.getEncryptKey();
|
if ("encryptKey".equals(key)) return approval.getEncryptKey();
|
||||||
} else if ("KINGDEE".equals(provider)) {
|
} else if ("KINGDEE".equals(provider)) {
|
||||||
if ("enabled".equals(key)) return String.valueOf(kingdeeConfig.isEnabled());
|
if ("enabled".equals(key) || INTERNAL_ENABLED_KEY.equals(key)) return String.valueOf(kingdeeConfig.isEnabled());
|
||||||
if ("baseUrl".equals(key)) return kingdeeConfig.getBaseUrl();
|
if ("baseUrl".equals(key)) return kingdeeConfig.getBaseUrl();
|
||||||
if ("clientId".equals(key)) return kingdeeConfig.getClientId();
|
if ("clientId".equals(key)) return kingdeeConfig.getClientId();
|
||||||
if ("clientSecret".equals(key)) return kingdeeConfig.getClientSecret();
|
if ("clientSecret".equals(key)) return kingdeeConfig.getClientSecret();
|
||||||
@@ -103,15 +113,7 @@ public class IntegrationConfigReader {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String storedValue(SysIntegrationConfig config) {
|
private String normalize(String provider) {
|
||||||
if (!Boolean.TRUE.equals(config.getSecret())) return config.getConfigValue();
|
return provider == null ? "" : provider.trim().toUpperCase(Locale.ROOT);
|
||||||
if (integrationConfigCrypto == null && IntegrationConfigCrypto.isEncrypted(config.getConfigValue())) {
|
|
||||||
throw new IllegalStateException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能读取加密集成配置");
|
|
||||||
}
|
}
|
||||||
// Non-ENC values are legacy data and remain readable for compatibility.
|
|
||||||
return integrationConfigCrypto == null ? config.getConfigValue()
|
|
||||||
: integrationConfigCrypto.decrypt(config.getConfigValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalize(String provider) { return provider == null ? "" : provider.trim().toUpperCase(Locale.ROOT); }
|
|
||||||
}
|
}
|
||||||
@@ -6,10 +6,10 @@ import com.finance.system.entity.SysIntegrationConfig;
|
|||||||
import com.finance.system.exception.BadRequestException;
|
import com.finance.system.exception.BadRequestException;
|
||||||
import com.finance.system.repository.SysIntegrationConfigRepository;
|
import com.finance.system.repository.SysIntegrationConfigRepository;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
|
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
@@ -17,32 +17,19 @@ import java.net.URISyntaxException;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allow-listed integration settings. Secrets are write-only from the API.
|
* 配置管理仅开放飞书「审批定义编码」;飞书/金蝶系统凭证来自 application.yml。
|
||||||
* Runtime property based clients remain the safe default when DB settings are absent;
|
|
||||||
* this service never logs a setting value.
|
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class IntegrationConfigService {
|
public class IntegrationConfigService {
|
||||||
private static final String DEFAULT_KINGDEE_HOST = "app.kingdee.com";
|
private static final String DEFAULT_KINGDEE_HOST = "app.kingdee.com";
|
||||||
private static final Map<String, List<Field>> FIELDS = new LinkedHashMap<>();
|
private static final String FEISHU = "FEISHU";
|
||||||
static {
|
private static final String KINGDEE = "KINGDEE";
|
||||||
FIELDS.put("FEISHU", Arrays.asList(
|
private static final String APPROVAL_CODE_KEY = "approvalCode";
|
||||||
new Field("appId", "App ID", false), new Field("appSecret", "App Secret", true),
|
|
||||||
new Field("redirectUri", "Redirect URI", false), new Field("approvalCode", "审批定义编码", false),
|
|
||||||
new Field("verificationToken", "Verification Token", true), new Field("encryptKey", "Encrypt Key", true),
|
|
||||||
new Field("syncOrgEnabled", "同步组织架构", false), new Field("syncApprovalEnabled", "同步审批", false)));
|
|
||||||
FIELDS.put("KINGDEE", Arrays.asList(
|
|
||||||
new Field("enabled", "启用金蝶", false), new Field("baseUrl", "Base URL", false),
|
|
||||||
new Field("clientId", "Client ID", true), new Field("clientSecret", "Client Secret", true),
|
|
||||||
new Field("dbId", "账套 ID", false), new Field("syncEnabled", "启用同步", false),
|
|
||||||
new Field("syncIntervalMinutes", "同步间隔(分钟)", false)));
|
|
||||||
}
|
|
||||||
|
|
||||||
private final SysIntegrationConfigRepository repository;
|
private final SysIntegrationConfigRepository repository;
|
||||||
private FeishuAuthService feishuAuthService;
|
private FeishuAuthService feishuAuthService;
|
||||||
private KingdeeClient kingdeeClient;
|
private KingdeeClient kingdeeClient;
|
||||||
private IntegrationConfigReader integrationConfigReader;
|
private IntegrationConfigReader integrationConfigReader;
|
||||||
private IntegrationConfigCrypto integrationConfigCrypto;
|
|
||||||
@Autowired private org.springframework.jdbc.core.JdbcTemplate jdbc;
|
@Autowired private org.springframework.jdbc.core.JdbcTemplate jdbc;
|
||||||
@javax.persistence.PersistenceContext private javax.persistence.EntityManager entityManager;
|
@javax.persistence.PersistenceContext private javax.persistence.EntityManager entityManager;
|
||||||
@Value("${kingdee.allowed-hosts:app.kingdee.com}")
|
@Value("${kingdee.allowed-hosts:app.kingdee.com}")
|
||||||
@@ -52,162 +39,135 @@ public class IntegrationConfigService {
|
|||||||
@Autowired(required = false) public void setFeishuAuthService(FeishuAuthService value) { this.feishuAuthService = value; }
|
@Autowired(required = false) public void setFeishuAuthService(FeishuAuthService value) { this.feishuAuthService = value; }
|
||||||
@Autowired(required = false) public void setKingdeeClient(KingdeeClient value) { this.kingdeeClient = value; }
|
@Autowired(required = false) public void setKingdeeClient(KingdeeClient value) { this.kingdeeClient = value; }
|
||||||
@Autowired(required = false) public void setIntegrationConfigReader(IntegrationConfigReader value) { this.integrationConfigReader = value; }
|
@Autowired(required = false) public void setIntegrationConfigReader(IntegrationConfigReader value) { this.integrationConfigReader = value; }
|
||||||
@Autowired(required = false) public void setIntegrationConfigCrypto(IntegrationConfigCrypto value) { this.integrationConfigCrypto = value; }
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public Map<String, Object> view() {
|
public Map<String, Object> view() {
|
||||||
Map<String, Object> result = new LinkedHashMap<>();
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
result.put("feishu", providerView("FEISHU")); result.put("kingdee", providerView("KINGDEE")); return result;
|
result.put("feishu", feishuApprovalView());
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.REQUIRES_NEW,
|
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.REQUIRES_NEW,
|
||||||
isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED, timeout = 30)
|
isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED, timeout = 30)
|
||||||
public void update(Map<String, Object> body) {
|
public void update(Map<String, Object> body) {
|
||||||
String provider = provider(body == null ? null : body.get("provider"));
|
String provider = provider(body == null ? null : body.get("provider"));
|
||||||
// Publication uses this same singleton and holds it through commit.
|
if (KINGDEE.equals(provider)) {
|
||||||
if ("FEISHU".equals(provider)) FeishuDirectoryLock.acquire(jdbc);
|
throw new BadRequestException("金蝶系统账号由后端配置文件维护;员工账号请在「员工金蝶账号绑定」中维护");
|
||||||
Map<?, ?> values = body == null || !(body.get("values") instanceof Map) ? Collections.emptyMap() : (Map<?, ?>) body.get("values");
|
}
|
||||||
Map<String, Field> allowList = new HashMap<>(); for (Field field : FIELDS.get(provider)) allowList.put(field.key, field);
|
Map<?, ?> values = body == null || !(body.get("values") instanceof Map)
|
||||||
Boolean enabled = booleanValue(body == null ? null : body.get("enabled"), false);
|
? Collections.emptyMap() : (Map<?, ?>) body.get("values");
|
||||||
|
if (values.isEmpty()) throw new BadRequestException("请填写审批定义编码");
|
||||||
for (Object rawKey : values.keySet()) {
|
for (Object rawKey : values.keySet()) {
|
||||||
String key = String.valueOf(rawKey);
|
if (!APPROVAL_CODE_KEY.equals(String.valueOf(rawKey))) {
|
||||||
if (!allowList.containsKey(key)) throw new BadRequestException("不支持的集成配置项: " + key);
|
throw new BadRequestException("配置管理仅支持保存审批定义编码");
|
||||||
Field field = allowList.get(key);
|
|
||||||
if (field.secret && values.get(rawKey) != null
|
|
||||||
&& StringUtils.hasText(String.valueOf(values.get(rawKey)))) {
|
|
||||||
if (integrationConfigCrypto == null) {
|
|
||||||
throw new BadRequestException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能保存敏感集成配置");
|
|
||||||
}
|
|
||||||
integrationConfigCrypto.assertConfigured();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Object baseUrl = values.get("baseUrl");
|
Object raw = values.get(APPROVAL_CODE_KEY);
|
||||||
if ("KINGDEE".equals(provider) && baseUrl != null && StringUtils.hasText(String.valueOf(baseUrl))) {
|
String approvalCode = raw == null ? "" : String.valueOf(raw).trim();
|
||||||
validateKingdeeBaseUrl(String.valueOf(baseUrl));
|
if (!StringUtils.hasText(approvalCode)) {
|
||||||
|
throw new BadRequestException("审批定义编码不能为空");
|
||||||
}
|
}
|
||||||
// Persist the provider switch even when the user has not entered any
|
if (approvalCode.length() > 200) {
|
||||||
// provider fields. This explicit value must override environment
|
throw new BadRequestException("审批定义编码过长");
|
||||||
// configuration, including an explicit false.
|
}
|
||||||
SysIntegrationConfig switchConfig = repository
|
SysIntegrationConfig config = repository.findByProviderAndConfigKey(FEISHU, APPROVAL_CODE_KEY)
|
||||||
.findByProviderAndConfigKey(provider, IntegrationConfigReader.INTERNAL_ENABLED_KEY)
|
|
||||||
.orElseGet(SysIntegrationConfig::new);
|
.orElseGet(SysIntegrationConfig::new);
|
||||||
refreshExisting(switchConfig);
|
|
||||||
switchConfig.setProvider(provider);
|
|
||||||
switchConfig.setConfigKey(IntegrationConfigReader.INTERNAL_ENABLED_KEY);
|
|
||||||
switchConfig.setConfigValue(String.valueOf(enabled));
|
|
||||||
switchConfig.setSecret(false);
|
|
||||||
switchConfig.setEnabled(enabled);
|
|
||||||
repository.save(switchConfig);
|
|
||||||
for (Map.Entry<?, ?> entry : values.entrySet()) {
|
|
||||||
String key = String.valueOf(entry.getKey()); Field field = allowList.get(key);
|
|
||||||
String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue());
|
|
||||||
Optional<SysIntegrationConfig> existing = repository.findByProviderAndConfigKey(provider, key);
|
|
||||||
existing.ifPresent(this::refreshExisting);
|
|
||||||
if (field.secret && !StringUtils.hasText(value) && existing.isPresent()) continue;
|
|
||||||
if (field.secret && StringUtils.hasText(value)) {
|
|
||||||
value = integrationConfigCrypto.encrypt(value);
|
|
||||||
}
|
|
||||||
SysIntegrationConfig config = existing.orElseGet(SysIntegrationConfig::new);
|
|
||||||
config.setProvider(provider); config.setConfigKey(key); config.setConfigValue(value);
|
|
||||||
config.setSecret(field.secret); config.setEnabled(enabled); repository.save(config);
|
|
||||||
}
|
|
||||||
// Keep the enable switch consistent for all existing keys without creating
|
|
||||||
// an unlisted sentinel key (which would make configuration injection possible).
|
|
||||||
repository.flush();
|
|
||||||
for (SysIntegrationConfig config : repository.findByProviderOrderByConfigKeyAsc(provider)) {
|
|
||||||
refreshExisting(config);
|
|
||||||
// A legacy plaintext secret may be read, but it must never be
|
|
||||||
// written back as part of an unrelated provider update. When the
|
|
||||||
// key is available, transparently migrate it to ENC[v1].
|
|
||||||
if (Boolean.TRUE.equals(config.getSecret())
|
|
||||||
&& StringUtils.hasText(config.getConfigValue())
|
|
||||||
&& !IntegrationConfigCrypto.isEncrypted(config.getConfigValue())) {
|
|
||||||
if (integrationConfigCrypto == null) continue;
|
|
||||||
integrationConfigCrypto.assertConfigured();
|
|
||||||
config.setConfigValue(integrationConfigCrypto.encrypt(config.getConfigValue()));
|
|
||||||
}
|
|
||||||
config.setEnabled(enabled); repository.save(config);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void refreshExisting(SysIntegrationConfig config) {
|
|
||||||
if (config.getId() != null) entityManager.refresh(config);
|
if (config.getId() != null) entityManager.refresh(config);
|
||||||
|
config.setProvider(FEISHU);
|
||||||
|
config.setConfigKey(APPROVAL_CODE_KEY);
|
||||||
|
config.setConfigValue(approvalCode);
|
||||||
|
config.setSecret(false);
|
||||||
|
config.setEnabled(true);
|
||||||
|
repository.saveAndFlush(config);
|
||||||
|
jdbc.update("DELETE FROM sys_integration_config WHERE provider = ? AND config_key = ?",
|
||||||
|
FEISHU, "syncApprovalEnabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public Map<String, Object> test(String requestedProvider) {
|
public Map<String, Object> test(String requestedProvider) {
|
||||||
String provider = provider(requestedProvider);
|
String provider = provider(requestedProvider);
|
||||||
Map<String, Object> current = providerView(provider);
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
boolean configured = Boolean.TRUE.equals(current.get("enabled")) && hasRequiredConfiguration(provider);
|
result.put("provider", provider);
|
||||||
Map<String, Object> result = new LinkedHashMap<>(); result.put("provider", provider); result.put("configured", configured);
|
boolean configured = integrationConfigReader != null && integrationConfigReader.isEnabled(provider)
|
||||||
if (!configured) { result.put("success", false); result.put("message", "集成未配置或未启用,未执行外部连接"); return result; }
|
&& hasRequiredConfiguration(provider);
|
||||||
try {
|
result.put("configured", configured);
|
||||||
if ("FEISHU".equals(provider) && feishuAuthService != null) {
|
if (!configured) {
|
||||||
feishuAuthService.getTenantAccessToken(); result.put("success", true); result.put("message", "连接测试成功"); return result;
|
result.put("success", false);
|
||||||
|
result.put("message", "集成未配置或未启用,未执行外部连接");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
if ("KINGDEE".equals(provider) && kingdeeClient != null && kingdeeClient.isEnabled()) {
|
try {
|
||||||
kingdeeClient.login(); result.put("success", true); result.put("message", "连接测试成功"); return result;
|
if (FEISHU.equals(provider) && feishuAuthService != null) {
|
||||||
|
feishuAuthService.getTenantAccessToken();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", "连接测试成功");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (KINGDEE.equals(provider) && kingdeeClient != null && kingdeeClient.isEnabled()) {
|
||||||
|
kingdeeClient.login();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", "连接测试成功");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
// Deliberately do not include an exception containing request/config values.
|
result.put("success", false);
|
||||||
result.put("success", false); result.put("message", "外部连接测试失败"); return result;
|
result.put("message", "外部连接测试失败");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
result.put("success", false); result.put("message", "连接测试客户端未配置"); return result;
|
result.put("success", false);
|
||||||
|
result.put("message", "连接测试客户端未配置");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> providerView(String provider) {
|
private Map<String, Object> feishuApprovalView() {
|
||||||
Map<String, SysIntegrationConfig> values = new HashMap<>();
|
boolean enabled = integrationConfigReader != null && integrationConfigReader.isEnabled(FEISHU);
|
||||||
for (SysIntegrationConfig config : repository.findByProviderOrderByConfigKeyAsc(provider)) values.put(config.getConfigKey(), config);
|
String approvalCode = integrationConfigReader == null
|
||||||
boolean enabled = integrationConfigReader == null
|
? null : integrationConfigReader.get(FEISHU, APPROVAL_CODE_KEY);
|
||||||
? values.values().stream().anyMatch(x -> Boolean.TRUE.equals(x.getEnabled()))
|
boolean fromDb = repository.findByProviderAndConfigKey(FEISHU, APPROVAL_CODE_KEY)
|
||||||
: integrationConfigReader.isEnabled(provider);
|
.map(row -> StringUtils.hasText(row.getConfigValue()))
|
||||||
List<Map<String, Object>> fields = new ArrayList<>();
|
.orElse(false);
|
||||||
for (Field field : FIELDS.get(provider)) {
|
|
||||||
SysIntegrationConfig config = values.get(field.key);
|
Map<String, Object> field = new LinkedHashMap<>();
|
||||||
String rawValue = config == null && integrationConfigReader != null
|
field.put("key", APPROVAL_CODE_KEY);
|
||||||
? integrationConfigReader.get(provider, field.key)
|
field.put("label", "审批定义编码");
|
||||||
: config == null ? null : storedValue(config);
|
field.put("inputType", "text");
|
||||||
boolean configured = StringUtils.hasText(rawValue);
|
field.put("placeholder", "例如:8A0D2B3C-XXXX-XXXX-XXXX-XXXXXXXXXXXX");
|
||||||
Map<String, Object> item = new LinkedHashMap<>(); item.put("key", field.key); item.put("label", field.label);
|
field.put("helpText", "填写飞书审批管理后台目标审批定义的 approval_code;保存后点击「验证并同步飞书审批」拉取流程并订阅事件。");
|
||||||
item.put("value", field.secret ? (configured ? RoleService.mask(rawValue) : "") : (rawValue == null ? "" : rawValue));
|
field.put("secret", false);
|
||||||
item.put("secret", field.secret); item.put("configured", configured); fields.add(item);
|
field.put("readOnly", false);
|
||||||
}
|
field.put("value", approvalCode == null ? "" : approvalCode);
|
||||||
Map<String, Object> result = new LinkedHashMap<>(); result.put("enabled", enabled); result.put("fields", fields); return result;
|
field.put("configured", StringUtils.hasText(approvalCode));
|
||||||
|
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("enabled", enabled);
|
||||||
|
result.put("readOnly", false);
|
||||||
|
result.put("source", fromDb ? "database" : "application.yml");
|
||||||
|
result.put("fields", Collections.singletonList(field));
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean hasRequiredConfiguration(String provider) {
|
private boolean hasRequiredConfiguration(String provider) {
|
||||||
if (integrationConfigReader != null) {
|
if (integrationConfigReader == null) return false;
|
||||||
if ("FEISHU".equals(provider)) return present(integrationConfigReader.get(provider, "appId")) && present(integrationConfigReader.get(provider, "appSecret"));
|
if (FEISHU.equals(provider)) {
|
||||||
return safeKingdeeUrl(integrationConfigReader.get(provider, "baseUrl")) && present(integrationConfigReader.get(provider, "clientId"))
|
return present(integrationConfigReader.get(provider, "appId"))
|
||||||
&& present(integrationConfigReader.get(provider, "clientSecret")) && present(integrationConfigReader.get(provider, "dbId"));
|
&& present(integrationConfigReader.get(provider, "appSecret"));
|
||||||
}
|
}
|
||||||
Map<String, SysIntegrationConfig> values = new HashMap<>();
|
return safeKingdeeUrl(integrationConfigReader.get(provider, "baseUrl"))
|
||||||
for (SysIntegrationConfig x : repository.findByProviderOrderByConfigKeyAsc(provider)) values.put(x.getConfigKey(), x);
|
&& present(integrationConfigReader.get(provider, "clientId"))
|
||||||
if ("FEISHU".equals(provider)) return present(values, "appId") && present(values, "appSecret");
|
&& present(integrationConfigReader.get(provider, "clientSecret"))
|
||||||
return present(values, "baseUrl") && safeKingdeeUrl(values.get("baseUrl").getConfigValue())
|
&& present(integrationConfigReader.get(provider, "dbId"));
|
||||||
&& present(values, "clientId") && present(values, "clientSecret") && present(values, "dbId");
|
}
|
||||||
|
|
||||||
|
private boolean present(String value) { return StringUtils.hasText(value); }
|
||||||
|
|
||||||
|
private String provider(Object value) {
|
||||||
|
String result = value == null ? "" : String.valueOf(value).trim().toUpperCase(Locale.ROOT);
|
||||||
|
if (!FEISHU.equals(result) && !KINGDEE.equals(result)) {
|
||||||
|
throw new BadRequestException("provider 必须是 FEISHU 或 KINGDEE");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
private boolean present(Map<String, SysIntegrationConfig> values, String key) {
|
|
||||||
return values.containsKey(key) && StringUtils.hasText(storedValue(values.get(key)));
|
|
||||||
}
|
|
||||||
private boolean present(String value) { return StringUtils.hasText(value); }
|
|
||||||
private String storedValue(SysIntegrationConfig config) {
|
|
||||||
if (config == null) return null;
|
|
||||||
if (!Boolean.TRUE.equals(config.getSecret())) return config.getConfigValue();
|
|
||||||
if (integrationConfigCrypto == null && IntegrationConfigCrypto.isEncrypted(config.getConfigValue())) {
|
|
||||||
throw new IllegalStateException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能读取加密集成配置");
|
|
||||||
}
|
|
||||||
return integrationConfigCrypto == null ? config.getConfigValue()
|
|
||||||
: integrationConfigCrypto.decrypt(config.getConfigValue());
|
|
||||||
}
|
|
||||||
private String provider(Object value) { String result = value == null ? "" : String.valueOf(value).trim().toUpperCase(Locale.ROOT); if (!FIELDS.containsKey(result)) throw new BadRequestException("provider 必须是 FEISHU 或 KINGDEE"); return result; }
|
|
||||||
private Boolean booleanValue(Object value, boolean defaultValue) { if (value == null) return defaultValue; if (value instanceof Boolean) return (Boolean) value; if ("true".equalsIgnoreCase(String.valueOf(value)) || "false".equalsIgnoreCase(String.valueOf(value))) return Boolean.valueOf(String.valueOf(value)); throw new BadRequestException("enabled 必须是布尔值"); }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates the outbound Kingdee endpoint before it can be persisted or
|
|
||||||
* considered configured. Exact hosts (or an explicitly configured
|
|
||||||
* *.suffix entry) are required, and every resolved address must be public.
|
|
||||||
*/
|
|
||||||
public void validateKingdeeBaseUrl(String rawUrl) {
|
public void validateKingdeeBaseUrl(String rawUrl) {
|
||||||
if (!StringUtils.hasText(rawUrl)) throw new BadRequestException("金蝶 baseUrl 不能为空");
|
if (!StringUtils.hasText(rawUrl)) throw new BadRequestException("金蝶 baseUrl 不能为空");
|
||||||
final URI uri;
|
final URI uri;
|
||||||
@@ -232,13 +192,10 @@ public class IntegrationConfigService {
|
|||||||
} catch (BadRequestException e) {
|
} catch (BadRequestException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// DNS may be unavailable during an offline configuration
|
// DNS may be unavailable; host allowlist remains authoritative.
|
||||||
// change. The explicit host allowlist remains authoritative;
|
|
||||||
// literal/private addresses were already rejected above.
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Validation sink used immediately before every outbound Kingdee URL is built. */
|
|
||||||
public String validateAndNormalizeKingdeeBaseUrl(String rawUrl) {
|
public String validateAndNormalizeKingdeeBaseUrl(String rawUrl) {
|
||||||
validateKingdeeBaseUrl(rawUrl);
|
validateKingdeeBaseUrl(rawUrl);
|
||||||
String normalized = rawUrl.trim();
|
String normalized = rawUrl.trim();
|
||||||
@@ -282,9 +239,4 @@ public class IntegrationConfigService {
|
|||||||
return b.length == 4 && (b[0] & 0xff) == 169 && (b[1] & 0xff) == 254
|
return b.length == 4 && (b[0] & 0xff) == 169 && (b[1] & 0xff) == 254
|
||||||
&& (b[2] & 0xff) == 169 && (b[3] & 0xff) == 254;
|
&& (b[2] & 0xff) == 169 && (b[3] & 0xff) == 254;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class Field {
|
|
||||||
private final String key; private final String label; private final boolean secret;
|
|
||||||
private Field(String key, String label, boolean secret) { this.key = key; this.label = label; this.secret = secret; }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package com.finance.system.service;
|
||||||
|
|
||||||
|
import com.finance.system.adapter.kingdee.KingdeeClient;
|
||||||
|
import com.finance.system.entity.SysUser;
|
||||||
|
import com.finance.system.entity.SysUserKingdeeAccount;
|
||||||
|
import com.finance.system.exception.BadRequestException;
|
||||||
|
import com.finance.system.exception.BusinessException;
|
||||||
|
import com.finance.system.repository.SysUserKingdeeAccountRepository;
|
||||||
|
import com.finance.system.repository.SysUserRepository;
|
||||||
|
import org.springframework.context.annotation.Lazy;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Employee Kingdee credentials for document writes.
|
||||||
|
* Scope is permission-driven: view/bind/unbind own vs all.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class KingdeeAccountBindingService {
|
||||||
|
|
||||||
|
public static final String VIEW_OWN = "finance.kingdee.account.view-own";
|
||||||
|
public static final String VIEW_ALL = "finance.kingdee.account.view-all";
|
||||||
|
public static final String BIND_OWN = "finance.kingdee.account.bind-own";
|
||||||
|
public static final String BIND_ALL = "finance.kingdee.account.bind";
|
||||||
|
public static final String UNBIND_OWN = "finance.kingdee.account.unbind-own";
|
||||||
|
public static final String UNBIND_ALL = "finance.kingdee.account.unbind";
|
||||||
|
public static final String DOCUMENT_WRITE = "finance.kingdee.document.write";
|
||||||
|
|
||||||
|
private final SysUserKingdeeAccountRepository bindingRepository;
|
||||||
|
private final SysUserRepository userRepository;
|
||||||
|
private final IntegrationConfigCrypto crypto;
|
||||||
|
private final KingdeeClient kingdeeClient;
|
||||||
|
private final JdbcTemplate jdbc;
|
||||||
|
private final RoleService roleService;
|
||||||
|
|
||||||
|
public KingdeeAccountBindingService(
|
||||||
|
SysUserKingdeeAccountRepository bindingRepository,
|
||||||
|
SysUserRepository userRepository,
|
||||||
|
IntegrationConfigCrypto crypto,
|
||||||
|
@Lazy KingdeeClient kingdeeClient,
|
||||||
|
JdbcTemplate jdbc,
|
||||||
|
RoleService roleService) {
|
||||||
|
this.bindingRepository = bindingRepository;
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.crypto = crypto;
|
||||||
|
this.kingdeeClient = kingdeeClient;
|
||||||
|
this.jdbc = jdbc;
|
||||||
|
this.roleService = roleService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Map<String, Object>> listBindings(Long actorId) {
|
||||||
|
if (actorId == null) throw new AccessDeniedException("未登录");
|
||||||
|
boolean viewAll = roleService.hasPermission(actorId, VIEW_ALL);
|
||||||
|
boolean viewOwn = roleService.hasPermission(actorId, VIEW_OWN)
|
||||||
|
|| roleService.hasPermission(actorId, "page.kingdee-account-binding");
|
||||||
|
if (!viewAll && !viewOwn) throw new AccessDeniedException("无权查看金蝶账号绑定");
|
||||||
|
|
||||||
|
Set<Long> eligibleIds = eligibleUserIds();
|
||||||
|
Map<Long, SysUserKingdeeAccount> byUser = bindingRepository.findAll().stream()
|
||||||
|
.collect(Collectors.toMap(SysUserKingdeeAccount::getUserId, x -> x, (a, b) -> a));
|
||||||
|
return userRepository.findAll().stream()
|
||||||
|
.filter(user -> eligibleIds.contains(user.getId()))
|
||||||
|
.filter(user -> viewAll || Objects.equals(user.getId(), actorId))
|
||||||
|
.sorted(Comparator.comparing(SysUser::getRealName, Comparator.nullsLast(String::compareToIgnoreCase)))
|
||||||
|
.map(user -> toView(user, byUser.get(user.getId())))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Map<String, Object> myBinding(Long userId) {
|
||||||
|
SysUser user = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new BadRequestException("用户不存在"));
|
||||||
|
return toView(user, bindingRepository.findById(userId).orElse(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean isBound(Long userId) {
|
||||||
|
return userId != null && bindingRepository.existsByUserId(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public KingdeeCredentials requireCredentials(Long userId) {
|
||||||
|
if (userId == null) throw new BusinessException("未登录,无法使用员工金蝶账号");
|
||||||
|
SysUserKingdeeAccount binding = bindingRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new BusinessException("请先在「配置管理 · 金蝶账号绑定」中绑定金蝶账号后,再变更金蝶云星空财务单据"));
|
||||||
|
return new KingdeeCredentials(binding.getKingdeeUsername(), crypto.decrypt(binding.getKingdeePassword()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Map<String, Object> bind(Long userId, String username, String password, Long operatorId, boolean verifyLogin) {
|
||||||
|
assertCanMutate(operatorId, userId, BIND_ALL, BIND_OWN, "绑定");
|
||||||
|
if (userId == null) throw new BadRequestException("用户不能为空");
|
||||||
|
SysUser user = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new BadRequestException("用户不存在"));
|
||||||
|
if (!eligibleUserIds().contains(userId)) {
|
||||||
|
throw new BadRequestException("仅可为财务角色,或已授予「变更金蝶财务单据」权限的人员绑定金蝶账号");
|
||||||
|
}
|
||||||
|
String normalizedUser = normalizeUsername(username);
|
||||||
|
if (!StringUtils.hasText(password)) throw new BadRequestException("金蝶密码不能为空");
|
||||||
|
crypto.assertConfigured();
|
||||||
|
|
||||||
|
bindingRepository.findByKingdeeUsername(normalizedUser).ifPresent(existing -> {
|
||||||
|
if (!Objects.equals(existing.getUserId(), userId)) {
|
||||||
|
throw new BadRequestException("该金蝶账号已绑定到其他员工");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (verifyLogin) {
|
||||||
|
kingdeeClient.validateUserCredentials(normalizedUser, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
SysUserKingdeeAccount binding = bindingRepository.findById(userId).orElseGet(SysUserKingdeeAccount::new);
|
||||||
|
binding.setUserId(userId);
|
||||||
|
binding.setKingdeeUsername(normalizedUser);
|
||||||
|
binding.setKingdeePassword(crypto.encrypt(password.trim()));
|
||||||
|
binding.setBoundBy(operatorId);
|
||||||
|
if (binding.getBoundAt() == null) binding.setBoundAt(LocalDateTime.now());
|
||||||
|
bindingRepository.save(binding);
|
||||||
|
return toView(user, binding);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void unbind(Long userId, Long operatorId) {
|
||||||
|
assertCanMutate(operatorId, userId, UNBIND_ALL, UNBIND_OWN, "解绑");
|
||||||
|
if (userId == null || !bindingRepository.existsByUserId(userId)) {
|
||||||
|
throw new BadRequestException("该员工尚未绑定金蝶账号");
|
||||||
|
}
|
||||||
|
bindingRepository.deleteById(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Map<String, Object> testBinding(Long userId, Long operatorId) {
|
||||||
|
assertCanMutate(operatorId, userId, BIND_ALL, BIND_OWN, "验证");
|
||||||
|
KingdeeCredentials credentials = requireCredentials(userId);
|
||||||
|
kingdeeClient.validateUserCredentials(credentials.getUsername(), credentials.getPassword());
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", "金蝶账号验证成功");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertCanMutate(Long operatorId, Long targetUserId, String allCode, String ownCode, String action) {
|
||||||
|
if (operatorId == null) throw new AccessDeniedException("未登录");
|
||||||
|
boolean canAll = roleService.hasEditPermission(operatorId, allCode);
|
||||||
|
boolean canOwn = roleService.hasEditPermission(operatorId, ownCode);
|
||||||
|
if (!canAll && !canOwn) throw new AccessDeniedException("无权" + action + "金蝶账号");
|
||||||
|
if (!canAll && !Objects.equals(operatorId, targetUserId)) {
|
||||||
|
throw new AccessDeniedException("当前权限仅可" + action + "本人的金蝶账号");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** FINANCE role ∪ document.write EDIT holders ∪ already bound. */
|
||||||
|
private Set<Long> eligibleUserIds() {
|
||||||
|
List<Long> ids = jdbc.queryForList(
|
||||||
|
"SELECT DISTINCT m.user_id "
|
||||||
|
+ "FROM sys_user_group_member m "
|
||||||
|
+ "JOIN sys_user_group_role gr ON gr.group_id = m.group_id "
|
||||||
|
+ "JOIN sys_role r ON r.id = gr.role_id "
|
||||||
|
+ "WHERE r.role_code = 'FINANCE' "
|
||||||
|
+ "UNION "
|
||||||
|
+ "SELECT DISTINCT m.user_id "
|
||||||
|
+ "FROM sys_user_group_member m "
|
||||||
|
+ "JOIN sys_user_group_role gr ON gr.group_id = m.group_id "
|
||||||
|
+ "JOIN sys_role_permission rp ON rp.role_id = gr.role_id "
|
||||||
|
+ "JOIN sys_permission p ON p.id = rp.permission_id "
|
||||||
|
+ "WHERE p.permission_code = ? AND rp.access_level = 'EDIT' "
|
||||||
|
+ "UNION "
|
||||||
|
+ "SELECT user_id FROM sys_user_kingdee_account",
|
||||||
|
Long.class,
|
||||||
|
DOCUMENT_WRITE);
|
||||||
|
return new LinkedHashSet<>(ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> toView(SysUser user, SysUserKingdeeAccount binding) {
|
||||||
|
Map<String, Object> view = new LinkedHashMap<>();
|
||||||
|
view.put("userId", user.getId());
|
||||||
|
view.put("realName", user.getRealName());
|
||||||
|
view.put("employeeNo", user.getEmployeeNo());
|
||||||
|
view.put("status", user.getStatus());
|
||||||
|
view.put("bound", binding != null);
|
||||||
|
view.put("kingdeeUsername", binding == null ? null : binding.getKingdeeUsername());
|
||||||
|
view.put("boundAt", binding == null ? null : binding.getBoundAt());
|
||||||
|
view.put("updatedAt", binding == null ? null : binding.getUpdatedAt());
|
||||||
|
view.put("boundBy", binding == null ? null : binding.getBoundBy());
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeUsername(String username) {
|
||||||
|
if (!StringUtils.hasText(username)) throw new BadRequestException("金蝶用户名不能为空");
|
||||||
|
String value = username.trim();
|
||||||
|
if (value.length() > 120) throw new BadRequestException("金蝶用户名过长");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
@lombok.Value
|
||||||
|
public static class KingdeeCredentials {
|
||||||
|
String username;
|
||||||
|
String password;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package com.finance.system.service;
|
||||||
|
|
||||||
|
import com.finance.system.adapter.feishu.FeishuApprovalFileClient;
|
||||||
|
import com.finance.system.dto.AttachmentDto;
|
||||||
|
import com.finance.system.dto.ExpenseItemDto;
|
||||||
|
import com.finance.system.dto.ReimbursementFormField;
|
||||||
|
import com.finance.system.entity.ReimApplication;
|
||||||
|
import com.finance.system.entity.ReimAttachment;
|
||||||
|
import com.finance.system.entity.ReimExpenseItem;
|
||||||
|
import com.finance.system.enums.ApplicationStatus;
|
||||||
|
import com.finance.system.exception.BusinessException;
|
||||||
|
import com.finance.system.exception.ResourceNotFoundException;
|
||||||
|
import com.finance.system.repository.ReimApplicationRepository;
|
||||||
|
import com.finance.system.repository.ReimAttachmentRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ReimbursementAttachmentService {
|
||||||
|
public static final long MAX_FILE_BYTES = 50L * 1024L * 1024L;
|
||||||
|
public static final long MAX_STAGED_BYTES = 500L * 1024L * 1024L;
|
||||||
|
public static final long MAX_STAGED_COUNT = 50L;
|
||||||
|
public static final long MAX_DAILY_BYTES = 1024L * 1024L * 1024L;
|
||||||
|
public static final long MAX_DAILY_COUNT = 100L;
|
||||||
|
private static final String UPLOADED = "UPLOADED";
|
||||||
|
private static final String DELETED = "DELETED";
|
||||||
|
private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai");
|
||||||
|
private final ReimbursementFormService forms;
|
||||||
|
private final FeishuApprovalFileClient client;
|
||||||
|
private final ReimAttachmentRepository attachments;
|
||||||
|
private final ReimApplicationRepository applications;
|
||||||
|
private final Set<Long> uploadsInProgress = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
|
public AttachmentDto upload(MultipartFile file, String fingerprint, String controlId, Long userId) {
|
||||||
|
if (userId == null) throw new BusinessException("未登录", 401);
|
||||||
|
String name = safeName(file == null ? null : file.getOriginalFilename());
|
||||||
|
if (file == null || file.isEmpty() || file.getSize() <= 0) throw new BusinessException("附件不能为空", 400);
|
||||||
|
if (file.getSize() > MAX_FILE_BYTES) throw new BusinessException("附件不能超过 50MB", 400);
|
||||||
|
String contentType = allowedContentType(name, file.getContentType());
|
||||||
|
ReimbursementFormField control = forms.requireCurrentAttachmentControl(fingerprint, controlId);
|
||||||
|
if (!uploadsInProgress.add(userId)) throw new BusinessException("同一用户只能同时上传一个附件", 429);
|
||||||
|
try {
|
||||||
|
requireUploadCapacity(userId, file.getSize());
|
||||||
|
byte[] bytes;
|
||||||
|
try { bytes = file.getBytes(); }
|
||||||
|
catch (IOException e) { throw new BusinessException("无法读取附件", 400); }
|
||||||
|
if (bytes.length == 0 || bytes.length > MAX_FILE_BYTES) throw new BusinessException("附件大小无效", 400);
|
||||||
|
requireUploadCapacity(userId, bytes.length);
|
||||||
|
// No database transaction spans this network call. A timeout after the provider
|
||||||
|
// accepted the bytes has an unknown outcome, so it is surfaced and never retried
|
||||||
|
// automatically. A later local save failure can leave a provider-side orphan.
|
||||||
|
String fileCode = client.upload(name, contentType, bytes);
|
||||||
|
ReimAttachment row = ReimAttachment.builder().fileName(name).fileType("attachment")
|
||||||
|
.fileSize((long)bytes.length).contentType(contentType).uploaderId(userId)
|
||||||
|
.formControlId(control.getId()).formFingerprint(fingerprint)
|
||||||
|
.feishuFileCode(fileCode).uploadStatus(UPLOADED).build();
|
||||||
|
return dto(attachments.save(row));
|
||||||
|
} finally {
|
||||||
|
uploadsInProgress.remove(userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireStagedCapacity(Long userId, long incomingBytes) {
|
||||||
|
long count = attachments.countByUploaderIdAndApplicationIdIsNullAndUploadStatus(userId, UPLOADED);
|
||||||
|
Long stored = attachments.sumStagedBytes(userId, UPLOADED);
|
||||||
|
long bytes = stored == null ? 0L : stored;
|
||||||
|
if (count >= MAX_STAGED_COUNT) throw new BusinessException("暂存附件不能超过 50 个", 429);
|
||||||
|
if (incomingBytes > MAX_STAGED_BYTES || bytes > MAX_STAGED_BYTES - incomingBytes)
|
||||||
|
throw new BusinessException("暂存附件总大小不能超过 500MB", 429);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireUploadCapacity(Long userId, long incomingBytes) {
|
||||||
|
requireStagedCapacity(userId, incomingBytes);
|
||||||
|
LocalDateTime start = startOfCurrentShanghaiDay();
|
||||||
|
long count = attachments.countByUploaderIdAndCreatedAtGreaterThanEqual(userId, start);
|
||||||
|
Long stored = attachments.sumUploadedBytesSince(userId, start);
|
||||||
|
long bytes = stored == null ? 0L : stored;
|
||||||
|
if (count >= MAX_DAILY_COUNT) throw new BusinessException("每日上传附件不能超过 100 个", 429);
|
||||||
|
if (incomingBytes > MAX_DAILY_BYTES || bytes > MAX_DAILY_BYTES - incomingBytes)
|
||||||
|
throw new BusinessException("每日上传附件总大小不能超过 1GB", 429);
|
||||||
|
}
|
||||||
|
|
||||||
|
static LocalDateTime startOfCurrentShanghaiDay() {
|
||||||
|
return LocalDate.now(SHANGHAI).atStartOfDay();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void remove(Long id, Long userId) {
|
||||||
|
ReimAttachment row = attachments.findByIdForUpdate(id)
|
||||||
|
.orElseThrow(() -> new ResourceNotFoundException("附件不存在"));
|
||||||
|
if (userId == null || !userId.equals(row.getUploaderId()))
|
||||||
|
throw new org.springframework.security.access.AccessDeniedException("只能删除本人附件");
|
||||||
|
ReimApplication claimedApplication = null;
|
||||||
|
if (row.getApplicationId() != null) {
|
||||||
|
claimedApplication = applications.findByIdForUpdate(row.getApplicationId())
|
||||||
|
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||||
|
if (!userId.equals(claimedApplication.getApplicantId())
|
||||||
|
|| !ApplicationStatus.DRAFT.name().equals(claimedApplication.getApplicationStatus()))
|
||||||
|
throw new BusinessException("只能移除暂存附件或本人草稿附件", 409);
|
||||||
|
}
|
||||||
|
tombstone(row);
|
||||||
|
attachments.save(row);
|
||||||
|
attachments.flush();
|
||||||
|
if (claimedApplication != null) {
|
||||||
|
claimedApplication.setFeishuFormDisplayValues(forms.buildDisplayValues(claimedApplication));
|
||||||
|
applications.save(claimedApplication);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Locks and validates all requested rows before any expense row is removed or written. */
|
||||||
|
public Map<Integer,List<ReimAttachment>> validateClaims(List<ExpenseItemDto> items, String fingerprint,
|
||||||
|
Long userId, ReimApplication existing) {
|
||||||
|
ReimbursementFormField control = forms.requireCurrentAttachmentControl(fingerprint);
|
||||||
|
Map<Integer,List<ReimAttachment>> result = new LinkedHashMap<>();
|
||||||
|
Set<Long> allIds = new HashSet<>();
|
||||||
|
Map<Long,ReimAttachment> loaded = new HashMap<>();
|
||||||
|
List<Long> requested = new ArrayList<>();
|
||||||
|
for (ExpenseItemDto item : items) if (item != null && item.getAttachmentIds() != null)
|
||||||
|
for (Long id : item.getAttachmentIds()) {
|
||||||
|
if (id == null || !allIds.add(id)) throw new BusinessException("附件 ID 不能为空且不能重复", 400);
|
||||||
|
requested.add(id);
|
||||||
|
}
|
||||||
|
if (!requested.isEmpty()) for (ReimAttachment row : attachments.findAllByIdInForUpdate(requested)) loaded.put(row.getId(), row);
|
||||||
|
int index = 0;
|
||||||
|
for (ExpenseItemDto item : items) {
|
||||||
|
List<ReimAttachment> rowValues = new ArrayList<>();
|
||||||
|
List<Long> ids = item.getAttachmentIds() == null ? Collections.emptyList() : item.getAttachmentIds();
|
||||||
|
if (control.isRequired() && ids.isEmpty()) throw new BusinessException("每条费用明细至少需要一个附件", 400);
|
||||||
|
if (ids.size() > 50) throw new BusinessException("单条费用明细附件不能超过 50 个", 400);
|
||||||
|
for (Long id : ids) {
|
||||||
|
ReimAttachment row = loaded.get(id);
|
||||||
|
if (row == null || !UPLOADED.equals(row.getUploadStatus()) || !userId.equals(row.getUploaderId())
|
||||||
|
|| !fingerprint.equals(row.getFormFingerprint()) || !control.getId().equals(row.getFormControlId()))
|
||||||
|
throw new BusinessException("附件无效、已过期或不属于当前用户", 400);
|
||||||
|
if (row.getApplicationId() != null && (existing == null
|
||||||
|
|| !row.getApplicationId().equals(existing.getId())
|
||||||
|
|| !ApplicationStatus.DRAFT.name().equals(existing.getApplicationStatus())))
|
||||||
|
throw new BusinessException("附件已被其他申请占用", 409);
|
||||||
|
rowValues.add(row);
|
||||||
|
}
|
||||||
|
result.put(index++, rowValues);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void detachApplicationAttachments(Long applicationId) {
|
||||||
|
for (ReimAttachment row : attachments.findByApplicationIdAndExpenseItemIdIsNotNullAndUploadStatus(
|
||||||
|
applicationId, UPLOADED)) {
|
||||||
|
row.setExpenseItemId(null);
|
||||||
|
row.setApplicationId(null);
|
||||||
|
attachments.save(row);
|
||||||
|
}
|
||||||
|
attachments.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void claim(Long applicationId, ReimExpenseItem item, List<ReimAttachment> rows) {
|
||||||
|
for (ReimAttachment row : rows) {
|
||||||
|
row.setApplicationId(applicationId);
|
||||||
|
row.setExpenseItemId(item.getId());
|
||||||
|
attachments.save(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteOmitted(Collection<ReimAttachment> previous, Set<Long> retained, Long userId) {
|
||||||
|
for (ReimAttachment row : previous)
|
||||||
|
if (userId.equals(row.getUploaderId()) && !retained.contains(row.getId())) {
|
||||||
|
tombstone(row);
|
||||||
|
attachments.save(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void tombstone(ReimAttachment row) {
|
||||||
|
row.setApplicationId(null);
|
||||||
|
row.setExpenseItemId(null);
|
||||||
|
row.setUploadStatus(DELETED);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AttachmentDto dto(ReimAttachment row) {
|
||||||
|
return AttachmentDto.builder().id(row.getId()).fileName(row.getFileName())
|
||||||
|
.fileType(row.getFileType()).contentType(row.getContentType()).fileSize(row.getFileSize())
|
||||||
|
.expenseItemId(row.getExpenseItemId()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String safeName(String value) {
|
||||||
|
if (!StringUtils.hasText(value)) throw new BusinessException("附件文件名不能为空", 400);
|
||||||
|
String name = value.trim();
|
||||||
|
if (name.length() > 500 || name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) throw new BusinessException("附件文件名无效", 400);
|
||||||
|
for (int i=0;i<name.length();i++) if (Character.isISOControl(name.charAt(i))) throw new BusinessException("附件文件名无效", 400);
|
||||||
|
if (".".equals(name) || "..".equals(name)) throw new BusinessException("附件文件名无效", 400);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String allowedContentType(String name, String value) {
|
||||||
|
int dot = name.lastIndexOf('.');
|
||||||
|
String extension = dot < 0 ? "" : name.substring(dot + 1).toLowerCase(Locale.ROOT);
|
||||||
|
Map<String,Set<String>> policy = new HashMap<>();
|
||||||
|
policy.put("pdf", Collections.singleton("application/pdf"));
|
||||||
|
policy.put("png", Collections.singleton("image/png"));
|
||||||
|
policy.put("jpg", Collections.singleton("image/jpeg"));
|
||||||
|
policy.put("jpeg", Collections.singleton("image/jpeg"));
|
||||||
|
policy.put("doc", Collections.singleton("application/msword"));
|
||||||
|
policy.put("docx", Collections.singleton("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
|
||||||
|
policy.put("xls", Collections.singleton("application/vnd.ms-excel"));
|
||||||
|
policy.put("xlsx", Collections.singleton("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
|
||||||
|
if (!policy.containsKey(extension)) throw new BusinessException("附件类型仅支持 PDF、图片、Word 和 Excel", 400);
|
||||||
|
String type = StringUtils.hasText(value) ? value.trim().toLowerCase(Locale.ROOT) : "application/octet-stream";
|
||||||
|
if (type.length() > 100 || (!"application/octet-stream".equals(type) && !policy.get(extension).contains(type)))
|
||||||
|
throw new BusinessException("附件扩展名与 MIME 类型不匹配", 400);
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,843 @@
|
|||||||
|
package com.finance.system.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.finance.system.adapter.feishu.FeishuApprovalService;
|
||||||
|
import com.finance.system.adapter.feishu.ReimbursementCanonicalizer;
|
||||||
|
import com.finance.system.dto.*;
|
||||||
|
import com.finance.system.entity.*;
|
||||||
|
import com.finance.system.exception.BusinessException;
|
||||||
|
import com.finance.system.repository.FeishuApprovalDefinitionSnapshotRepository;
|
||||||
|
import com.finance.system.repository.*;
|
||||||
|
import com.finance.system.util.Sha256;
|
||||||
|
import lombok.*;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Reads normalized snapshots and validates the deliberately small dynamic-value model. */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ReimbursementFormService {
|
||||||
|
private static final int MAX_VALUES_BYTES = 100000;
|
||||||
|
private static final int MAX_SCHEMA_BYTES = 1000000;
|
||||||
|
private static final int MAX_CONTROLS = 200, MAX_DEPTH = 5, MAX_OPTIONS = 500;
|
||||||
|
private final FeishuApprovalDefinitionSnapshotRepository snapshots;
|
||||||
|
private final FeishuApprovalService feishu;
|
||||||
|
private final ObjectMapper json;
|
||||||
|
private final SysUserRepository users;
|
||||||
|
private final SysDepartmentRepository departments;
|
||||||
|
private final SysExpenseTypeRepository expenseTypes;
|
||||||
|
private final ReimExpenseItemRepository expenseItems;
|
||||||
|
private final ReimAttachmentRepository attachments;
|
||||||
|
private final ApplicantDepartmentDirectoryRepository applicantDepartments;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Must run in a read-only transaction so {@code form_schema} LOB is materialized
|
||||||
|
* before the persistence context closes (open-in-view is disabled).
|
||||||
|
*/
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public ReimbursementFormDefinition currentDefinition() {
|
||||||
|
if (!feishu.isApprovalEnabledAndConfigured()) return ReimbursementFormDefinition.builder()
|
||||||
|
.mode("LOCAL").fields(Collections.emptyList()).build();
|
||||||
|
FeishuApprovalDefinitionSnapshot snapshot = currentSnapshot(false);
|
||||||
|
// Touch LOB inside the transaction before returning.
|
||||||
|
String schema = snapshot.getFormSchema();
|
||||||
|
return ReimbursementFormDefinition.builder().mode("FEISHU").approvalCode(snapshot.getApprovalCode())
|
||||||
|
.definitionFingerprint(snapshot.getFingerprint()).formFingerprint(snapshot.getFormFingerprint())
|
||||||
|
.fetchedAt(snapshot.getFetchedAt()).fields(parseSchema(schema)).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public PinnedForm validateForWrite(String submittedFingerprint, Map<String, Object> submittedValues) {
|
||||||
|
if (!feishu.isApprovalEnabledAndConfigured()) {
|
||||||
|
if (StringUtils.hasText(submittedFingerprint) || (submittedValues != null && !submittedValues.isEmpty()))
|
||||||
|
throw new BusinessException("本地审批模式不接受飞书动态表单字段", 400);
|
||||||
|
return new PinnedForm(null, "[]", "{}");
|
||||||
|
}
|
||||||
|
FeishuApprovalDefinitionSnapshot snapshot = currentSnapshot(false);
|
||||||
|
if (!StringUtils.hasText(submittedFingerprint) || !submittedFingerprint.equals(snapshot.getFormFingerprint()))
|
||||||
|
throw new BusinessException("飞书审批表单已更新,请刷新页面后重新填写", 409);
|
||||||
|
List<ReimbursementFormField> fields = parseSchema(snapshot.getFormSchema());
|
||||||
|
rejectOversizedOrNestedRequest(submittedValues);
|
||||||
|
Map<String, Object> canonical = canonicalize(fields, submittedValues);
|
||||||
|
try {
|
||||||
|
String values = json.writeValueAsString(canonical);
|
||||||
|
if (values.getBytes(StandardCharsets.UTF_8).length > MAX_VALUES_BYTES)
|
||||||
|
throw new BusinessException("动态表单值过大", 400);
|
||||||
|
return new PinnedForm(snapshot.getFormFingerprint(), snapshot.getFormSchema(), values);
|
||||||
|
} catch (BusinessException e) { throw e; }
|
||||||
|
catch (Exception e) { throw new BusinessException("动态表单值无法保存", 400); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validates upload staging against the currently synchronized attachment child. */
|
||||||
|
public ReimbursementFormField requireCurrentAttachmentControl(String fingerprint, String controlId) {
|
||||||
|
ReimbursementFormField field = requireCurrentAttachmentControl(fingerprint);
|
||||||
|
if (!Objects.equals(controlId, field.getId()))
|
||||||
|
throw new BusinessException("附件控件不是当前费用明细附件字段", 409);
|
||||||
|
return field;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ReimbursementFormField requireCurrentAttachmentControl(String fingerprint) {
|
||||||
|
FeishuApprovalDefinitionSnapshot snapshot = currentSnapshot(false);
|
||||||
|
if (!StringUtils.hasText(fingerprint) || !fingerprint.equals(snapshot.getFormFingerprint()))
|
||||||
|
throw new BusinessException("飞书审批表单已更新,请刷新页面后重新上传附件", 409);
|
||||||
|
List<ReimbursementFormField> matches = new ArrayList<>();
|
||||||
|
for (ReimbursementFormField field : parseSchema(snapshot.getFormSchema())) {
|
||||||
|
if (!"EXPENSE_ITEMS".equals(field.getBinding())) continue;
|
||||||
|
for (ReimbursementFormField child : field.getChildren())
|
||||||
|
if ("EXPENSE_ATTACHMENT".equals(child.getBinding()))
|
||||||
|
matches.add(child);
|
||||||
|
}
|
||||||
|
if (matches.size() != 1) throw new BusinessException("附件控件不是当前费用明细附件字段", 409);
|
||||||
|
return matches.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private FeishuApprovalDefinitionSnapshot currentSnapshot(boolean lock) {
|
||||||
|
FeishuApprovalDefinitionSnapshot snapshot = (lock
|
||||||
|
? snapshots.findByIdForRouteValidation(FeishuApprovalDefinitionSnapshot.CURRENT_ID)
|
||||||
|
: snapshots.findById(FeishuApprovalDefinitionSnapshot.CURRENT_ID))
|
||||||
|
.orElseThrow(() -> new BusinessException("飞书审批表单尚未同步,请先在配置管理中验证并同步飞书审批", 409));
|
||||||
|
String configured = feishu.getConfiguredApprovalCode();
|
||||||
|
String snapshotCode = snapshot.getApprovalCode() == null ? "" : snapshot.getApprovalCode().trim();
|
||||||
|
String configuredCode = configured == null ? "" : configured.trim();
|
||||||
|
if (!StringUtils.hasText(snapshot.getFormFingerprint()) || !StringUtils.hasText(snapshot.getFormSchema()))
|
||||||
|
throw new BusinessException("飞书审批表单快照不完整,请重新同步", 409);
|
||||||
|
if (!StringUtils.hasText(configuredCode) || !configuredCode.equals(snapshotCode))
|
||||||
|
throw new BusinessException("当前飞书审批编码与已同步表单不一致,请保存审批编码后重新同步", 409);
|
||||||
|
if (!snapshot.getFormFingerprint().equals(Sha256.hex(snapshot.getFormSchema())))
|
||||||
|
throw new BusinessException("当前飞书表单快照校验失败,请重新同步", 409);
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ReimbursementFormField> parseSchema(String schema) {
|
||||||
|
if (!StringUtils.hasText(schema) || schema.getBytes(StandardCharsets.UTF_8).length > MAX_SCHEMA_BYTES)
|
||||||
|
throw new BusinessException("飞书表单快照缺失、过大或无效", 409);
|
||||||
|
try {
|
||||||
|
List<ReimbursementFormField> fields = json.readValue(schema,
|
||||||
|
new TypeReference<List<ReimbursementFormField>>() { });
|
||||||
|
validateSchema(fields);
|
||||||
|
return fields;
|
||||||
|
} catch (BusinessException e) { throw e; }
|
||||||
|
catch (Exception e) { throw new BusinessException("飞书表单快照缺失或无效", 409); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> parseValues(String values) {
|
||||||
|
if (!StringUtils.hasText(values)) return Collections.emptyMap();
|
||||||
|
if (values.getBytes(StandardCharsets.UTF_8).length > MAX_VALUES_BYTES)
|
||||||
|
throw new BusinessException("已保存的飞书表单值过大", 409);
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = json.readValue(values, new TypeReference<LinkedHashMap<String,Object>>() { });
|
||||||
|
if (result == null) return Collections.emptyMap();
|
||||||
|
rejectNestedValues(result);
|
||||||
|
return result;
|
||||||
|
} catch (BusinessException e) { throw e; }
|
||||||
|
catch (Exception e) { throw new BusinessException("已保存的飞书表单值无效", 409); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Must run while the application is stable/locked before preview or payload construction. */
|
||||||
|
public void assertApplicationMatchesCurrentForm(ReimApplication app) {
|
||||||
|
assertApplicationMatchesCurrentForm(app, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void assertApplicationMatchesCurrentFormLocked(ReimApplication app) {
|
||||||
|
assertApplicationMatchesCurrentForm(app, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertApplicationMatchesCurrentForm(ReimApplication app, boolean lockSnapshot) {
|
||||||
|
if (!feishu.isApprovalEnabledAndConfigured()) return;
|
||||||
|
FeishuApprovalDefinitionSnapshot current = currentSnapshot(lockSnapshot);
|
||||||
|
if (app == null || !StringUtils.hasText(app.getFeishuFormFingerprint())
|
||||||
|
|| !Objects.equals(app.getFeishuFormFingerprint(), current.getFormFingerprint())
|
||||||
|
|| !StringUtils.hasText(app.getFeishuFormSchema())
|
||||||
|
|| !Objects.equals(Sha256.hex(app.getFeishuFormSchema()), app.getFeishuFormFingerprint()))
|
||||||
|
throw new BusinessException("申请使用的飞书表单已失效,请刷新并重新保存申请", 409);
|
||||||
|
List<ReimbursementFormField> fields;
|
||||||
|
Map<String,Object> stored;
|
||||||
|
Map<String,Object> canonical;
|
||||||
|
try {
|
||||||
|
fields = parseSchema(app.getFeishuFormSchema());
|
||||||
|
stored = parseValues(app.getFeishuFormValues());
|
||||||
|
canonical = canonicalize(fields, stored);
|
||||||
|
} catch (BusinessException e) {
|
||||||
|
throw new BusinessException("申请保存的飞书表单值无效,请重新保存: " + e.getMessage(), 409);
|
||||||
|
}
|
||||||
|
if (!canonical.equals(stored)) throw new BusinessException("申请保存的飞书表单值无效,请重新保存", 409);
|
||||||
|
parseDisplayValues(app.getFeishuFormDisplayValues(), fields);
|
||||||
|
validateRequiredBoundValues(fields, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> canonicalize(List<ReimbursementFormField> fields, Map<String, Object> supplied) {
|
||||||
|
Map<String, Object> input = supplied == null ? Collections.emptyMap() : supplied;
|
||||||
|
if (input.size() > 200) throw new BusinessException("动态表单字段过多", 400);
|
||||||
|
Map<String, ReimbursementFormField> custom = new LinkedHashMap<>();
|
||||||
|
Set<String> bound = new HashSet<>(); collect(fields, custom, bound, false);
|
||||||
|
for (String key : input.keySet()) {
|
||||||
|
if (key.startsWith("__currency__")) {
|
||||||
|
if (!currencyField(fields, key.substring("__currency__".length())).isPresent())
|
||||||
|
throw new BusinessException("未知的动态表单字段: " + key, 400);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (bound.contains(key)) throw new BusinessException("绑定字段不能通过 formValues 提交: " + key, 400);
|
||||||
|
if (!custom.containsKey(key)) throw new BusinessException("未知的动态表单字段: " + key, 400);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
for (String key : input.keySet()) {
|
||||||
|
if (!key.startsWith("__currency__")) continue;
|
||||||
|
ReimbursementFormField amountField = currencyField(fields, key.substring("__currency__".length()))
|
||||||
|
.orElseThrow(() -> new BusinessException("未知的动态表单字段: " + key, 400));
|
||||||
|
Object value = input.get(key);
|
||||||
|
result.put(key, canonicalCurrency(amountField, value));
|
||||||
|
}
|
||||||
|
for (Map.Entry<String, ReimbursementFormField> entry : custom.entrySet()) {
|
||||||
|
ReimbursementFormField field = entry.getValue(); Object value = input.get(entry.getKey());
|
||||||
|
if (field.isReadOnly() || "DISPLAY".equals(field.getType())) {
|
||||||
|
if (input.containsKey(entry.getKey())) throw new BusinessException("只读字段不能提交: " + entry.getKey(), 400);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isEmpty(value)) {
|
||||||
|
if (field.isRequired()) throw new BusinessException("必填字段不能为空: " + field.getLabel(), 400);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.put(entry.getKey(), canonicalValue(field, value));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collect(List<ReimbursementFormField> fields, Map<String, ReimbursementFormField> custom,
|
||||||
|
Set<String> bound, boolean expenseChildren) {
|
||||||
|
if (fields == null) return;
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if (StringUtils.hasText(field.getValueKey())) {
|
||||||
|
if ("DEPARTMENT".equals(field.getType()) && !expenseChildren) custom.put(field.getValueKey(), field);
|
||||||
|
else if ("CUSTOM".equals(field.getBinding()) && !expenseChildren) custom.put(field.getValueKey(), field);
|
||||||
|
else bound.add(field.getValueKey());
|
||||||
|
}
|
||||||
|
if (!field.isReadOnly() || "EXPENSE_ITEMS".equals(field.getType()))
|
||||||
|
collect(field.getChildren(), custom, bound, expenseChildren || "EXPENSE_ITEMS".equals(field.getType()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object canonicalValue(ReimbursementFormField field, Object value) {
|
||||||
|
String type = field.getType();
|
||||||
|
if ("TEXT".equals(type) || "TEXTAREA".equals(type)) {
|
||||||
|
if (!(value instanceof String)) throw invalid(field);
|
||||||
|
String text = (String) value;
|
||||||
|
int max = field.getMaxLength() == null ? 5000 : Math.min(field.getMaxLength(), 20000);
|
||||||
|
if (text.length() > max) throw new BusinessException("字段内容过长: " + field.getLabel(), 400);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
if ("DEPARTMENT".equals(type)) {
|
||||||
|
if (!(value instanceof String) || !StringUtils.hasText((String) value) || ((String) value).length() > 64
|
||||||
|
|| !value.equals(((String) value).trim())) throw invalid(field);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if ("DECIMAL".equals(type)) {
|
||||||
|
if (!(value instanceof String) && !(value instanceof Number)) throw invalid(field);
|
||||||
|
try {
|
||||||
|
BigDecimal decimal = new BigDecimal(String.valueOf(value));
|
||||||
|
if (decimal.precision() > 38 || decimal.scale() > 18) throw invalid(field);
|
||||||
|
return decimal.stripTrailingZeros().toPlainString();
|
||||||
|
} catch (NumberFormatException e) { throw invalid(field); }
|
||||||
|
}
|
||||||
|
if ("DATE".equals(type)) {
|
||||||
|
if (!(value instanceof String)) throw invalid(field);
|
||||||
|
try { return LocalDate.parse((String)value).toString(); }
|
||||||
|
catch (Exception e) { throw new BusinessException("日期必须为 ISO yyyy-MM-dd: " + field.getLabel(), 400); }
|
||||||
|
}
|
||||||
|
Set<String> allowed = optionValues(field);
|
||||||
|
if ("SINGLE_SELECT".equals(type)) {
|
||||||
|
if (!(value instanceof String) || !allowed.contains(value)) throw invalid(field);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if ("MULTI_SELECT".equals(type)) {
|
||||||
|
if (!(value instanceof Collection)) throw invalid(field);
|
||||||
|
Collection<?> values = (Collection<?>) value;
|
||||||
|
if (values.size() > 500) throw invalid(field);
|
||||||
|
List<String> result = new ArrayList<>(); Set<String> unique = new HashSet<>();
|
||||||
|
for (Object item : values) {
|
||||||
|
if (!(item instanceof String) || !allowed.contains(item) || !unique.add((String)item)) throw invalid(field);
|
||||||
|
result.add((String)item);
|
||||||
|
}
|
||||||
|
if (field.isRequired() && result.isEmpty()) throw invalid(field);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
throw new BusinessException("不支持提交字段: " + field.getLabel(), 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> optionValues(ReimbursementFormField field) {
|
||||||
|
Set<String> values = new HashSet<>();
|
||||||
|
if (field.getOptions() != null) for (ReimbursementFormField.Option option : field.getOptions()) values.add(option.getValue());
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
private void rejectOversizedOrNestedRequest(Map<String,Object> values) {
|
||||||
|
if (values == null) return;
|
||||||
|
try {
|
||||||
|
if (json.writeValueAsBytes(values).length > MAX_SCHEMA_BYTES)
|
||||||
|
throw new BusinessException("动态表单请求超过 1MB", 400);
|
||||||
|
} catch (BusinessException e) { throw e; }
|
||||||
|
catch (Exception e) { throw new BusinessException("动态表单请求格式无效", 400); }
|
||||||
|
rejectNestedValues(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void rejectNestedValues(Map<String,Object> values) {
|
||||||
|
if (values.size() > MAX_CONTROLS) throw new BusinessException("动态表单字段过多", 400);
|
||||||
|
for (Map.Entry<String,Object> entry : values.entrySet()) {
|
||||||
|
if (!StringUtils.hasText(entry.getKey()) || entry.getKey().length() > 300)
|
||||||
|
throw new BusinessException("动态表单字段键无效", 400);
|
||||||
|
Object value = entry.getValue();
|
||||||
|
if (value instanceof Map || (value != null && value.getClass().isArray()))
|
||||||
|
throw new BusinessException("动态表单不接受嵌套对象或数组", 400);
|
||||||
|
if (value instanceof Collection) {
|
||||||
|
Collection<?> list = (Collection<?>) value;
|
||||||
|
if (list.size() > MAX_OPTIONS) throw new BusinessException("动态表单数组过大", 400);
|
||||||
|
for (Object item : list) if (!(item instanceof String))
|
||||||
|
throw new BusinessException("动态表单数组只能包含字符串选项", 400);
|
||||||
|
} else if (value != null && !(value instanceof String) && !(value instanceof Number)
|
||||||
|
&& !(value instanceof Boolean)) {
|
||||||
|
throw new BusinessException("动态表单字段值类型无效", 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateSchema(List<ReimbursementFormField> fields) {
|
||||||
|
if (fields == null || fields.isEmpty()) throw new BusinessException("飞书表单快照没有可用控件", 409);
|
||||||
|
SchemaCounter counter = new SchemaCounter(); Set<String> ids = new HashSet<>(); Set<String> keys = new HashSet<>();
|
||||||
|
validateSchemaLevel(fields, 1, false, counter, ids, keys);
|
||||||
|
if (!hasUsableField(fields)) throw new BusinessException("飞书表单快照没有可用控件", 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateSchemaLevel(List<ReimbursementFormField> fields, int depth, boolean expenseChild,
|
||||||
|
SchemaCounter counter,
|
||||||
|
Set<String> ids, Set<String> keys) {
|
||||||
|
if (depth > MAX_DEPTH) throw new BusinessException("飞书表单快照层级无效", 409);
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if (field == null || ++counter.controls > MAX_CONTROLS || !StringUtils.hasText(field.getId())
|
||||||
|
|| field.getId().length() > 300 || !StringUtils.hasText(field.getProviderType())
|
||||||
|
|| field.getProviderType().length() > 80 || !ids.add(field.getId())
|
||||||
|
|| !StringUtils.hasText(field.getValueKey()) || field.getValueKey().length() > 300
|
||||||
|
|| !keys.add(field.getValueKey()))
|
||||||
|
throw new BusinessException("飞书表单快照控件标识无效或重复", 409);
|
||||||
|
if (!Arrays.asList("TEXT","TEXTAREA","DISPLAY","DECIMAL","DATE","SINGLE_SELECT","MULTI_SELECT","EXPENSE_ITEMS","CONTACT","DEPARTMENT","ATTACHMENT","FORMULA").contains(field.getType()))
|
||||||
|
throw new BusinessException("飞书表单快照控件类型无效", 409);
|
||||||
|
if (!Arrays.asList("CUSTOM","APPLICATION_NO","TITLE","APPLICANT_NAME","DEPARTMENT","EXPENSE_TYPE",
|
||||||
|
"TOTAL_AMOUNT","DESCRIPTION","SOURCE_DOC_NO","EXPENSE_ITEMS","EXPENSE_DATE","REIMBURSEMENT_DATE",
|
||||||
|
"EXPENSE_CATEGORY","EXPENSE_DESCRIPTION","EXPENSE_AMOUNT","EXPENSE_ATTACHMENT","APPLICANT_CONTACT","APPLICANT_DEPARTMENT").contains(field.getBinding()))
|
||||||
|
throw new BusinessException("飞书表单快照绑定无效", 409);
|
||||||
|
boolean contactType = "CONTACT".equals(field.getType());
|
||||||
|
boolean contactBinding = "APPLICANT_CONTACT".equals(field.getBinding());
|
||||||
|
if (contactType != contactBinding || (contactType && (!field.isReadOnly()
|
||||||
|
|| !"contact".equals(normalizedProviderType(field)) || expenseChild || depth != 1)))
|
||||||
|
throw new BusinessException("报销人联系人控件类型、绑定或只读约束无效", 409);
|
||||||
|
if ("contact".equals(normalizedProviderType(field)) && !contactType
|
||||||
|
&& !("DISPLAY".equals(field.getType()) && "CUSTOM".equals(field.getBinding()) && field.isReadOnly()))
|
||||||
|
throw new BusinessException("飞书联系人控件绑定无效", 409);
|
||||||
|
boolean departmentType = "DEPARTMENT".equals(field.getType());
|
||||||
|
boolean departmentBinding = "APPLICANT_DEPARTMENT".equals(field.getBinding());
|
||||||
|
// Applicant department is an editable picker (readOnly=false) after sync; do not require read-only.
|
||||||
|
if (departmentType != departmentBinding || (departmentType
|
||||||
|
&& (!"department".equals(normalizedProviderType(field)) || expenseChild || depth != 1)))
|
||||||
|
throw new BusinessException("报销人所属部门控件类型、绑定约束无效", 409);
|
||||||
|
if ("department".equals(normalizedProviderType(field)) && !departmentType
|
||||||
|
&& !("DISPLAY".equals(field.getType()) && "CUSTOM".equals(field.getBinding()) && field.isReadOnly()))
|
||||||
|
throw new BusinessException("飞书部门控件绑定无效", 409);
|
||||||
|
boolean expenseBinding = Arrays.asList("EXPENSE_DATE","EXPENSE_CATEGORY",
|
||||||
|
"EXPENSE_DESCRIPTION","EXPENSE_AMOUNT","EXPENSE_ATTACHMENT").contains(field.getBinding());
|
||||||
|
if ("EXPENSE_ITEMS".equals(field.getType()) != "EXPENSE_ITEMS".equals(field.getBinding()))
|
||||||
|
throw new BusinessException("费用明细控件绑定与类型不匹配", 409);
|
||||||
|
if ((!expenseChild && expenseBinding)
|
||||||
|
|| (expenseChild && !expenseBinding
|
||||||
|
&& !("CUSTOM".equals(field.getBinding()) && field.isReadOnly()
|
||||||
|
&& "DISPLAY".equals(field.getType()))))
|
||||||
|
throw new BusinessException("飞书费用明细子控件绑定无效", 409);
|
||||||
|
if ((field.getCustomId() != null && field.getCustomId().length() > 200)
|
||||||
|
|| (field.getLabel() != null && field.getLabel().length() > 500))
|
||||||
|
throw new BusinessException("飞书表单快照字段元数据过长", 409);
|
||||||
|
if ("EXPENSE_AMOUNT".equals(field.getBinding()) && !"amount".equals(normalizedProviderType(field)))
|
||||||
|
throw new BusinessException("飞书费用金额控件类型无效", 409);
|
||||||
|
if ("amount".equals(normalizedProviderType(field)) && !"CNY".equals(field.getCurrency()))
|
||||||
|
throw new BusinessException("飞书费用金额控件币种约束无效", 409);
|
||||||
|
if ("EXPENSE_ATTACHMENT".equals(field.getBinding())
|
||||||
|
&& (!"ATTACHMENT".equals(field.getType()) || !"attachmentv2".equals(normalizedProviderType(field))))
|
||||||
|
throw new BusinessException("飞书费用附件控件约束无效", 409);
|
||||||
|
if ("TOTAL_AMOUNT".equals(field.getBinding()) && "formula".equals(normalizedProviderType(field))
|
||||||
|
&& !"FORMULA".equals(field.getType()))
|
||||||
|
throw new BusinessException("飞书总金额公式控件约束无效", 409);
|
||||||
|
Set<String> optionValues = new HashSet<>();
|
||||||
|
if (field.getOptions() != null) for (ReimbursementFormField.Option option : field.getOptions()) {
|
||||||
|
if (++counter.options > MAX_OPTIONS || option == null || !StringUtils.hasText(option.getValue())
|
||||||
|
|| option.getValue().length() > 500 || !optionValues.add(option.getValue()))
|
||||||
|
throw new BusinessException("飞书表单快照选项无效或重复", 409);
|
||||||
|
}
|
||||||
|
if (("SINGLE_SELECT".equals(field.getType()) || "MULTI_SELECT".equals(field.getType()))
|
||||||
|
&& optionValues.isEmpty())
|
||||||
|
throw new BusinessException("飞书表单快照选择控件没有选项", 409);
|
||||||
|
if (!("SINGLE_SELECT".equals(field.getType()) || "MULTI_SELECT".equals(field.getType()))
|
||||||
|
&& !optionValues.isEmpty()) {
|
||||||
|
// Feishu amount widgets persist allowed currencies in options (not a select control).
|
||||||
|
boolean amountCurrencyOptions = "DECIMAL".equals(field.getType())
|
||||||
|
&& "amount".equals(normalizedProviderType(field))
|
||||||
|
&& StringUtils.hasText(field.getCurrency());
|
||||||
|
if (!amountCurrencyOptions)
|
||||||
|
throw new BusinessException("非选择控件不能包含选项快照", 409);
|
||||||
|
}
|
||||||
|
if (field.getChildren() != null && !field.getChildren().isEmpty())
|
||||||
|
if (contactType || departmentType) throw new BusinessException("报销人身份控件不能包含子控件", 409);
|
||||||
|
if (field.getChildren() != null && !field.getChildren().isEmpty())
|
||||||
|
validateSchemaLevel(field.getChildren(), depth + 1,
|
||||||
|
expenseChild || "EXPENSE_ITEMS".equals(field.getType()), counter, ids, keys);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasUsableField(List<ReimbursementFormField> fields) {
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if ("CONTACT".equals(field.getType()) || "DEPARTMENT".equals(field.getType())
|
||||||
|
|| (!field.isReadOnly() && !"DISPLAY".equals(field.getType()))) return true;
|
||||||
|
if (field.getChildren() != null && hasUsableField(field.getChildren())) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateRequiredBoundValues(List<ReimbursementFormField> fields, ReimApplication app) {
|
||||||
|
SysUser user = app.getApplicantId() == null ? null : users.findById(app.getApplicantId()).orElse(null);
|
||||||
|
SysDepartment department = app.getDepartmentId() == null ? null : departments.findById(app.getDepartmentId()).orElse(null);
|
||||||
|
SysExpenseType expenseType = app.getExpenseTypeId() == null ? null : expenseTypes.findById(app.getExpenseTypeId()).orElse(null);
|
||||||
|
List<ReimExpenseItem> items = expenseItems.findByApplicationId(app.getId());
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if (field.isReadOnly()) continue;
|
||||||
|
// Editable applicant department is stored in formValues, not as a system-bound snapshot.
|
||||||
|
if ("APPLICANT_DEPARTMENT".equals(field.getBinding()) || "DEPARTMENT".equals(field.getType())) continue;
|
||||||
|
if (field.isRequired() && !"CUSTOM".equals(field.getBinding())) {
|
||||||
|
Object value = boundValue(field.getBinding(), app, user, department, expenseType, items);
|
||||||
|
if (isEmpty(value)) throw new BusinessException("飞书必填字段缺少系统值: " + field.getLabel(), 409);
|
||||||
|
}
|
||||||
|
if ("EXPENSE_ITEMS".equals(field.getType())) for (ReimExpenseItem item : items)
|
||||||
|
validateRequiredExpenseChildren(field.getChildren(), item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object boundValue(String binding, ReimApplication app, SysUser user, SysDepartment department,
|
||||||
|
SysExpenseType expenseType, List<ReimExpenseItem> items) {
|
||||||
|
if (binding == null) return null;
|
||||||
|
switch (binding) {
|
||||||
|
case "APPLICATION_NO": return app.getApplicationNo(); case "TITLE": return app.getTitle();
|
||||||
|
case "APPLICANT_NAME": return user == null ? null : user.getRealName();
|
||||||
|
case "APPLICANT_CONTACT": return applicantContactSnapshot(user);
|
||||||
|
case "APPLICANT_DEPARTMENT": return applicantDepartmentSnapshot(user);
|
||||||
|
case "DEPARTMENT": return department == null ? null : department.getDeptName();
|
||||||
|
case "EXPENSE_TYPE": return expenseType == null ? null : expenseType.getTypeName();
|
||||||
|
case "TOTAL_AMOUNT": return app.getTotalAmount();
|
||||||
|
case "REIMBURSEMENT_DATE": return app.getCreatedAt() == null ? LocalDate.now() : app.getCreatedAt().toLocalDate();
|
||||||
|
case "DESCRIPTION": return app.getDescription();
|
||||||
|
case "SOURCE_DOC_NO": return app.getSourceDocNo(); case "EXPENSE_ITEMS": return items;
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateRequiredExpenseChildren(List<ReimbursementFormField> children, ReimExpenseItem item) {
|
||||||
|
if (children == null) return;
|
||||||
|
for (ReimbursementFormField child : children) {
|
||||||
|
if (child.isRequired() && !child.isReadOnly() && isEmpty(expenseChildValue(child.getBinding(), item)))
|
||||||
|
throw new BusinessException("费用明细缺少飞书必填字段: " + child.getLabel(), 409);
|
||||||
|
validateRequiredExpenseChildren(child.getChildren(), item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private Object expenseChildValue(String binding, ReimExpenseItem item) {
|
||||||
|
if (binding == null) return null;
|
||||||
|
switch (binding) {
|
||||||
|
case "EXPENSE_DATE": return item.getExpenseDate();
|
||||||
|
case "EXPENSE_CATEGORY": return item.getCategory();
|
||||||
|
case "EXPENSE_DESCRIPTION": return item.getDescription();
|
||||||
|
case "EXPENSE_AMOUNT": return item.getAmount();
|
||||||
|
case "EXPENSE_ATTACHMENT": return attachmentSnapshot(item);
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String,Object>> attachmentSnapshot(ReimExpenseItem item) {
|
||||||
|
if (item == null || item.getId() == null) return Collections.emptyList();
|
||||||
|
List<ReimAttachment> rows = attachments
|
||||||
|
.findByExpenseItemIdAndApplicationIdIsNotNullAndUploadStatusOrderByIdAsc(item.getId(), "UPLOADED");
|
||||||
|
if (rows.size() > 50) throw new BusinessException("单条费用明细附件超过 50 个", 400);
|
||||||
|
List<Map<String,Object>> result = new ArrayList<>();
|
||||||
|
Set<Long> ids = new HashSet<>();
|
||||||
|
for (ReimAttachment attachment : rows) {
|
||||||
|
if (!"UPLOADED".equals(attachment.getUploadStatus()) || attachment.getId() == null
|
||||||
|
|| !ids.add(attachment.getId()) || !StringUtils.hasText(attachment.getFeishuFileCode()))
|
||||||
|
throw new BusinessException("费用明细附件元数据无效", 409);
|
||||||
|
Map<String,Object> value = new LinkedHashMap<>();
|
||||||
|
value.put("attachment_id", attachment.getId());
|
||||||
|
value.put("provider_code", attachment.getFeishuFileCode());
|
||||||
|
value.put("display_name", attachment.getFileName());
|
||||||
|
result.add(Collections.unmodifiableMap(value));
|
||||||
|
}
|
||||||
|
return Collections.unmodifiableList(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Captures immutable labels and bound values for historical FEISHU detail rendering. */
|
||||||
|
public String buildDisplayValues(ReimApplication app) {
|
||||||
|
if (app == null || !StringUtils.hasText(app.getFeishuFormFingerprint())) return "{}";
|
||||||
|
List<ReimbursementFormField> fields = parseSchema(app.getFeishuFormSchema());
|
||||||
|
SysUser user = app.getApplicantId() == null ? null : users.findById(app.getApplicantId()).orElse(null);
|
||||||
|
SysDepartment department = app.getDepartmentId() == null ? null : departments.findById(app.getDepartmentId()).orElse(null);
|
||||||
|
SysExpenseType expenseType = app.getExpenseTypeId() == null ? null : expenseTypes.findById(app.getExpenseTypeId()).orElse(null);
|
||||||
|
List<ReimExpenseItem> items = expenseItems.findByApplicationId(app.getId());
|
||||||
|
if (items.size() > 500) throw new BusinessException("费用明细超过表单快照上限", 400);
|
||||||
|
Map<String,Object> display = new LinkedHashMap<>();
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if ("CUSTOM".equals(field.getBinding())) continue;
|
||||||
|
if ("EXPENSE_ITEMS".equals(field.getBinding())) {
|
||||||
|
List<Map<String,Object>> rows = new ArrayList<>();
|
||||||
|
for (ReimExpenseItem item : ReimbursementCanonicalizer.orderedItems(items)) {
|
||||||
|
Map<String,Object> row = new LinkedHashMap<>();
|
||||||
|
for (ReimbursementFormField child : field.getChildren() == null
|
||||||
|
? Collections.<ReimbursementFormField>emptyList() : field.getChildren()) {
|
||||||
|
if ("CUSTOM".equals(child.getBinding())) continue;
|
||||||
|
row.put(child.getValueKey(), displaySubmissionValue(child,
|
||||||
|
expenseChildValue(child.getBinding(), item)));
|
||||||
|
}
|
||||||
|
rows.add(row);
|
||||||
|
}
|
||||||
|
display.put(field.getValueKey(), rows);
|
||||||
|
} else {
|
||||||
|
Object raw = "DEPARTMENT".equals(field.getType())
|
||||||
|
? selectedDepartmentSnapshot(app, field, user)
|
||||||
|
: boundValue(field.getBinding(), app, user, department, expenseType, items);
|
||||||
|
display.put(field.getValueKey(), displaySubmissionValue(field, raw));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
byte[] encoded = json.writeValueAsBytes(display);
|
||||||
|
if (encoded.length > MAX_SCHEMA_BYTES) throw new BusinessException("表单展示快照超过 1MB", 400);
|
||||||
|
return new String(encoded, StandardCharsets.UTF_8);
|
||||||
|
} catch (BusinessException e) { throw e; }
|
||||||
|
catch (Exception e) { throw new BusinessException("表单展示快照生成失败", 500); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String,Object> mergedSnapshotValues(ReimApplication app, List<ReimbursementFormField> fields) {
|
||||||
|
Map<String,Object> merged = new LinkedHashMap<>(parseValues(app.getFeishuFormValues()));
|
||||||
|
merged.putAll(parseDisplayValues(app.getFeishuFormDisplayValues(), fields));
|
||||||
|
// Detail readers need the immutable display label, not provider identifiers. Keep the
|
||||||
|
// complete contact object solely in feishu_form_display_values for remote payload creation.
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if (!"APPLICANT_CONTACT".equals(field.getBinding())
|
||||||
|
&& !"APPLICANT_DEPARTMENT".equals(field.getBinding())) continue;
|
||||||
|
Object value = merged.get(field.getValueKey());
|
||||||
|
if (!(value instanceof Map)) continue; // The validated display parser reports malformed snapshots.
|
||||||
|
Map<String,Object> safe = new LinkedHashMap<>();
|
||||||
|
safe.put("display_label", ((Map<?,?>)value).get("display_label"));
|
||||||
|
merged.put(field.getValueKey(), safe);
|
||||||
|
}
|
||||||
|
sanitizeAttachmentValues(merged, fields);
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private void sanitizeAttachmentValues(Map<String,Object> merged, List<ReimbursementFormField> fields) {
|
||||||
|
for (ReimbursementFormField parent : fields) {
|
||||||
|
if (!"EXPENSE_ITEMS".equals(parent.getBinding())) continue;
|
||||||
|
Object rows = merged.get(parent.getValueKey());
|
||||||
|
if (!(rows instanceof List)) continue;
|
||||||
|
for (Object rowValue : (List<?>)rows) {
|
||||||
|
if (!(rowValue instanceof Map)) continue;
|
||||||
|
Map<String,Object> row = (Map<String,Object>)rowValue;
|
||||||
|
for (ReimbursementFormField child : parent.getChildren()) {
|
||||||
|
if (!"EXPENSE_ATTACHMENT".equals(child.getBinding())) continue;
|
||||||
|
Object values = row.get(child.getValueKey());
|
||||||
|
if (!(values instanceof List)) continue;
|
||||||
|
List<Map<String,Object>> safeValues = new ArrayList<>();
|
||||||
|
for (Object item : (List<?>)values) {
|
||||||
|
if (!(item instanceof Map)) continue;
|
||||||
|
Map<String,Object> safe = new LinkedHashMap<>();
|
||||||
|
safe.put("id", ((Map<?,?>)item).get("attachment_id"));
|
||||||
|
safe.put("fileName", ((Map<?,?>)item).get("display_name"));
|
||||||
|
safeValues.add(safe);
|
||||||
|
}
|
||||||
|
row.put(child.getValueKey(), safeValues);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String,Object> parseDisplayValues(String source, List<ReimbursementFormField> fields) {
|
||||||
|
if (!StringUtils.hasText(source)) {
|
||||||
|
Map<String,Object> empty = Collections.emptyMap();
|
||||||
|
validateDisplayMap(empty, fields);
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
if (source.getBytes(StandardCharsets.UTF_8).length > MAX_SCHEMA_BYTES)
|
||||||
|
throw new BusinessException("已保存的表单展示快照过大", 409);
|
||||||
|
try {
|
||||||
|
Map<String,Object> value = json.readValue(source, new TypeReference<LinkedHashMap<String,Object>>() { });
|
||||||
|
validateDisplayMap(value, fields);
|
||||||
|
return value;
|
||||||
|
} catch (BusinessException e) { throw e; }
|
||||||
|
catch (Exception e) { throw new BusinessException("已保存的表单展示快照无效", 409); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateDisplayMap(Map<String,Object> value, List<ReimbursementFormField> fields) {
|
||||||
|
if (value == null || value.size() > MAX_CONTROLS) throw new BusinessException("表单展示快照结构无效", 409);
|
||||||
|
Map<String,ReimbursementFormField> allowed = new HashMap<>();
|
||||||
|
for (ReimbursementFormField field : fields) if (!"CUSTOM".equals(field.getBinding())) allowed.put(field.getValueKey(), field);
|
||||||
|
for (Map.Entry<String,Object> entry : value.entrySet()) {
|
||||||
|
ReimbursementFormField field = allowed.get(entry.getKey());
|
||||||
|
if (field == null) throw new BusinessException("表单展示快照包含未知字段", 409);
|
||||||
|
if ("EXPENSE_ITEMS".equals(field.getBinding())) validateDisplayRows(entry.getValue(), field.getChildren());
|
||||||
|
else validateDisplayValue(entry.getValue(), field);
|
||||||
|
}
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if ("APPLICANT_CONTACT".equals(field.getBinding()) && !value.containsKey(field.getValueKey()))
|
||||||
|
throw new BusinessException("申请人未绑定飞书用户身份,无法保存或预览报销人联系人字段", 409);
|
||||||
|
if ("APPLICANT_DEPARTMENT".equals(field.getBinding()) && !value.containsKey(field.getValueKey()))
|
||||||
|
throw new BusinessException("申请人没有当前飞书目录部门绑定,无法保存或预览报销人所属部门字段", 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateDisplayRows(Object value, List<ReimbursementFormField> children) {
|
||||||
|
if (!(value instanceof List) || ((List<?>)value).size() > 500)
|
||||||
|
throw new BusinessException("费用明细展示快照无效", 409);
|
||||||
|
Map<String,ReimbursementFormField> allowed = new HashMap<>();
|
||||||
|
if (children != null) for (ReimbursementFormField child : children)
|
||||||
|
if (!"CUSTOM".equals(child.getBinding())) allowed.put(child.getValueKey(), child);
|
||||||
|
for (Object rowValue : (List<?>)value) {
|
||||||
|
if (!(rowValue instanceof Map) || ((Map<?,?>)rowValue).size() > MAX_CONTROLS)
|
||||||
|
throw new BusinessException("费用明细展示快照无效", 409);
|
||||||
|
for (Map.Entry<?,?> entry : ((Map<?,?>)rowValue).entrySet()) {
|
||||||
|
if (!(entry.getKey() instanceof String) || !allowed.containsKey(entry.getKey()))
|
||||||
|
throw new BusinessException("费用明细展示快照包含未知字段", 409);
|
||||||
|
validateDisplayValue(entry.getValue(), allowed.get(entry.getKey()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateDisplayValue(Object value, ReimbursementFormField field) {
|
||||||
|
if ("CONTACT".equals(field.getType())) {
|
||||||
|
validateApplicantContactSnapshot(value, 409);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("DEPARTMENT".equals(field.getType())) {
|
||||||
|
validateApplicantDepartmentSnapshot(value, 409);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("ATTACHMENT".equals(field.getType())) {
|
||||||
|
validateAttachmentSnapshot(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (value instanceof Collection) {
|
||||||
|
if (!"MULTI_SELECT".equals(field.getType()) || ((Collection<?>)value).size() > MAX_OPTIONS)
|
||||||
|
throw new BusinessException("表单展示快照数组无效", 409);
|
||||||
|
Set<String> allowed = optionValues(field);
|
||||||
|
for (Object item : (Collection<?>)value)
|
||||||
|
if (!(item instanceof String) || !allowed.contains(item))
|
||||||
|
throw new BusinessException("表单展示快照选项无效", 409);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (value != null && !(value instanceof String) && !(value instanceof Number) && !(value instanceof Boolean))
|
||||||
|
throw new BusinessException("表单展示快照值类型无效", 409);
|
||||||
|
if (value instanceof String && ((String)value).length() > 20000)
|
||||||
|
throw new BusinessException("表单展示快照值过长", 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object displaySubmissionValue(ReimbursementFormField field, Object value) {
|
||||||
|
if (value == null) return null;
|
||||||
|
if ("CONTACT".equals(field.getType())) {
|
||||||
|
validateApplicantContactSnapshot(value, 400);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if ("DEPARTMENT".equals(field.getType())) {
|
||||||
|
validateApplicantDepartmentSnapshot(value, 400);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if ("ATTACHMENT".equals(field.getType())) {
|
||||||
|
validateAttachmentSnapshot(value);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
String providerType = field.getProviderType() == null ? "" : field.getProviderType()
|
||||||
|
.replace("_", "").toLowerCase(Locale.ROOT);
|
||||||
|
if ("number".equals(providerType) || "amount".equals(providerType) || "formula".equals(providerType)) {
|
||||||
|
try { return (value instanceof BigDecimal ? (BigDecimal)value : new BigDecimal(String.valueOf(value)))
|
||||||
|
.stripTrailingZeros(); }
|
||||||
|
catch (Exception e) { throw new BusinessException("表单数值快照生成失败: " + field.getLabel(), 400); }
|
||||||
|
}
|
||||||
|
if ("date".equals(providerType)) {
|
||||||
|
try {
|
||||||
|
LocalDate date = value instanceof LocalDate ? (LocalDate)value : LocalDate.parse(String.valueOf(value));
|
||||||
|
return date.atStartOfDay(java.time.ZoneId.of("Asia/Shanghai"))
|
||||||
|
.format(java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME);
|
||||||
|
} catch (Exception e) { throw new BusinessException("表单日期快照生成失败: " + field.getLabel(), 400); }
|
||||||
|
}
|
||||||
|
if ("radio".equals(providerType) || "radiov2".equals(providerType))
|
||||||
|
return displayOptionValue(field, String.valueOf(value));
|
||||||
|
if ("checkbox".equals(providerType) || "checkboxv2".equals(providerType)) {
|
||||||
|
Collection<?> source = value instanceof Collection ? (Collection<?>)value : Collections.singletonList(value);
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
for (Object item : source) result.add(displayOptionValue(field, String.valueOf(item)));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
String text = String.valueOf(value);
|
||||||
|
return text.substring(0, Math.min(text.length(), 20000));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateAttachmentSnapshot(Object value) {
|
||||||
|
if (!(value instanceof List) || ((List<?>)value).size() > 50)
|
||||||
|
throw new BusinessException("费用明细附件展示快照无效", 409);
|
||||||
|
Set<Long> ids = new HashSet<>();
|
||||||
|
for (Object item : (List<?>)value) {
|
||||||
|
if (!(item instanceof Map) || ((Map<?,?>)item).size() != 3)
|
||||||
|
throw new BusinessException("费用明细附件展示快照无效", 409);
|
||||||
|
Map<?,?> map = (Map<?,?>)item;
|
||||||
|
if (!map.keySet().containsAll(Arrays.asList("attachment_id", "provider_code", "display_name")))
|
||||||
|
throw new BusinessException("费用明细附件展示快照无效", 409);
|
||||||
|
Object id = map.get("attachment_id"), code = map.get("provider_code"), name = map.get("display_name");
|
||||||
|
if (!(id instanceof Number) || !ids.add(((Number)id).longValue())
|
||||||
|
|| !(code instanceof String) || !StringUtils.hasText((String)code) || ((String)code).length() > 500
|
||||||
|
|| !(name instanceof String) || !StringUtils.hasText((String)name) || ((String)name).length() > 500)
|
||||||
|
throw new BusinessException("费用明细附件展示快照无效", 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String displayOptionValue(ReimbursementFormField field, String value) {
|
||||||
|
if (field.getOptions() != null) for (ReimbursementFormField.Option option : field.getOptions())
|
||||||
|
if (value.equals(option.getValue()) || value.equals(option.getLabel())) return option.getValue();
|
||||||
|
throw new BusinessException("表单选项快照生成失败: " + field.getLabel(), 400);
|
||||||
|
}
|
||||||
|
private Map<String,Object> applicantContactSnapshot(SysUser user) {
|
||||||
|
if (user == null || (!StringUtils.hasText(user.getFeishuUserId())
|
||||||
|
&& !StringUtils.hasText(user.getFeishuOpenId())))
|
||||||
|
throw new BusinessException("申请人未绑定飞书用户身份,无法保存或预览报销人联系人字段", 400);
|
||||||
|
Map<String,Object> value = new LinkedHashMap<>();
|
||||||
|
if (StringUtils.hasText(user.getFeishuUserId())) value.put("user_id", applicantIdentifier(user.getFeishuUserId()));
|
||||||
|
if (StringUtils.hasText(user.getFeishuOpenId())) value.put("open_id", applicantIdentifier(user.getFeishuOpenId()));
|
||||||
|
String label = StringUtils.hasText(user.getRealName()) ? user.getRealName().trim() : "飞书用户";
|
||||||
|
value.put("display_label", bounded(label, 500));
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
private Optional<ReimbursementFormField> currencyField(List<ReimbursementFormField> fields, String valueKey) {
|
||||||
|
if (!StringUtils.hasText(valueKey) || fields == null) return Optional.empty();
|
||||||
|
for (ReimbursementFormField field : fields) {
|
||||||
|
if (valueKey.equals(field.getValueKey()) && "DECIMAL".equals(field.getType())
|
||||||
|
&& StringUtils.hasText(field.getCurrency())) return Optional.of(field);
|
||||||
|
Optional<ReimbursementFormField> child = currencyField(field.getChildren(), valueKey);
|
||||||
|
if (child.isPresent()) return child;
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object canonicalCurrency(ReimbursementFormField field, Object value) {
|
||||||
|
Set<String> allowed = new LinkedHashSet<>();
|
||||||
|
if (field.getOptions() != null) for (ReimbursementFormField.Option option : field.getOptions()) {
|
||||||
|
if (StringUtils.hasText(option.getValue())) allowed.add(option.getValue());
|
||||||
|
}
|
||||||
|
if (allowed.isEmpty() && StringUtils.hasText(field.getCurrency())) allowed.add(field.getCurrency());
|
||||||
|
if (value instanceof String) {
|
||||||
|
String code = ((String) value).trim().toUpperCase(Locale.ROOT);
|
||||||
|
if (!allowed.contains(code)) throw new BusinessException("币种不在飞书金额控件允许范围内: " + field.getLabel(), 400);
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
if (value instanceof List) {
|
||||||
|
if (((List<?>) value).size() > 500) throw new BusinessException("费用明细币种过多", 400);
|
||||||
|
List<String> codes = new ArrayList<>();
|
||||||
|
for (Object item : (List<?>) value) {
|
||||||
|
if (!(item instanceof String)) throw new BusinessException("币种无效: " + field.getLabel(), 400);
|
||||||
|
String code = ((String) item).trim().toUpperCase(Locale.ROOT);
|
||||||
|
if (!allowed.contains(code)) throw new BusinessException("币种不在飞书金额控件允许范围内: " + field.getLabel(), 400);
|
||||||
|
codes.add(code);
|
||||||
|
}
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
|
throw new BusinessException("币种无效: " + field.getLabel(), 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String,Object> selectedDepartmentSnapshot(ReimApplication app, ReimbursementFormField field, SysUser user) {
|
||||||
|
Object supplied = parseValues(app.getFeishuFormValues()).get(field.getValueKey());
|
||||||
|
if (supplied instanceof String && StringUtils.hasText((String) supplied)) {
|
||||||
|
ApplicantDepartmentDirectoryRepository.DirectoryDepartment department = applicantDepartments
|
||||||
|
.findByOpenDepartmentId(((String) supplied).trim())
|
||||||
|
.orElseThrow(() -> new BusinessException("所选部门不在当前飞书组织架构中: " + field.getLabel(), 400));
|
||||||
|
Map<String,Object> value = new LinkedHashMap<>();
|
||||||
|
value.put("open_department_ids", Collections.singletonList(department.getOpenDepartmentId()));
|
||||||
|
value.put("display_label", department.getDisplayLabel());
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return applicantDepartmentSnapshot(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String,Object> applicantDepartmentSnapshot(SysUser user) {
|
||||||
|
if (user == null || !StringUtils.hasText(user.getFeishuOpenId()))
|
||||||
|
throw new BusinessException("申请人未绑定飞书 open_id,无法解析报销人所属部门", 400);
|
||||||
|
ApplicantDepartmentDirectoryRepository.DirectoryDepartment department = applicantDepartments
|
||||||
|
.findPreferredNonRootByOpenId(user.getFeishuOpenId().trim())
|
||||||
|
.orElseThrow(() -> new BusinessException("申请人没有当前飞书目录的非根部门绑定,无法保存报销人所属部门", 400));
|
||||||
|
String openDepartmentId = department.getOpenDepartmentId();
|
||||||
|
String label = department.getDisplayLabel();
|
||||||
|
if (!StringUtils.hasText(openDepartmentId) || openDepartmentId.length() > 64
|
||||||
|
|| !openDepartmentId.equals(openDepartmentId.trim())
|
||||||
|
|| !StringUtils.hasText(label) || label.length() > 500 || !label.equals(label.trim()))
|
||||||
|
throw new BusinessException("当前飞书目录中的申请人部门数据无效,无法保存报销人所属部门", 400);
|
||||||
|
Map<String,Object> value = new LinkedHashMap<>();
|
||||||
|
value.put("open_department_ids", Collections.singletonList(openDepartmentId));
|
||||||
|
value.put("display_label", label);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
private void validateApplicantContactSnapshot(Object value, int status) {
|
||||||
|
if (!(value instanceof Map) || ((Map<?,?>) value).size() > 3)
|
||||||
|
throw new BusinessException("报销人联系人展示快照结构无效", status);
|
||||||
|
Map<?,?> contact = (Map<?,?>) value;
|
||||||
|
for (Object key : contact.keySet()) if (!(key instanceof String)
|
||||||
|
|| !Arrays.asList("user_id", "open_id", "display_label").contains(key))
|
||||||
|
throw new BusinessException("报销人联系人展示快照结构无效", status);
|
||||||
|
String userId = boundedSnapshotText(contact.get("user_id"), 100, false, status);
|
||||||
|
String openId = boundedSnapshotText(contact.get("open_id"), 100, false, status);
|
||||||
|
boundedSnapshotText(contact.get("display_label"), 500, true, status);
|
||||||
|
if (!StringUtils.hasText(userId) && !StringUtils.hasText(openId))
|
||||||
|
throw new BusinessException("申请人未绑定飞书用户身份,无法保存或预览报销人联系人字段", status);
|
||||||
|
}
|
||||||
|
private void validateApplicantDepartmentSnapshot(Object value, int status) {
|
||||||
|
if (!(value instanceof Map) || ((Map<?,?>)value).size() != 2)
|
||||||
|
throw new BusinessException("报销人所属部门展示快照结构无效", status);
|
||||||
|
Map<?,?> department = (Map<?,?>)value;
|
||||||
|
for (Object key : department.keySet()) if (!(key instanceof String)
|
||||||
|
|| !Arrays.asList("open_department_ids", "display_label").contains(key))
|
||||||
|
throw new BusinessException("报销人所属部门展示快照结构无效", status);
|
||||||
|
Object idsValue = department.get("open_department_ids");
|
||||||
|
if (!(idsValue instanceof List) || ((List<?>)idsValue).isEmpty() || ((List<?>)idsValue).size() > 10)
|
||||||
|
throw new BusinessException("报销人所属部门展示快照标识无效", status);
|
||||||
|
Set<String> 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 new BusinessException("报销人所属部门展示快照标识无效", status);
|
||||||
|
}
|
||||||
|
Object label = department.get("display_label");
|
||||||
|
if (!(label instanceof String) || !StringUtils.hasText((String)label)
|
||||||
|
|| ((String)label).length() > 500 || !label.equals(((String)label).trim()))
|
||||||
|
throw new BusinessException("报销人所属部门展示快照名称无效", status);
|
||||||
|
}
|
||||||
|
private String boundedSnapshotText(Object value, int max, boolean required, int status) {
|
||||||
|
if (value == null && !required) return null;
|
||||||
|
if (!(value instanceof String) || !StringUtils.hasText((String)value)
|
||||||
|
|| ((String)value).length() > max || !((String)value).equals(((String)value).trim()))
|
||||||
|
throw new BusinessException("报销人联系人展示快照值无效", status);
|
||||||
|
return (String)value;
|
||||||
|
}
|
||||||
|
private String applicantIdentifier(String value) {
|
||||||
|
String identifier = value.trim();
|
||||||
|
if (identifier.length() > 100)
|
||||||
|
throw new BusinessException("申请人的飞书用户标识过长,无法保存报销人联系人字段", 400);
|
||||||
|
return identifier;
|
||||||
|
}
|
||||||
|
private String normalizedProviderType(ReimbursementFormField field) {
|
||||||
|
return field.getProviderType() == null ? "" : field.getProviderType().replace("_", "").toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
private String bounded(String value, int max) { return value.substring(0, Math.min(value.length(), max)); }
|
||||||
|
private static class SchemaCounter { int controls; int options; }
|
||||||
|
private boolean isEmpty(Object value) { return value == null || (value instanceof String && !StringUtils.hasText((String)value)) || (value instanceof Collection && ((Collection<?>)value).isEmpty()); }
|
||||||
|
private BusinessException invalid(ReimbursementFormField field) { return new BusinessException("字段值格式无效: " + field.getLabel(), 400); }
|
||||||
|
|
||||||
|
@Value
|
||||||
|
public static class PinnedForm { String fingerprint; String schema; String values; }
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import com.finance.system.exception.ResourceNotFoundException;
|
|||||||
import com.finance.system.repository.*;
|
import com.finance.system.repository.*;
|
||||||
import com.finance.system.service.ReimApplicationService;
|
import com.finance.system.service.ReimApplicationService;
|
||||||
import com.finance.system.service.RoleService;
|
import com.finance.system.service.RoleService;
|
||||||
|
import com.finance.system.service.ReimbursementFormService;
|
||||||
import com.finance.system.util.AuditUtil;
|
import com.finance.system.util.AuditUtil;
|
||||||
import com.finance.system.adapter.kingdee.KingdeeConfig;
|
import com.finance.system.adapter.kingdee.KingdeeConfig;
|
||||||
import com.finance.system.adapter.feishu.FeishuApprovalService;
|
import com.finance.system.adapter.feishu.FeishuApprovalService;
|
||||||
@@ -26,6 +27,7 @@ import java.time.LocalDateTime;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -46,6 +48,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
private final ReimPaymentRepository reimPaymentRepository;
|
private final ReimPaymentRepository reimPaymentRepository;
|
||||||
private final SysApprovalNodeRepository sysApprovalNodeRepository;
|
private final SysApprovalNodeRepository sysApprovalNodeRepository;
|
||||||
private final KingdeeConfig kingdeeConfig;
|
private final KingdeeConfig kingdeeConfig;
|
||||||
|
private final ReimbursementFormService reimbursementFormService;
|
||||||
|
private final com.finance.system.service.ReimbursementAttachmentService reimbursementAttachmentService;
|
||||||
private RoleService roleService;
|
private RoleService roleService;
|
||||||
private FeishuApprovalService feishuApprovalService;
|
private FeishuApprovalService feishuApprovalService;
|
||||||
private ReimbursementRoutePreviewService routePreviewService;
|
private ReimbursementRoutePreviewService routePreviewService;
|
||||||
@@ -208,6 +212,11 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
.orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
|
.orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
|
||||||
validateFieldPermissions(request, userId, null, true);
|
validateFieldPermissions(request, userId, null, true);
|
||||||
validateRequest(request, userId);
|
validateRequest(request, userId);
|
||||||
|
ReimbursementFormService.PinnedForm pinnedForm = reimbursementFormService.validateForWrite(
|
||||||
|
request.getFormFingerprint(), request.getFormValues());
|
||||||
|
java.util.Map<Integer,List<ReimAttachment>> attachmentClaims = pinnedForm.getFingerprint() == null
|
||||||
|
? Collections.emptyMap() : reimbursementAttachmentService.validateClaims(
|
||||||
|
request.getItems(), pinnedForm.getFingerprint(), userId, null);
|
||||||
|
|
||||||
ReimApplication app = new ReimApplication();
|
ReimApplication app = new ReimApplication();
|
||||||
app.setApplicationNo(generateApplicationNo());
|
app.setApplicationNo(generateApplicationNo());
|
||||||
@@ -227,11 +236,17 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
app.setBudgetStatus(BudgetStatus.PENDING.name());
|
app.setBudgetStatus(BudgetStatus.PENDING.name());
|
||||||
app.setSourceSystem("LOCAL");
|
app.setSourceSystem("LOCAL");
|
||||||
app.setSourceStatus(kingdeeConfig.isEnabled() ? SyncStatus.PENDING.name() : "NOT_CONFIGURED");
|
app.setSourceStatus(kingdeeConfig.isEnabled() ? SyncStatus.PENDING.name() : "NOT_CONFIGURED");
|
||||||
|
app.setFeishuFormFingerprint(pinnedForm.getFingerprint());
|
||||||
|
app.setFeishuFormSchema(pinnedForm.getSchema());
|
||||||
|
app.setFeishuFormValues(pinnedForm.getValues());
|
||||||
app.setDeleted(false);
|
app.setDeleted(false);
|
||||||
|
|
||||||
app = reimApplicationRepository.save(app);
|
app = reimApplicationRepository.save(app);
|
||||||
|
|
||||||
saveItems(app.getId(), request.getItems());
|
List<ReimExpenseItem> savedItems = saveItems(app.getId(), request.getItems());
|
||||||
|
claimAttachments(app.getId(), savedItems, attachmentClaims);
|
||||||
|
app.setFeishuFormDisplayValues(reimbursementFormService.buildDisplayValues(app));
|
||||||
|
app = reimApplicationRepository.save(app);
|
||||||
|
|
||||||
log.info("创建报销申请: applicationNo={}, userId={}", app.getApplicationNo(), userId);
|
log.info("创建报销申请: applicationNo={}, userId={}", app.getApplicationNo(), userId);
|
||||||
return buildDetail(app);
|
return buildDetail(app);
|
||||||
@@ -254,6 +269,11 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
}
|
}
|
||||||
validateFieldPermissions(request, userId, app, false);
|
validateFieldPermissions(request, userId, app, false);
|
||||||
validateRequest(request, app.getApplicantId());
|
validateRequest(request, app.getApplicantId());
|
||||||
|
ReimbursementFormService.PinnedForm pinnedForm = reimbursementFormService.validateForWrite(
|
||||||
|
request.getFormFingerprint(), request.getFormValues());
|
||||||
|
java.util.Map<Integer,List<ReimAttachment>> attachmentClaims = pinnedForm.getFingerprint() == null
|
||||||
|
? Collections.emptyMap() : reimbursementAttachmentService.validateClaims(
|
||||||
|
request.getItems(), pinnedForm.getFingerprint(), userId, app);
|
||||||
|
|
||||||
app.setTitle(request.getTitle());
|
app.setTitle(request.getTitle());
|
||||||
app.setExpenseTypeId(request.getExpenseTypeId());
|
app.setExpenseTypeId(request.getExpenseTypeId());
|
||||||
@@ -262,8 +282,20 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
app.setDescription(request.getDescription());
|
app.setDescription(request.getDescription());
|
||||||
app.setPayeeName(request.getPayeeName());
|
app.setPayeeName(request.getPayeeName());
|
||||||
app.setPayeeBankId(request.getPayeeBankId());
|
app.setPayeeBankId(request.getPayeeBankId());
|
||||||
|
app.setFeishuFormFingerprint(pinnedForm.getFingerprint());
|
||||||
|
app.setFeishuFormSchema(pinnedForm.getSchema());
|
||||||
|
app.setFeishuFormValues(pinnedForm.getValues());
|
||||||
|
List<ReimAttachment> previousAttachments = reimAttachmentRepository
|
||||||
|
.findByApplicationIdAndExpenseItemIdIsNotNullAndUploadStatus(id, "UPLOADED");
|
||||||
|
reimbursementAttachmentService.detachApplicationAttachments(id);
|
||||||
reimExpenseItemRepository.deleteByApplicationId(id);
|
reimExpenseItemRepository.deleteByApplicationId(id);
|
||||||
saveItems(app.getId(), request.getItems());
|
reimExpenseItemRepository.flush();
|
||||||
|
List<ReimExpenseItem> savedItems = saveItems(app.getId(), request.getItems());
|
||||||
|
claimAttachments(app.getId(), savedItems, attachmentClaims);
|
||||||
|
Set<Long> retained = attachmentClaims.values().stream().flatMap(List::stream)
|
||||||
|
.map(ReimAttachment::getId).collect(Collectors.toSet());
|
||||||
|
reimbursementAttachmentService.deleteOmitted(previousAttachments, retained, userId);
|
||||||
|
app.setFeishuFormDisplayValues(reimbursementFormService.buildDisplayValues(app));
|
||||||
// A returned submission re-enters the editable draft state. The next
|
// A returned submission re-enters the editable draft state. The next
|
||||||
// explicit submit then starts a fresh approval transition while the
|
// explicit submit then starts a fresh approval transition while the
|
||||||
// original application number remains unchanged.
|
// original application number remains unchanged.
|
||||||
@@ -431,8 +463,21 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
|
|
||||||
private void ensureCanRead(ReimApplication app, Long currentId) {
|
private void ensureCanRead(ReimApplication app, Long currentId) {
|
||||||
if (currentId == null) throw new com.finance.system.exception.UnauthorizedException("未登录");
|
if (currentId == null) throw new com.finance.system.exception.UnauthorizedException("未登录");
|
||||||
if (currentId.equals(app.getApplicantId())) return;
|
if (currentId.equals(app.getApplicantId())) {
|
||||||
if (roleService != null && roleService.hasPermission(currentId, "page.finance-receipt")) return;
|
if (roleService == null
|
||||||
|
|| roleService.hasPermission(currentId, "reimbursement:view-own")
|
||||||
|
|| roleService.hasPermission(currentId, "reimbursement.application.view-own")
|
||||||
|
|| roleService.hasPermission(currentId, "page.applications")
|
||||||
|
|| roleService.hasPermission(currentId, "page.application-edit")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (roleService != null && (
|
||||||
|
roleService.hasPermission(currentId, "reimbursement:view-all")
|
||||||
|
|| roleService.hasPermission(currentId, "reimbursement.application.view-all")
|
||||||
|
|| roleService.hasPermission(currentId, "page.finance-receipt"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (roleService == null && (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole())) return;
|
if (roleService == null && (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole())) return;
|
||||||
throw new org.springframework.security.access.AccessDeniedException("无权访问该申请");
|
throw new org.springframework.security.access.AccessDeniedException("无权访问该申请");
|
||||||
}
|
}
|
||||||
@@ -549,7 +594,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void saveItems(Long applicationId, List<ExpenseItemDto> items) {
|
private List<ReimExpenseItem> saveItems(Long applicationId, List<ExpenseItemDto> items) {
|
||||||
|
List<ReimExpenseItem> saved = new ArrayList<>();
|
||||||
int seq = 1;
|
int seq = 1;
|
||||||
for (ExpenseItemDto dto : items) {
|
for (ExpenseItemDto dto : items) {
|
||||||
ReimExpenseItem item = new ReimExpenseItem();
|
ReimExpenseItem item = new ReimExpenseItem();
|
||||||
@@ -560,9 +606,17 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
item.setDescription(dto.getDescription());
|
item.setDescription(dto.getDescription());
|
||||||
item.setAmount(dto.getAmount());
|
item.setAmount(dto.getAmount());
|
||||||
item.setCurrency("CNY");
|
item.setCurrency("CNY");
|
||||||
reimExpenseItemRepository.save(item);
|
saved.add(reimExpenseItemRepository.save(item));
|
||||||
seq++;
|
seq++;
|
||||||
}
|
}
|
||||||
|
reimExpenseItemRepository.flush();
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void claimAttachments(Long applicationId, List<ReimExpenseItem> items,
|
||||||
|
java.util.Map<Integer,List<ReimAttachment>> claims) {
|
||||||
|
for (int i=0;i<items.size();i++) reimbursementAttachmentService.claim(applicationId, items.get(i),
|
||||||
|
claims.getOrDefault(i, Collections.emptyList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Long resolveApprover(SysApprovalNode node) {
|
private Long resolveApprover(SysApprovalNode node) {
|
||||||
@@ -591,7 +645,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
|
|
||||||
List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(app.getId());
|
List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(app.getId());
|
||||||
List<ReimInvoice> invoices = reimInvoiceRepository.findByApplicationId(app.getId());
|
List<ReimInvoice> invoices = reimInvoiceRepository.findByApplicationId(app.getId());
|
||||||
List<ReimAttachment> attachments = reimAttachmentRepository.findByApplicationId(app.getId());
|
List<ReimAttachment> attachments = reimAttachmentRepository
|
||||||
|
.findByApplicationIdAndExpenseItemIdIsNotNullAndUploadStatus(app.getId(), "UPLOADED");
|
||||||
List<ReimApprovalRecord> approvalRecords = reimApprovalRecordRepository
|
List<ReimApprovalRecord> approvalRecords = reimApprovalRecordRepository
|
||||||
.findByApplicationIdOrderByActionTimeAsc(app.getId());
|
.findByApplicationIdOrderByActionTimeAsc(app.getId());
|
||||||
List<ReimPayment> payments = reimPaymentRepository.findByApplicationId(app.getId());
|
List<ReimPayment> payments = reimPaymentRepository.findByApplicationId(app.getId());
|
||||||
@@ -641,9 +696,25 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
.attachments(attachments.stream().map(this::buildAttachment).collect(Collectors.toList()))
|
.attachments(attachments.stream().map(this::buildAttachment).collect(Collectors.toList()))
|
||||||
.approvalRecords(approvalRecords.stream().map(this::buildApprovalRecord).collect(Collectors.toList()))
|
.approvalRecords(approvalRecords.stream().map(this::buildApprovalRecord).collect(Collectors.toList()))
|
||||||
.payments(payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList()))
|
.payments(payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList()))
|
||||||
|
.formSnapshot(buildFormSnapshot(app))
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ReimApplicationDetail.FormSnapshot buildFormSnapshot(ReimApplication app) {
|
||||||
|
if (!org.springframework.util.StringUtils.hasText(app.getFeishuFormSchema())) {
|
||||||
|
return ReimApplicationDetail.FormSnapshot.builder().mode("LEGACY")
|
||||||
|
.fields(Collections.emptyList()).values(Collections.emptyMap()).build();
|
||||||
|
}
|
||||||
|
if (!org.springframework.util.StringUtils.hasText(app.getFeishuFormFingerprint())) {
|
||||||
|
return ReimApplicationDetail.FormSnapshot.builder().mode("LOCAL")
|
||||||
|
.fields(Collections.emptyList()).values(Collections.emptyMap()).build();
|
||||||
|
}
|
||||||
|
List<ReimbursementFormField> fields = reimbursementFormService.parseSchema(app.getFeishuFormSchema());
|
||||||
|
return ReimApplicationDetail.FormSnapshot.builder().mode("FEISHU")
|
||||||
|
.fingerprint(app.getFeishuFormFingerprint())
|
||||||
|
.fields(fields).values(reimbursementFormService.mergedSnapshotValues(app, fields)).build();
|
||||||
|
}
|
||||||
|
|
||||||
private ExpenseItemDto buildExpenseItem(ReimExpenseItem item) {
|
private ExpenseItemDto buildExpenseItem(ReimExpenseItem item) {
|
||||||
ExpenseItemDto dto = new ExpenseItemDto();
|
ExpenseItemDto dto = new ExpenseItemDto();
|
||||||
dto.setId(item.getId());
|
dto.setId(item.getId());
|
||||||
@@ -652,6 +723,10 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
dto.setCategory(item.getCategory());
|
dto.setCategory(item.getCategory());
|
||||||
dto.setDescription(item.getDescription());
|
dto.setDescription(item.getDescription());
|
||||||
dto.setAmount(item.getAmount());
|
dto.setAmount(item.getAmount());
|
||||||
|
List<ReimAttachment> rowAttachments = reimAttachmentRepository
|
||||||
|
.findByExpenseItemIdAndApplicationIdIsNotNullAndUploadStatusOrderByIdAsc(item.getId(), "UPLOADED");
|
||||||
|
dto.setAttachmentIds(rowAttachments.stream().map(ReimAttachment::getId).collect(Collectors.toList()));
|
||||||
|
dto.setAttachments(rowAttachments.stream().map(this::buildAttachment).collect(Collectors.toList()));
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -672,7 +747,9 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
|||||||
dto.setId(attachment.getId());
|
dto.setId(attachment.getId());
|
||||||
dto.setFileName(attachment.getFileName());
|
dto.setFileName(attachment.getFileName());
|
||||||
dto.setFileType(attachment.getFileType());
|
dto.setFileType(attachment.getFileType());
|
||||||
dto.setFileUrl(attachment.getFileUrl());
|
dto.setContentType(attachment.getContentType());
|
||||||
|
dto.setFileSize(attachment.getFileSize());
|
||||||
|
dto.setExpenseItemId(attachment.getExpenseItemId());
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.finance.system.entity.*;
|
|||||||
import com.finance.system.exception.BusinessException;
|
import com.finance.system.exception.BusinessException;
|
||||||
import com.finance.system.repository.*;
|
import com.finance.system.repository.*;
|
||||||
import com.finance.system.service.ReimbursementFingerprintService;
|
import com.finance.system.service.ReimbursementFingerprintService;
|
||||||
|
import com.finance.system.service.ReimbursementFormService;
|
||||||
import com.finance.system.service.RoleService;
|
import com.finance.system.service.RoleService;
|
||||||
import com.finance.system.util.Sha256;
|
import com.finance.system.util.Sha256;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -38,6 +39,7 @@ public class ReimbursementRoutePreviewService {
|
|||||||
private final SysUserRepository users;
|
private final SysUserRepository users;
|
||||||
private final RoleService roles;
|
private final RoleService roles;
|
||||||
private final ReimbursementFingerprintService fingerprints;
|
private final ReimbursementFingerprintService fingerprints;
|
||||||
|
private final ReimbursementFormService forms;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
@Value("${feishu.approval.snapshot-max-age-seconds:86400}")
|
@Value("${feishu.approval.snapshot-max-age-seconds:86400}")
|
||||||
@@ -45,6 +47,7 @@ public class ReimbursementRoutePreviewService {
|
|||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public RoutePreviewDto preview(ReimApplication application, Long userId) {
|
public RoutePreviewDto preview(ReimApplication application, Long userId) {
|
||||||
|
forms.assertApplicationMatchesCurrentForm(application);
|
||||||
Route route = currentRoute(false);
|
Route route = currentRoute(false);
|
||||||
return issue(application, userId, route, fingerprints.fingerprint(application));
|
return issue(application, userId, route, fingerprints.fingerprint(application));
|
||||||
}
|
}
|
||||||
@@ -86,6 +89,7 @@ public class ReimbursementRoutePreviewService {
|
|||||||
/** Called only while the reimbursement is pessimistically locked. */
|
/** Called only while the reimbursement is pessimistically locked. */
|
||||||
@Transactional
|
@Transactional
|
||||||
public ReimRoutePreviewToken validateForSubmit(ReimApplication application, Long userId, String rawToken) {
|
public ReimRoutePreviewToken validateForSubmit(ReimApplication application, Long userId, String rawToken) {
|
||||||
|
forms.assertApplicationMatchesCurrentFormLocked(application);
|
||||||
if (!StringUtils.hasText(rawToken) || rawToken.length() > 512) throw invalid();
|
if (!StringUtils.hasText(rawToken) || rawToken.length() > 512) throw invalid();
|
||||||
ReimRoutePreviewToken token = tokens.findByTokenHashForUpdate(Sha256.hex(rawToken))
|
ReimRoutePreviewToken token = tokens.findByTokenHashForUpdate(Sha256.hex(rawToken))
|
||||||
.orElseThrow(this::invalid);
|
.orElseThrow(this::invalid);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.finance.system.exception.*;
|
|||||||
import com.finance.system.repository.*;
|
import com.finance.system.repository.*;
|
||||||
import com.finance.system.service.RoleService;
|
import com.finance.system.service.RoleService;
|
||||||
import com.finance.system.service.ReimbursementFingerprintService;
|
import com.finance.system.service.ReimbursementFingerprintService;
|
||||||
|
import com.finance.system.service.ReimbursementFormService;
|
||||||
import com.finance.system.util.Sha256;
|
import com.finance.system.util.Sha256;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.springframework.dao.DataIntegrityViolationException;
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
@@ -37,6 +38,7 @@ public class ReimbursementSubmissionStateService {
|
|||||||
private final SysUserRepository users;
|
private final SysUserRepository users;
|
||||||
private final SysApprovalNodeRepository localNodes;
|
private final SysApprovalNodeRepository localNodes;
|
||||||
private final IntFeishuApprovalAttemptRepository attempts;
|
private final IntFeishuApprovalAttemptRepository attempts;
|
||||||
|
private final ReimbursementFormService forms;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public PreparedSubmission prepare(Long applicationId, Long userId, String rawToken) {
|
public PreparedSubmission prepare(Long applicationId, Long userId, String rawToken) {
|
||||||
@@ -59,6 +61,9 @@ public class ReimbursementSubmissionStateService {
|
|||||||
mapping.setStatus("CREATE_OUTCOME_UNKNOWN");
|
mapping.setStatus("CREATE_OUTCOME_UNKNOWN");
|
||||||
resumable = true;
|
resumable = true;
|
||||||
}
|
}
|
||||||
|
// New attempts must still match the active form while the application row is locked.
|
||||||
|
// Unknown-outcome recovery keeps using its already persisted exact payload.
|
||||||
|
if (!resumable) forms.assertApplicationMatchesCurrentFormLocked(app);
|
||||||
ReimRoutePreviewToken token = resumable
|
ReimRoutePreviewToken token = resumable
|
||||||
? routes.validateForUnknownResume(app, userId, rawToken)
|
? routes.validateForUnknownResume(app, userId, rawToken)
|
||||||
: routes.validateForSubmit(app, userId, rawToken);
|
: routes.validateForSubmit(app, userId, rawToken);
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ server:
|
|||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: finance-system
|
name: finance-system
|
||||||
|
servlet:
|
||||||
|
multipart:
|
||||||
|
max-file-size: 50MB
|
||||||
|
max-request-size: 51MB
|
||||||
datasource:
|
datasource:
|
||||||
url: "${DB_URL:jdbc:mysql://localhost:3306/finance_system?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}"
|
url: "${DB_URL:jdbc:mysql://localhost:3306/finance_system?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}"
|
||||||
username: "${DB_USERNAME}"
|
username: "${DB_USERNAME:root}"
|
||||||
password: "${DB_PASSWORD}"
|
password: "${DB_PASSWORD:123456}"
|
||||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
hikari:
|
hikari:
|
||||||
maximum-pool-size: 20
|
maximum-pool-size: 20
|
||||||
@@ -26,14 +30,17 @@ database:
|
|||||||
# Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone.
|
# Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone.
|
||||||
time-zone: "${DB_TIME_ZONE:Asia/Shanghai}"
|
time-zone: "${DB_TIME_ZONE:Asia/Shanghai}"
|
||||||
jwt:
|
jwt:
|
||||||
secret: "${JWT_SECRET:}"
|
secret: "${JWT_SECRET:Uqen22fWWeubQ6f2dFIWteMDIhd4PU4u}"
|
||||||
expiration: ${JWT_EXPIRATION:86400000}
|
expiration: ${JWT_EXPIRATION:86400000}
|
||||||
auth:
|
auth:
|
||||||
time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}"
|
time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}"
|
||||||
feishu:
|
feishu:
|
||||||
app-id: "${FEISHU_APP_ID:}"
|
# Feishu credentials are file/env only (not editable via 配置管理 UI).
|
||||||
app-secret: "${FEISHU_APP_SECRET:}"
|
enabled: ${FEISHU_ENABLED:true}
|
||||||
|
app-id: "${FEISHU_APP_ID:cli_aa1d754854f95ccd}"
|
||||||
|
app-secret: "${FEISHU_APP_SECRET:Uqen22fWWeubQ6f2dFIWteMDIhd4PU4u}"
|
||||||
redirect-uri: "${FEISHU_REDIRECT_URI:http://127.0.0.1:8080/api/feishu/callback}"
|
redirect-uri: "${FEISHU_REDIRECT_URI:http://127.0.0.1:8080/api/feishu/callback}"
|
||||||
|
sync-org-enabled: ${FEISHU_SYNC_ORG_ENABLED:true}
|
||||||
local-bootstrap-enabled: ${FEISHU_LOCAL_BOOTSTRAP_ENABLED:false}
|
local-bootstrap-enabled: ${FEISHU_LOCAL_BOOTSTRAP_ENABLED:false}
|
||||||
local-bootstrap-open-id: "${FEISHU_LOCAL_BOOTSTRAP_OPEN_ID:}"
|
local-bootstrap-open-id: "${FEISHU_LOCAL_BOOTSTRAP_OPEN_ID:}"
|
||||||
directory:
|
directory:
|
||||||
@@ -53,8 +60,9 @@ app:
|
|||||||
frontend-url: ${FRONTEND_URL:http://localhost:5173}
|
frontend-url: ${FRONTEND_URL:http://localhost:5173}
|
||||||
# Required when saving secret=true integration settings. Never put a real
|
# Required when saving secret=true integration settings. Never put a real
|
||||||
# key in this file; provide APP_INTEGRATION_ENCRYPTION_KEY at deployment.
|
# key in this file; provide APP_INTEGRATION_ENCRYPTION_KEY at deployment.
|
||||||
integration-encryption-key: "${APP_INTEGRATION_ENCRYPTION_KEY:}"
|
integration-encryption-key: "${APP_INTEGRATION_ENCRYPTION_KEY:9Srk7wn4ayAb1TyPRFfdlyDQB6h9ss3f}"
|
||||||
kingdee:
|
kingdee:
|
||||||
|
# System account for sync/query. Employee write ops require bound accounts.
|
||||||
enabled: ${KINGDEE_ENABLED:false}
|
enabled: ${KINGDEE_ENABLED:false}
|
||||||
base-url: ${KINGDEE_BASE_URL:}
|
base-url: ${KINGDEE_BASE_URL:}
|
||||||
allowed-hosts: ${KINGDEE_ALLOWED_HOSTS:app.kingdee.com}
|
allowed-hosts: ${KINGDEE_ALLOWED_HOSTS:app.kingdee.com}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
|
||||||
|
|
||||||
|
<property name="LOG_PATH" value="${LOG_PATH:-logs}"/>
|
||||||
|
<property name="APP_NAME" value="finance-system"/>
|
||||||
|
|
||||||
|
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||||
|
<charset>UTF-8</charset>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${LOG_PATH}/${APP_NAME}.log</file>
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||||
|
<fileNamePattern>${LOG_PATH}/${APP_NAME}.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||||
|
<maxFileSize>50MB</maxFileSize>
|
||||||
|
<maxHistory>30</maxHistory>
|
||||||
|
<totalSizeCap>2GB</totalSizeCap>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||||
|
<charset>UTF-8</charset>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
|
||||||
|
<queueSize>1024</queueSize>
|
||||||
|
<discardingThreshold>0</discardingThreshold>
|
||||||
|
<appender-ref ref="FILE"/>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<logger name="com.finance.system" level="DEBUG"/>
|
||||||
|
<logger name="org.springframework.security" level="INFO"/>
|
||||||
|
<logger name="org.hibernate.SQL" level="WARN"/>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="CONSOLE"/>
|
||||||
|
<appender-ref ref="ASYNC_FILE"/>
|
||||||
|
</root>
|
||||||
|
</configuration>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.finance.system.adapter.feishu;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.finance.system.dto.ReimbursementFormField;
|
||||||
|
import com.finance.system.entity.ReimApplication;
|
||||||
|
import com.finance.system.util.Sha256;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class FeishuApprovalFormBuilderTest {
|
||||||
|
private final ObjectMapper json = new ObjectMapper();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void buildsNumericAmountCurrencyAttachmentsFormulaAndTwoDimensionalFieldList() throws Exception {
|
||||||
|
ReimbursementFormField amount = field("amount-id", "amount", "DECIMAL", "EXPENSE_AMOUNT", "金额", false);
|
||||||
|
amount.setCurrency("CNY");
|
||||||
|
ReimbursementFormField attachment = field("attachment-id", "attachmentV2", "ATTACHMENT", "EXPENSE_ATTACHMENT", "附件", false);
|
||||||
|
ReimbursementFormField reason = field("reason-id", "input", "TEXT", "EXPENSE_DESCRIPTION", "报销事由", false);
|
||||||
|
ReimbursementFormField date = field("date-id", "date", "DATE", "EXPENSE_DATE", "发生日期", false);
|
||||||
|
ReimbursementFormField details = field("detail-id", "fieldList", "EXPENSE_ITEMS", "EXPENSE_ITEMS", "明细", false);
|
||||||
|
details.setChildren(Arrays.asList(reason, date, amount, attachment));
|
||||||
|
ReimbursementFormField formula = field("formula-id", "formula", "FORMULA", "TOTAL_AMOUNT", "总金额", true);
|
||||||
|
ReimbursementFormField topAmount = field("top-amount-id", "amount", "DECIMAL", "CUSTOM", "预支金额", false);
|
||||||
|
topAmount.setCurrency("CNY");
|
||||||
|
List<ReimbursementFormField> fields = Arrays.asList(details, formula, topAmount);
|
||||||
|
|
||||||
|
Map<String,Object> attachmentValue = new LinkedHashMap<>();
|
||||||
|
attachmentValue.put("attachment_id", 7L);
|
||||||
|
attachmentValue.put("provider_code", "provider-file-code");
|
||||||
|
attachmentValue.put("display_name", "receipt.pdf");
|
||||||
|
Map<String,Object> row = new LinkedHashMap<>();
|
||||||
|
row.put("reason-id", "差旅");
|
||||||
|
row.put("date-id", "2026-09-30T00:00:00+08:00");
|
||||||
|
row.put("amount-id", new BigDecimal("12.30"));
|
||||||
|
row.put("attachment-id", Collections.singletonList(attachmentValue));
|
||||||
|
Map<String,Object> display = new LinkedHashMap<>();
|
||||||
|
display.put("detail-id", Collections.singletonList(row));
|
||||||
|
display.put("formula-id", new BigDecimal("12.30"));
|
||||||
|
|
||||||
|
ReimApplication app = new ReimApplication();
|
||||||
|
String schema = json.writeValueAsString(fields);
|
||||||
|
app.setFeishuFormSchema(schema);
|
||||||
|
app.setFeishuFormFingerprint(Sha256.hex(schema));
|
||||||
|
app.setFeishuFormValues("{\"top-amount-id\":12.30}");
|
||||||
|
app.setFeishuFormDisplayValues(json.writeValueAsString(display));
|
||||||
|
app.setTotalAmount(new BigDecimal("12.30"));
|
||||||
|
|
||||||
|
JsonNode form = json.readTree(FeishuApprovalFormBuilder.buildFormJson(app));
|
||||||
|
assertThat(form.isArray()).isTrue();
|
||||||
|
JsonNode detail = form.get(0);
|
||||||
|
assertThat(detail.path("id").asText()).isEqualTo("detail-id");
|
||||||
|
assertThat(detail.path("value").isArray()).isTrue();
|
||||||
|
assertThat(detail.path("value").get(0).isArray()).isTrue();
|
||||||
|
Map<String,JsonNode> controls = new HashMap<>();
|
||||||
|
for (JsonNode control : detail.path("value").get(0)) controls.put(control.path("id").asText(), control);
|
||||||
|
assertThat(controls.get("amount-id").path("value").isNumber()).isTrue();
|
||||||
|
assertThat(controls.get("amount-id").path("value").decimalValue()).isEqualByComparingTo("12.3");
|
||||||
|
assertThat(controls.get("amount-id").path("currency").asText()).isEqualTo("CNY");
|
||||||
|
assertThat(controls.get("attachment-id").path("value").isArray()).isTrue();
|
||||||
|
assertThat(controls.get("attachment-id").path("value").get(0).asText()).isEqualTo("provider-file-code");
|
||||||
|
assertThat(form.get(1).path("value").isNumber()).isTrue();
|
||||||
|
assertThat(form.get(1).path("value").decimalValue()).isEqualByComparingTo("12.3");
|
||||||
|
assertThat(form.get(2).path("currency").asText()).isEqualTo("CNY");
|
||||||
|
assertThat(form.get(2).path("value").decimalValue()).isEqualByComparingTo("12.3");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ReimbursementFormField field(String id, String providerType, String type,
|
||||||
|
String binding, String label, boolean readOnly) {
|
||||||
|
return ReimbursementFormField.builder().id(id).valueKey(id).providerType(providerType).type(type)
|
||||||
|
.binding(binding).label(label).required(true).readOnly(readOnly).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.finance.system.adapter.feishu;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.finance.system.dto.ReimbursementFormField;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
class FeishuDefinitionNormalizerTest {
|
||||||
|
private final ObjectMapper json = new ObjectMapper();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void normalizesExactLiveNoCustomIdTemplateWithoutReplacingProviderIds() throws Exception {
|
||||||
|
String source = "{\"data\":{\"approval_code\":\"approval-live\","
|
||||||
|
+ "\"nodes\":[{\"id\":\"node-provider-1\",\"name\":\"财务审批\"}],"
|
||||||
|
+ "\"form\":["
|
||||||
|
+ control("contact-id", "contact", "报销人", true, null) + ","
|
||||||
|
+ control("department-id", "department", "报销人所属部门", true, null) + ","
|
||||||
|
+ control("reimbursement-date-id", "date", "报销日期", true, null) + ","
|
||||||
|
+ control("detail-provider-id", "fieldList", "明细", true,
|
||||||
|
"\"children\":["
|
||||||
|
+ control("reason-id", "input", "报销事由", true, null) + ","
|
||||||
|
+ control("date-id", "date", "发生日期", true, null) + ","
|
||||||
|
+ control("amount-id", "amount", "金额", true,
|
||||||
|
"\"option\":{\"currencyRange\":[\"CNY\",\"JPY\",\"USD\"]}") + ","
|
||||||
|
+ control("attachment-id", "attachmentV2", "附件", true, null) + "]") + ","
|
||||||
|
+ control("formula-id", "formula", "总金额", true, null)
|
||||||
|
+ "]}}";
|
||||||
|
|
||||||
|
FeishuDefinitionNormalizer.NormalizedDefinition normalized =
|
||||||
|
new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "ignored");
|
||||||
|
|
||||||
|
assertThat(normalized.getApprovalCode()).isEqualTo("approval-live");
|
||||||
|
assertThat(normalized.getNodes().get(0).getNodeKey()).isEqualTo("node-provider-1");
|
||||||
|
Map<String,ReimbursementFormField> top = byBinding(normalized.getFormFields());
|
||||||
|
assertThat(top.get("APPLICANT_CONTACT").getId()).isEqualTo("contact-id");
|
||||||
|
assertThat(top.get("APPLICANT_DEPARTMENT").getId()).isEqualTo("department-id");
|
||||||
|
assertThat(top.get("REIMBURSEMENT_DATE").getId()).isEqualTo("reimbursement-date-id");
|
||||||
|
assertThat(top.get("TOTAL_AMOUNT").getType()).isEqualTo("FORMULA");
|
||||||
|
ReimbursementFormField details = top.get("EXPENSE_ITEMS");
|
||||||
|
assertThat(details.getId()).isEqualTo("detail-provider-id");
|
||||||
|
Map<String,ReimbursementFormField> children = byBinding(details.getChildren());
|
||||||
|
assertThat(children.keySet()).containsExactlyInAnyOrder(
|
||||||
|
"EXPENSE_DESCRIPTION", "EXPENSE_DATE", "EXPENSE_AMOUNT", "EXPENSE_ATTACHMENT");
|
||||||
|
assertThat(children.get("EXPENSE_AMOUNT").getCurrency()).isEqualTo("CNY");
|
||||||
|
assertThat(children.get("EXPENSE_AMOUNT").getOptions()).extracting("value").containsExactlyInAnyOrder("CNY", "JPY", "USD");
|
||||||
|
assertThat(children.get("EXPENSE_ATTACHMENT").getType()).isEqualTo("ATTACHMENT");
|
||||||
|
assertThat(children.get("EXPENSE_ATTACHMENT").getId()).isEqualTo("attachment-id");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void acceptsV2ChoiceOptionsFromValueArray() throws Exception {
|
||||||
|
String source = "{\"data\":{\"nodes\":[{\"id\":\"n1\"}],\"form\":["
|
||||||
|
+ "{\"id\":\"r\",\"custom_id\":\"choice\",\"type\":\"radioV2\",\"name\":\"单选\","
|
||||||
|
+ "\"value\":[{\"value\":\"a\",\"name\":\"甲\"}]},"
|
||||||
|
+ "{\"id\":\"c\",\"custom_id\":\"choices\",\"type\":\"checkboxV2\",\"name\":\"多选\","
|
||||||
|
+ "\"value\":[{\"value\":\"b\",\"name\":\"乙\"}]}]}}";
|
||||||
|
FeishuDefinitionNormalizer.NormalizedDefinition normalized =
|
||||||
|
new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "approval");
|
||||||
|
assertThat(normalized.getFormFields().get(0).getOptions().get(0).getValue()).isEqualTo("a");
|
||||||
|
assertThat(normalized.getFormFields().get(1).getOptions().get(0).getValue()).isEqualTo("b");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsDateTimeDefinitionFormatButKeepsDateOnlyDefault() throws Exception {
|
||||||
|
String source = "{\"data\":{\"nodes\":[{\"id\":\"n1\"}],\"form\":["
|
||||||
|
+ "{\"id\":\"d\",\"custom_id\":\"day\",\"type\":\"date\",\"name\":\"日期\","
|
||||||
|
+ "\"property\":{\"format\":\"YYYY-MM-DD HH:mm\"}}]}}";
|
||||||
|
assertThatThrownBy(() -> new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "approval"))
|
||||||
|
.isInstanceOf(com.finance.system.exception.BusinessException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String,ReimbursementFormField> byBinding(List<ReimbursementFormField> fields) {
|
||||||
|
Map<String,ReimbursementFormField> result = new LinkedHashMap<>();
|
||||||
|
for (ReimbursementFormField field : fields) result.put(field.getBinding(), field);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String control(String id, String type, String name, boolean required, String extra) {
|
||||||
|
return "{\"id\":\"" + id + "\",\"type\":\"" + type + "\",\"name\":\"" + name
|
||||||
|
+ "\",\"required\":" + required + (extra == null ? "" : "," + extra) + "}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
package com.finance.system.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.finance.system.adapter.feishu.FeishuApprovalFileClient;
|
||||||
|
import com.finance.system.dto.AttachmentDto;
|
||||||
|
import com.finance.system.dto.ExpenseItemDto;
|
||||||
|
import com.finance.system.dto.ReimbursementFormField;
|
||||||
|
import com.finance.system.entity.ReimAttachment;
|
||||||
|
import com.finance.system.exception.BusinessException;
|
||||||
|
import com.finance.system.repository.ReimApplicationRepository;
|
||||||
|
import com.finance.system.repository.ReimAttachmentRepository;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashSet;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
class ReimbursementAttachmentServiceTest {
|
||||||
|
@Test
|
||||||
|
void acceptsPlainOriginalNameAndRejectsPathsAndControlCharacters() {
|
||||||
|
assertThat(ReimbursementAttachmentService.safeName(" receipt 01.pdf ")).isEqualTo("receipt 01.pdf");
|
||||||
|
assertThatThrownBy(() -> ReimbursementAttachmentService.safeName("../receipt.pdf"))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
assertThatThrownBy(() -> ReimbursementAttachmentService.safeName("folder\\receipt.pdf"))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
assertThatThrownBy(() -> ReimbursementAttachmentService.safeName("receipt\r.pdf"))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void enforcesSafeExtensionAndCompatibleMimePolicy() {
|
||||||
|
assertThat(ReimbursementAttachmentService.allowedContentType("receipt.PDF", "application/pdf"))
|
||||||
|
.isEqualTo("application/pdf");
|
||||||
|
assertThat(ReimbursementAttachmentService.allowedContentType("photo.jpeg", "application/octet-stream"))
|
||||||
|
.isEqualTo("application/octet-stream");
|
||||||
|
for (String name : Arrays.asList("run.exe", "page.html", "vector.svg", "bundle.zip"))
|
||||||
|
assertThatThrownBy(() -> ReimbursementAttachmentService.allowedContentType(name, "application/octet-stream"))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
assertThatThrownBy(() -> ReimbursementAttachmentService.allowedContentType("receipt.pdf", "text/html"))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsIndividualSizeAndStagedQuotaBeforeProviderUpload() {
|
||||||
|
ReimbursementFormService forms = mock(ReimbursementFormService.class);
|
||||||
|
FeishuApprovalFileClient client = mock(FeishuApprovalFileClient.class);
|
||||||
|
ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimbursementAttachmentService service = new ReimbursementAttachmentService(
|
||||||
|
forms, client, repository, mock(ReimApplicationRepository.class));
|
||||||
|
|
||||||
|
MultipartFile tooLarge = mock(MultipartFile.class);
|
||||||
|
when(tooLarge.getOriginalFilename()).thenReturn("large.pdf");
|
||||||
|
when(tooLarge.isEmpty()).thenReturn(false);
|
||||||
|
when(tooLarge.getSize()).thenReturn(ReimbursementAttachmentService.MAX_FILE_BYTES + 1);
|
||||||
|
assertThatThrownBy(() -> service.upload(tooLarge, "fp", "control", 7L))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
|
||||||
|
ReimbursementFormField control = ReimbursementFormField.builder().id("control").build();
|
||||||
|
when(forms.requireCurrentAttachmentControl("fp", "control")).thenReturn(control);
|
||||||
|
when(repository.countByUploaderIdAndApplicationIdIsNullAndUploadStatus(7L, "UPLOADED"))
|
||||||
|
.thenReturn(ReimbursementAttachmentService.MAX_STAGED_COUNT);
|
||||||
|
when(repository.sumStagedBytes(7L, "UPLOADED")).thenReturn(0L);
|
||||||
|
MockMultipartFile valid = new MockMultipartFile("file", "receipt.pdf", "application/pdf", new byte[]{1});
|
||||||
|
assertThatThrownBy(() -> service.upload(valid, "fp", "control", 7L))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
verifyNoInteractions(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void countsEveryUploadTodayRegardlessOfClaimOrDeletionBeforeProviderUpload() {
|
||||||
|
ReimbursementFormService forms = mock(ReimbursementFormService.class);
|
||||||
|
FeishuApprovalFileClient client = mock(FeishuApprovalFileClient.class);
|
||||||
|
ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimbursementAttachmentService service = new ReimbursementAttachmentService(
|
||||||
|
forms, client, repository, mock(ReimApplicationRepository.class));
|
||||||
|
when(forms.requireCurrentAttachmentControl("fp", "control"))
|
||||||
|
.thenReturn(ReimbursementFormField.builder().id("control").build());
|
||||||
|
when(repository.countByUploaderIdAndCreatedAtGreaterThanEqual(eq(7L), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(ReimbursementAttachmentService.MAX_DAILY_COUNT);
|
||||||
|
|
||||||
|
MockMultipartFile file = new MockMultipartFile(
|
||||||
|
"file", "receipt.pdf", "application/pdf", new byte[]{1});
|
||||||
|
assertThatThrownBy(() -> service.upload(file, "fp", "control", 7L))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
|
||||||
|
org.mockito.ArgumentCaptor<LocalDateTime> start = org.mockito.ArgumentCaptor.forClass(LocalDateTime.class);
|
||||||
|
verify(repository).countByUploaderIdAndCreatedAtGreaterThanEqual(eq(7L), start.capture());
|
||||||
|
assertThat(start.getValue()).isEqualTo(LocalDate.now(ZoneId.of("Asia/Shanghai")).atStartOfDay());
|
||||||
|
verifyNoInteractions(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void enforcesDailyByteBudgetBeforeProviderUpload() {
|
||||||
|
ReimbursementFormService forms = mock(ReimbursementFormService.class);
|
||||||
|
FeishuApprovalFileClient client = mock(FeishuApprovalFileClient.class);
|
||||||
|
ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimbursementAttachmentService service = new ReimbursementAttachmentService(
|
||||||
|
forms, client, repository, mock(ReimApplicationRepository.class));
|
||||||
|
when(forms.requireCurrentAttachmentControl("fp", "control"))
|
||||||
|
.thenReturn(ReimbursementFormField.builder().id("control").build());
|
||||||
|
when(repository.sumUploadedBytesSince(eq(7L), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(ReimbursementAttachmentService.MAX_DAILY_BYTES);
|
||||||
|
|
||||||
|
MockMultipartFile file = new MockMultipartFile(
|
||||||
|
"file", "receipt.pdf", "application/pdf", new byte[]{1});
|
||||||
|
assertThatThrownBy(() -> service.upload(file, "fp", "control", 7L))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
verifyNoInteractions(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validatesRequiredDuplicateAndOwnershipWhenClaiming() {
|
||||||
|
ReimbursementFormService forms = mock(ReimbursementFormService.class);
|
||||||
|
ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimbursementAttachmentService service = new ReimbursementAttachmentService(
|
||||||
|
forms, mock(FeishuApprovalFileClient.class), repository, mock(ReimApplicationRepository.class));
|
||||||
|
ReimbursementFormField required = ReimbursementFormField.builder().id("control").required(true).build();
|
||||||
|
when(forms.requireCurrentAttachmentControl("fp")).thenReturn(required);
|
||||||
|
|
||||||
|
ExpenseItemDto missing = ExpenseItemDto.builder().build();
|
||||||
|
assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(missing), "fp", 7L, null))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
|
||||||
|
ExpenseItemDto duplicate = ExpenseItemDto.builder().attachmentIds(Arrays.asList(1L, 1L)).build();
|
||||||
|
assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(duplicate), "fp", 7L, null))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
|
||||||
|
ExpenseItemDto foreign = ExpenseItemDto.builder().attachmentIds(Collections.singletonList(2L)).build();
|
||||||
|
ReimAttachment row = ReimAttachment.builder().id(2L).uploaderId(8L).uploadStatus("UPLOADED")
|
||||||
|
.formFingerprint("fp").formControlId("control").build();
|
||||||
|
when(repository.findAllByIdInForUpdate(anyCollection())).thenReturn(Collections.singletonList(row));
|
||||||
|
assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(foreign), "fp", 7L, null))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
|
||||||
|
ExpenseItemDto deletedClaim = ExpenseItemDto.builder().attachmentIds(Collections.singletonList(3L)).build();
|
||||||
|
ReimAttachment deleted = ReimAttachment.builder().id(3L).uploaderId(7L).uploadStatus("DELETED")
|
||||||
|
.formFingerprint("fp").formControlId("control").build();
|
||||||
|
when(repository.findAllByIdInForUpdate(Collections.singletonList(3L)))
|
||||||
|
.thenReturn(Collections.singletonList(deleted));
|
||||||
|
assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(deletedClaim), "fp", 7L, null))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void removeUsesLockedLookupAndExpenseMetadataCannotExposeProviderCodeOrUrl() throws Exception {
|
||||||
|
ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimbursementAttachmentService service = new ReimbursementAttachmentService(mock(ReimbursementFormService.class),
|
||||||
|
mock(FeishuApprovalFileClient.class), repository, mock(ReimApplicationRepository.class));
|
||||||
|
ReimAttachment row = ReimAttachment.builder().id(4L).uploaderId(7L).fileName("receipt.pdf")
|
||||||
|
.feishuFileCode("secret-code").fileUrl("secret-url").build();
|
||||||
|
when(repository.findByIdForUpdate(4L)).thenReturn(java.util.Optional.of(row));
|
||||||
|
service.remove(4L, 7L);
|
||||||
|
verify(repository).findByIdForUpdate(4L);
|
||||||
|
assertThat(row.getApplicationId()).isNull();
|
||||||
|
assertThat(row.getExpenseItemId()).isNull();
|
||||||
|
assertThat(row.getUploadStatus()).isEqualTo("DELETED");
|
||||||
|
verify(repository).save(row);
|
||||||
|
verify(repository, never()).delete(any(ReimAttachment.class));
|
||||||
|
|
||||||
|
ExpenseItemDto item = ExpenseItemDto.builder().attachments(Collections.singletonList(
|
||||||
|
AttachmentDto.builder().id(4L).fileName("receipt.pdf").build())).build();
|
||||||
|
String json = new ObjectMapper().writeValueAsString(item);
|
||||||
|
assertThat(json).contains("\"attachments\"").doesNotContain("secret-code", "secret-url", "provider");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void omittedDraftAttachmentsBecomeUnlinkedTombstones() {
|
||||||
|
ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimbursementAttachmentService service = new ReimbursementAttachmentService(mock(ReimbursementFormService.class),
|
||||||
|
mock(FeishuApprovalFileClient.class), repository, mock(ReimApplicationRepository.class));
|
||||||
|
ReimAttachment omitted = ReimAttachment.builder().id(9L).uploaderId(7L).applicationId(3L)
|
||||||
|
.expenseItemId(4L).uploadStatus("UPLOADED").feishuFileCode("internal-code").build();
|
||||||
|
|
||||||
|
service.deleteOmitted(Collections.singletonList(omitted), new HashSet<Long>(), 7L);
|
||||||
|
|
||||||
|
assertThat(omitted.getApplicationId()).isNull();
|
||||||
|
assertThat(omitted.getExpenseItemId()).isNull();
|
||||||
|
assertThat(omitted.getUploadStatus()).isEqualTo("DELETED");
|
||||||
|
assertThat(omitted.getFeishuFileCode()).isEqualTo("internal-code");
|
||||||
|
verify(repository).save(omitted);
|
||||||
|
verify(repository, never()).delete(any(ReimAttachment.class));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.finance.system.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.finance.system.adapter.feishu.FeishuApprovalService;
|
||||||
|
import com.finance.system.adapter.feishu.FeishuDefinitionNormalizer;
|
||||||
|
import com.finance.system.dto.ReimbursementFormField;
|
||||||
|
import com.finance.system.repository.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures the live-style Feishu template (editable department + multi-currency amount)
|
||||||
|
* survives {@link ReimbursementFormService#parseSchema} after sync.
|
||||||
|
*/
|
||||||
|
class ReimbursementFormSchemaValidationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void acceptsSyncedLiveTemplateWithCurrencyOptionsAndEditableDepartment() throws Exception {
|
||||||
|
ObjectMapper json = new ObjectMapper();
|
||||||
|
String source = "{\"data\":{\"approval_code\":\"approval-live\","
|
||||||
|
+ "\"nodes\":[{\"id\":\"node-1\",\"name\":\"财务审批\"}],"
|
||||||
|
+ "\"form\":["
|
||||||
|
+ "{\"id\":\"contact-id\",\"type\":\"contact\",\"name\":\"报销人\",\"required\":true},"
|
||||||
|
+ "{\"id\":\"department-id\",\"type\":\"department\",\"name\":\"报销人所属部门\",\"required\":true},"
|
||||||
|
+ "{\"id\":\"reimbursement-date-id\",\"type\":\"date\",\"name\":\"报销日期\",\"required\":true},"
|
||||||
|
+ "{\"id\":\"detail-id\",\"type\":\"fieldList\",\"name\":\"明细\",\"required\":true,\"children\":["
|
||||||
|
+ "{\"id\":\"reason-id\",\"type\":\"input\",\"name\":\"报销事由\",\"required\":true},"
|
||||||
|
+ "{\"id\":\"date-id\",\"type\":\"date\",\"name\":\"发生日期\",\"required\":true},"
|
||||||
|
+ "{\"id\":\"amount-id\",\"type\":\"amount\",\"name\":\"金额\",\"required\":true,"
|
||||||
|
+ "\"option\":{\"currencyRange\":[\"CNY\",\"JPY\",\"USD\"]}},"
|
||||||
|
+ "{\"id\":\"attachment-id\",\"type\":\"attachmentV2\",\"name\":\"附件\",\"required\":true}"
|
||||||
|
+ "]},"
|
||||||
|
+ "{\"id\":\"formula-id\",\"type\":\"formula\",\"name\":\"总金额\",\"required\":true}"
|
||||||
|
+ "]}}";
|
||||||
|
|
||||||
|
FeishuDefinitionNormalizer.NormalizedDefinition normalized =
|
||||||
|
new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "approval-live");
|
||||||
|
|
||||||
|
ReimbursementFormService service = new ReimbursementFormService(
|
||||||
|
mock(FeishuApprovalDefinitionSnapshotRepository.class),
|
||||||
|
mock(FeishuApprovalService.class),
|
||||||
|
json,
|
||||||
|
mock(SysUserRepository.class),
|
||||||
|
mock(SysDepartmentRepository.class),
|
||||||
|
mock(SysExpenseTypeRepository.class),
|
||||||
|
mock(ReimExpenseItemRepository.class),
|
||||||
|
mock(ReimAttachmentRepository.class),
|
||||||
|
mock(ApplicantDepartmentDirectoryRepository.class));
|
||||||
|
|
||||||
|
List<ReimbursementFormField> fields = service.parseSchema(normalized.getFormSchema());
|
||||||
|
assertThat(fields).isNotEmpty();
|
||||||
|
ReimbursementFormField department = fields.stream()
|
||||||
|
.filter(field -> "APPLICANT_DEPARTMENT".equals(field.getBinding()))
|
||||||
|
.findFirst().orElseThrow(IllegalStateException::new);
|
||||||
|
assertThat(department.isReadOnly()).isFalse();
|
||||||
|
ReimbursementFormField amount = fields.stream()
|
||||||
|
.filter(field -> "EXPENSE_ITEMS".equals(field.getBinding()))
|
||||||
|
.flatMap(field -> field.getChildren().stream())
|
||||||
|
.filter(field -> "EXPENSE_AMOUNT".equals(field.getBinding()))
|
||||||
|
.findFirst().orElseThrow(IllegalStateException::new);
|
||||||
|
assertThat(amount.getOptions()).extracting(ReimbursementFormField.Option::getValue)
|
||||||
|
.contains("CNY", "JPY", "USD");
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
package com.finance.system.service.impl;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.finance.system.adapter.kingdee.KingdeeConfig;
|
||||||
|
import com.finance.system.dto.ReimApplicationDetail;
|
||||||
|
import com.finance.system.entity.ReimApplication;
|
||||||
|
import com.finance.system.entity.ReimAttachment;
|
||||||
|
import com.finance.system.entity.ReimExpenseItem;
|
||||||
|
import com.finance.system.repository.*;
|
||||||
|
import com.finance.system.service.ReimbursementAttachmentService;
|
||||||
|
import com.finance.system.service.ReimbursementFormService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
class ReimApplicationAttachmentDetailTest {
|
||||||
|
@Test
|
||||||
|
void detailMapsSafeAttachmentMetadataToItsExpenseRowAndKeepsTopLevelCompatibility() throws Exception {
|
||||||
|
ReimApplicationRepository applications = mock(ReimApplicationRepository.class);
|
||||||
|
SysUserRepository users = mock(SysUserRepository.class);
|
||||||
|
SysDepartmentRepository departments = mock(SysDepartmentRepository.class);
|
||||||
|
SysExpenseTypeRepository expenseTypes = mock(SysExpenseTypeRepository.class);
|
||||||
|
SysBankAccountRepository banks = mock(SysBankAccountRepository.class);
|
||||||
|
ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class);
|
||||||
|
ReimInvoiceRepository invoices = mock(ReimInvoiceRepository.class);
|
||||||
|
ReimAttachmentRepository attachments = mock(ReimAttachmentRepository.class);
|
||||||
|
ReimApprovalRecordRepository approvals = mock(ReimApprovalRecordRepository.class);
|
||||||
|
ReimPaymentRepository payments = mock(ReimPaymentRepository.class);
|
||||||
|
|
||||||
|
ReimApplicationServiceImpl service = new ReimApplicationServiceImpl(applications, users, departments,
|
||||||
|
expenseTypes, banks, items, invoices, attachments, approvals, payments,
|
||||||
|
mock(SysApprovalNodeRepository.class), mock(KingdeeConfig.class),
|
||||||
|
mock(ReimbursementFormService.class), mock(ReimbursementAttachmentService.class));
|
||||||
|
|
||||||
|
ReimApplication app = new ReimApplication();
|
||||||
|
app.setId(10L);
|
||||||
|
app.setApplicantId(7L);
|
||||||
|
ReimExpenseItem item = new ReimExpenseItem();
|
||||||
|
item.setId(20L);
|
||||||
|
item.setApplicationId(10L);
|
||||||
|
ReimAttachment attachment = ReimAttachment.builder().id(30L).applicationId(10L).expenseItemId(20L)
|
||||||
|
.fileName("receipt.pdf").contentType("application/pdf").fileSize(123L)
|
||||||
|
.feishuFileCode("provider-secret").fileUrl("provider-url").build();
|
||||||
|
|
||||||
|
when(applications.findById(10L)).thenReturn(Optional.of(app));
|
||||||
|
when(users.findById(7L)).thenReturn(Optional.empty());
|
||||||
|
when(items.findByApplicationId(10L)).thenReturn(Collections.singletonList(item));
|
||||||
|
when(invoices.findByApplicationId(10L)).thenReturn(Collections.emptyList());
|
||||||
|
when(attachments.findByApplicationIdAndExpenseItemIdIsNotNullAndUploadStatus(10L, "UPLOADED"))
|
||||||
|
.thenReturn(Collections.singletonList(attachment));
|
||||||
|
when(attachments.findByExpenseItemIdAndApplicationIdIsNotNullAndUploadStatusOrderByIdAsc(20L, "UPLOADED"))
|
||||||
|
.thenReturn(Collections.singletonList(attachment));
|
||||||
|
when(approvals.findByApplicationIdOrderByActionTimeAsc(10L)).thenReturn(Collections.emptyList());
|
||||||
|
when(payments.findByApplicationId(10L)).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
|
ReimApplicationDetail detail = service.getApplicationDetail(10L, 7L);
|
||||||
|
assertThat(detail.getExpenseItems().get(0).getAttachmentIds()).containsExactly(30L);
|
||||||
|
assertThat(detail.getExpenseItems().get(0).getAttachments().get(0).getFileName()).isEqualTo("receipt.pdf");
|
||||||
|
assertThat(detail.getAttachments()).hasSize(1);
|
||||||
|
String payload = new ObjectMapper().writeValueAsString(detail);
|
||||||
|
assertThat(payload).doesNotContain("provider-secret", "provider-url", "feishuFileCode", "fileUrl");
|
||||||
|
}
|
||||||
|
}
|
||||||