根据已更新的原型调整系统
This commit is contained in:
1 parent
c3cdb9e2d6
commit
65de682b7a
69 files changed
+1355
-343
No files matched your search
@@ -19,6 +19,12 @@ application-local.yml
|
||||
application-local.yaml
|
||||
application-local.properties
|
||||
|
||||
# Private runtime configuration. Spring Boot loads ./config/application.yml
|
||||
# automatically when the process starts from the deployment directory.
|
||||
config/application.yml
|
||||
config/application.yaml
|
||||
!config/application.example.yml
|
||||
|
||||
# IDE, temporary and OS files.
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
@@ -1,26 +1,41 @@
|
||||
# Backend deployment notes
|
||||
|
||||
## Configuration file-only deployment
|
||||
|
||||
Runtime configuration is read from `./config/application.yml`. Spring Boot loads
|
||||
that file automatically when IDEA or the packaged JAR starts with the backend
|
||||
directory as its working directory; no environment variables or additional JVM
|
||||
arguments are required. Copy `config/application.example.yml` when preparing a
|
||||
new server and replace every `CHANGE_ME` value before startup.
|
||||
|
||||
`config/application.yml` contains database credentials and cryptographic keys and
|
||||
is intentionally ignored by Git. Include it in the private deployment package,
|
||||
restrict its filesystem permissions to the service account, and never publish it
|
||||
to a source repository. The classpath `src/main/resources/application.yml` keeps
|
||||
fail-fast placeholders so a missing private configuration cannot silently start
|
||||
with shared credentials.
|
||||
|
||||
Before saving any `secret=true` value in `sys_integration_config`, configure
|
||||
`APP_INTEGRATION_ENCRYPTION_KEY` (preferably a randomly generated 32-byte or
|
||||
longer secret) in the backend runtime environment. Do not commit the key or
|
||||
place a real value in `src/main/resources/application.yml`.
|
||||
`app.integration-encryption-key` in the private configuration file with a random
|
||||
32-byte-or-longer secret.
|
||||
|
||||
## Payee bank-account protection
|
||||
|
||||
Before creating or changing a payee bank account, provide these runtime secrets:
|
||||
Before creating or changing a payee bank account, provide these values in the
|
||||
private configuration file:
|
||||
|
||||
- `APP_BANK_ACCOUNT_ENCRYPTION_KEYS`: comma-separated `version=Base64Key`
|
||||
- `app.bank-account.encryption-keys`: comma-separated `version=Base64Key`
|
||||
entries; every decoded AES key must be exactly 32 bytes. Keep old versions
|
||||
present while old ciphertext still exists.
|
||||
- `APP_BANK_ACCOUNT_ACTIVE_KEY_VERSION`: the version used for new ciphertext.
|
||||
- `APP_BANK_ACCOUNT_FINGERPRINT_KEY`: a separate Base64-encoded 32-byte HMAC key.
|
||||
- `app.bank-account.active-key-version`: the version used for new ciphertext.
|
||||
- `app.bank-account.fingerprint-key`: a separate Base64-encoded 32-byte HMAC key.
|
||||
|
||||
Never reuse the integration key, JWT secret, database password, or an encryption
|
||||
key as the fingerprint key. Keep all real values outside the repository.
|
||||
|
||||
For an existing database, apply
|
||||
`V20261201_02__protect_payee_bank_accounts.sql` first. After a verified backup,
|
||||
set `APP_BANK_ACCOUNT_LEGACY_BACKFILL_ENABLED=true` for one observed maintenance
|
||||
set `app.bank-account.legacy-backfill-enabled=true` for one observed maintenance
|
||||
run, then return it to `false`. The backfill is deliberately non-destructive: it
|
||||
adds ciphertext, mask, fingerprint, and key version but does not clear the legacy
|
||||
plaintext column. Final plaintext clearing requires a separate reviewed change,
|
||||
@@ -42,7 +57,7 @@ or have a DBA pre-create those tables and keep the runtime account DML-only.
|
||||
Existing installations use the closed manifest and chain runner documented in
|
||||
[`../financial_system_docs/mysql-migration-runner.md`](../financial_system_docs/mysql-migration-runner.md), with
|
||||
DBA review and staging rehearsal; never run the clean-install snapshot against them.
|
||||
Deployment JDBC `serverTimezone` and `DB_TIME_ZONE` are both `UTC`. MySQL 8.4 LTS
|
||||
Deployment JDBC `serverTimezone` and `database.time-zone` are both `UTC`. MySQL 8.4 LTS
|
||||
is the runtime target; repository tests are not evidence of execution on a real
|
||||
production-equivalent instance, so the exact manifest requires production-like rehearsal.
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
# Copy this file to ./config/application.yml and replace every CHANGE_ME value.
|
||||
# The private application.yml is loaded automatically and must never be committed.
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: "jdbc:mysql://127.0.0.1:3306/finance_system?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC"
|
||||
username: "CHANGE_ME_DATABASE_USER"
|
||||
password: "CHANGE_ME_DATABASE_PASSWORD"
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
show-sql: false
|
||||
open-in-view: false
|
||||
|
||||
database:
|
||||
time-zone: "UTC"
|
||||
|
||||
jwt:
|
||||
secret: "CHANGE_ME_RANDOM_SECRET_AT_LEAST_32_UTF8_BYTES"
|
||||
expiration: 86400000
|
||||
|
||||
auth:
|
||||
time-zone: "Asia/Shanghai"
|
||||
|
||||
file:
|
||||
storage:
|
||||
provider: "local"
|
||||
local:
|
||||
base-path: "./uploads"
|
||||
aliyun-oss:
|
||||
region: ""
|
||||
endpoint: ""
|
||||
bucket: ""
|
||||
access-key-id: ""
|
||||
access-key-secret: ""
|
||||
session-token: ""
|
||||
cleanup:
|
||||
interval-ms: 30000
|
||||
stale-upload-minutes: 60
|
||||
|
||||
feishu:
|
||||
enabled: false
|
||||
app-id: ""
|
||||
app-secret: ""
|
||||
redirect-uri: "https://CHANGE_ME_PUBLIC_HOST/api/feishu/callback"
|
||||
sync-org-enabled: false
|
||||
local-bootstrap-enabled: false
|
||||
local-bootstrap-open-id: ""
|
||||
directory:
|
||||
bootstrap-sync-on-startup: false
|
||||
credential-revision: "1"
|
||||
max-elapsed-seconds: 120
|
||||
department-id-type: "open_department_id"
|
||||
directory-concurrency: 4
|
||||
max-retries: 3
|
||||
requests-per-second: 45
|
||||
requests-per-minute: 900
|
||||
approval:
|
||||
approval-code: ""
|
||||
verification-token: ""
|
||||
encrypt-key: ""
|
||||
|
||||
app:
|
||||
frontend-url: "https://CHANGE_ME_PUBLIC_HOST"
|
||||
frontend-allowed-origins: "https://CHANGE_ME_PUBLIC_HOST"
|
||||
integration-encryption-key: "CHANGE_ME_RANDOM_SECRET_AT_LEAST_32_UTF8_BYTES"
|
||||
bank-account:
|
||||
encryption-keys: "v1=CHANGE_ME_BASE64_ENCODED_32_BYTE_AES_KEY"
|
||||
fingerprint-key: "CHANGE_ME_BASE64_ENCODED_32_BYTE_HMAC_KEY"
|
||||
active-key-version: "v1"
|
||||
legacy-backfill-enabled: false
|
||||
|
||||
finance:
|
||||
payment:
|
||||
# 付款前财务核对门禁;付款后的银行回单缺失会单独进入待补回单状态。
|
||||
require-receipt-before-registration: false
|
||||
require-independent-review: false
|
||||
|
||||
kingdee:
|
||||
enabled: false
|
||||
base-url: ""
|
||||
allowed-hosts: "app.kingdee.com"
|
||||
client-id: ""
|
||||
client-secret: ""
|
||||
db-id: ""
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.finance.system: "INFO"
|
||||
com.finance.system.adapter.feishu.FeishuDirectoryService: "INFO"
|
||||
org.springframework.security: "INFO"
|
||||
org.hibernate.SQL: "WARN"
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
path: "/v3/api-docs"
|
||||
enabled: false
|
||||
swagger-ui:
|
||||
path: "/swagger-ui.html"
|
||||
enabled: false
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: "health,prometheus"
|
||||
endpoint:
|
||||
health:
|
||||
show-details: "never"
|
||||
|
||||
observability:
|
||||
tenant-id: "CHANGE_ME_TENANT_ID"
|
||||
organization-id: 1
|
||||
audit:
|
||||
max-attempts: 10
|
||||
integrity:
|
||||
current-key-id: "v1"
|
||||
current-key: "CHANGE_ME_RANDOM_SECRET_AT_LEAST_32_UTF8_BYTES"
|
||||
# Key rotation: keep retired keys here only while their audit records still exist.
|
||||
historical-keys: {}
|
||||
verification-enabled: true
|
||||
verification-delay-ms: 300000
|
||||
verification-initial-delay-ms: 60000
|
||||
verification-batch-size: 200
|
||||
@@ -15,7 +15,7 @@
|
||||
<artifactId>financial_system_backend</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>financial_system_backend</name>
|
||||
<description>统一费用支付平台 - 员工报销管理系统</description>
|
||||
<description>统一付款平台 - 企业付款申请与结果管理系统</description>
|
||||
|
||||
<properties>
|
||||
<java.version>8</java.version>
|
||||
|
||||
+7
-7
@@ -32,7 +32,7 @@ public class FeishuApprovalEventStateService {
|
||||
}
|
||||
// Global lock order: application first, then current mapping.
|
||||
ReimApplication app = applications.findByIdForUpdate(candidate.getApplicationId())
|
||||
.orElseThrow(() -> retryable("报销申请尚未就绪"));
|
||||
.orElseThrow(() -> retryable("付款申请尚未就绪"));
|
||||
IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(candidate.getApplicationId())
|
||||
.orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
|
||||
if (!Objects.equals(instanceCode, mapping.getFeishuInstanceCode())) {
|
||||
@@ -56,13 +56,13 @@ public class FeishuApprovalEventStateService {
|
||||
app.setApprovalStatus(normalized);
|
||||
if (ApprovalStatus.PENDING.name().equals(normalized)) {
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode("飞书审批");
|
||||
app.setCurrentApproverId(null); app.setApproveTime(null);
|
||||
app.setCurrentApproverId(null); app.setApproveTime(null); app.setApprovedAmount(null);
|
||||
} else {
|
||||
app.setCurrentApproverId(null); app.setCurrentApprovalNode(null);
|
||||
if (ApprovalStatus.APPROVED.name().equals(normalized)) {
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setApproveTime(LocalDateTime.now());
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setApproveTime(LocalDateTime.now()); app.setApprovedAmount(app.getTotalAmount());
|
||||
} else {
|
||||
app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setApproveTime(null);
|
||||
app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setApproveTime(null); app.setApprovedAmount(null);
|
||||
}
|
||||
}
|
||||
applications.save(app);
|
||||
@@ -76,7 +76,7 @@ public class FeishuApprovalEventStateService {
|
||||
Long approvalId;
|
||||
if (candidate != null) {
|
||||
applications.findByIdForUpdate(candidate.getApplicationId())
|
||||
.orElseThrow(() -> retryable("报销申请尚未就绪"));
|
||||
.orElseThrow(() -> retryable("付款申请尚未就绪"));
|
||||
IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(candidate.getApplicationId())
|
||||
.orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
|
||||
if (Objects.equals(instanceCode, mapping.getFeishuInstanceCode())) approvalId = mapping.getId();
|
||||
@@ -121,7 +121,7 @@ public class FeishuApprovalEventStateService {
|
||||
IntFeishuApprovalAttempt known = attempts.findByInstanceCode(instanceCode)
|
||||
.orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
|
||||
applications.findByIdForUpdate(known.getApplicationId())
|
||||
.orElseThrow(() -> retryable("报销申请尚未就绪"));
|
||||
.orElseThrow(() -> retryable("付款申请尚未就绪"));
|
||||
IntFeishuApprovalAttempt attempt = attempts.findByInstanceCodeForUpdate(instanceCode)
|
||||
.orElseThrow(() -> retryable("飞书历史审批映射尚未就绪"));
|
||||
if (attempt.getEventUpdatedAt() != null && eventTime.isBefore(attempt.getEventUpdatedAt())) return;
|
||||
@@ -135,7 +135,7 @@ public class FeishuApprovalEventStateService {
|
||||
IntFeishuApprovalAttempt known = attempts.findByInstanceCode(instanceCode)
|
||||
.orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
|
||||
applications.findByIdForUpdate(known.getApplicationId())
|
||||
.orElseThrow(() -> retryable("报销申请尚未就绪"));
|
||||
.orElseThrow(() -> retryable("付款申请尚未就绪"));
|
||||
return attempts.findByInstanceCodeForUpdate(instanceCode)
|
||||
.orElseThrow(() -> retryable("飞书历史审批映射尚未就绪")).getFeishuApprovalId();
|
||||
}
|
||||
|
||||
@@ -22,11 +22,11 @@ public final class FeishuApprovalFormBuilder {
|
||||
|
||||
public static String buildFormJson(ReimApplication app) {
|
||||
if (!StringUtils.hasText(app.getFeishuFormFingerprint()) || !StringUtils.hasText(app.getFeishuFormSchema()))
|
||||
throw new BusinessException("报销申请缺少已固定的飞书表单快照,禁止创建远程审批", 409);
|
||||
throw new BusinessException("付款申请缺少已固定的飞书表单快照,禁止创建远程审批", 409);
|
||||
if (!app.getFeishuFormFingerprint().equals(Sha256.hex(app.getFeishuFormSchema())))
|
||||
throw new BusinessException("报销申请的飞书表单快照校验失败", 409);
|
||||
throw new BusinessException("付款申请的飞书表单快照校验失败", 409);
|
||||
if (!StringUtils.hasText(app.getFeishuFormDisplayValues()))
|
||||
throw new BusinessException("报销申请缺少不可变的飞书展示值快照", 409);
|
||||
throw new BusinessException("付款申请缺少不可变的飞书展示值快照", 409);
|
||||
try {
|
||||
requireSize(app.getFeishuFormSchema(), "飞书表单快照过大");
|
||||
requireSize(app.getFeishuFormValues(), "飞书自定义表单值过大");
|
||||
@@ -46,7 +46,7 @@ public final class FeishuApprovalFormBuilder {
|
||||
requireSize(result, "飞书审批表单过大");
|
||||
return result;
|
||||
} catch (BusinessException e) { throw e; }
|
||||
catch (Exception e) { throw new BusinessException("报销申请的飞书表单快照无效", 409); }
|
||||
catch (Exception e) { throw new BusinessException("付款申请的飞书表单快照无效", 409); }
|
||||
}
|
||||
|
||||
/** Compatibility overload; mutable master data and line entities are deliberately ignored. */
|
||||
|
||||
@@ -210,7 +210,7 @@ public class FeishuApprovalService {
|
||||
throw new BusinessException("飞书审批创建参数无效", 400);
|
||||
String normalizedApprovalCode = intendedApprovalCode.trim();
|
||||
ReimApplication application = reimApplicationRepository.findById(applicationId)
|
||||
.orElseThrow(() -> new BusinessException("报销申请不存在,无法创建飞书审批", 400));
|
||||
.orElseThrow(() -> new BusinessException("付款申请不存在,无法创建飞书审批", 400));
|
||||
SysUser applicant = application.getApplicantId() == null ? null
|
||||
: sysUserRepository.findById(application.getApplicantId()).orElse(null);
|
||||
if (applicant == null || (!StringUtils.hasText(applicant.getFeishuUserId())
|
||||
@@ -380,7 +380,7 @@ public class FeishuApprovalService {
|
||||
// Terminal records are monotonic. This prevents a delayed PENDING
|
||||
// callback from reopening an already approved/rejected application.
|
||||
ReimApplication application = reimApplicationRepository.findByIdForUpdate(candidate.getApplicationId())
|
||||
.orElseThrow(() -> new BusinessException("未找到对应的报销申请"));
|
||||
.orElseThrow(() -> new BusinessException("未找到对应的付款申请"));
|
||||
IntFeishuApproval syncRecord = intFeishuApprovalRepository.findByApplicationIdForUpdate(candidate.getApplicationId())
|
||||
.filter(value -> Objects.equals(instanceCode, value.getFeishuInstanceCode()))
|
||||
.orElseThrow(() -> new BusinessException("审批实例已不是当前申请", 409));
|
||||
@@ -402,17 +402,20 @@ public class FeishuApprovalService {
|
||||
application.setCurrentApprovalNode("飞书审批");
|
||||
application.setCurrentApproverId(null);
|
||||
application.setApproveTime(null);
|
||||
application.setApprovedAmount(null);
|
||||
} else {
|
||||
application.setCurrentApproverId(null);
|
||||
application.setCurrentApprovalNode(null);
|
||||
if (ApprovalStatus.APPROVED.name().equals(normalizedStatus)) {
|
||||
application.setApplicationStatus(ApplicationStatus.SUBMITTED.name());
|
||||
application.setApproveTime(LocalDateTime.now());
|
||||
application.setApprovedAmount(application.getTotalAmount());
|
||||
} else {
|
||||
// Rejected/cancelled applications follow the existing local
|
||||
// returned-draft behavior and can be corrected and resubmitted.
|
||||
application.setApplicationStatus(ApplicationStatus.DRAFT.name());
|
||||
application.setApproveTime(null);
|
||||
application.setApprovedAmount(null);
|
||||
}
|
||||
}
|
||||
reimApplicationRepository.save(application);
|
||||
@@ -421,7 +424,7 @@ public class FeishuApprovalService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据报销单ID查询审批进度
|
||||
* 根据付款申请ID查询审批进度
|
||||
*/
|
||||
public List<FeishuApprovalResponse.TimelineNode> getApprovalTimelineByApplication(Long applicationId) {
|
||||
IntFeishuApproval syncRecord = intFeishuApprovalRepository
|
||||
|
||||
@@ -93,8 +93,8 @@ public class FeishuMessageService {
|
||||
private String buildApprovalCard(String applicationNo, String title,
|
||||
String applicantName, BigDecimal amount, String detailUrl) {
|
||||
return String.format("{\"config\":{\"wide_screen_mode\":true},"
|
||||
+ "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"📋 报销审批待办\"},\"template\":\"blue\"},"
|
||||
+ "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您有一笔报销申请需要审批:\\n**单号**:%s\\n**标题**:%s\\n**申请人**:%s\\n**金额**:¥%.2f\"}},"
|
||||
+ "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"📋 付款申请审批待办\"},\"template\":\"blue\"},"
|
||||
+ "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您有一笔付款申请需要审批:\\n**单号**:%s\\n**标题**:%s\\n**申请人**:%s\\n**申请付款金额**:¥%.2f\"}},"
|
||||
+ "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"去审批\"},\"type\":\"primary\",\"multi_url\":{\"url\":\"%s\",\"pc_url\":\"\"}}]}]}",
|
||||
applicationNo, title, applicantName, amount, detailUrl);
|
||||
}
|
||||
@@ -114,7 +114,7 @@ public class FeishuMessageService {
|
||||
|
||||
return String.format("{\"config\":{\"wide_screen_mode\":true},"
|
||||
+ "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"💰 付款结果通知\"},\"template\":\"green\"},"
|
||||
+ "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您的报销申请已处理:\\n**单号**:%s\\n**金额**:¥%.2f\\n**状态**:%s\"}},"
|
||||
+ "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您的付款申请已处理:\\n**单号**:%s\\n**申请付款金额**:¥%.2f\\n**状态**:%s\"}},"
|
||||
+ "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"查看详情\"},\"type\":\"default\",\"multi_url\":{\"url\":\"%s\",\"pc_url\":\"\"}}]}]}",
|
||||
applicationNo, amount, statusText, detailUrl);
|
||||
}
|
||||
|
||||
@@ -18,16 +18,16 @@ public class KingdeeSyncService {
|
||||
private final KingdeeClient kingdeeClient;
|
||||
|
||||
/**
|
||||
* 同步报销单到金蝶
|
||||
* 同步付款申请关联单据到金蝶
|
||||
*/
|
||||
public void syncExpenseReimbursement(ReimApplication application) {
|
||||
if (!kingdeeClient.isEnabled()) return;
|
||||
try {
|
||||
Map<String, Object> data = buildReimbursementData(application);
|
||||
Map<String, Object> result = kingdeeClient.save("FIN_EXPENSE_REIMBURSEMENT", data);
|
||||
log.info("金蝶同步报销单成功: applicationNo={}", application.getApplicationNo());
|
||||
log.info("金蝶同步付款申请成功: applicationNo={}", application.getApplicationNo());
|
||||
} catch (Exception e) {
|
||||
log.error("金蝶同步报销单失败: applicationNo={}", application.getApplicationNo(), e);
|
||||
log.error("金蝶同步付款申请失败: applicationNo={}", application.getApplicationNo(), e);
|
||||
throw new BusinessException("金蝶同步失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -48,13 +48,13 @@ public class KingdeeSyncService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询金蝶报销单状态
|
||||
* 查询金蝶关联业务单据状态
|
||||
*/
|
||||
public Map<String, Object> queryReimbursementStatus(String billNo) {
|
||||
try {
|
||||
return kingdeeClient.view("FIN_EXPENSE_REIMBURSEMENT", billNo);
|
||||
} catch (Exception e) {
|
||||
log.error("查询金蝶报销单状态失败: billNo={}", billNo, e);
|
||||
log.error("查询金蝶关联业务单据状态失败: billNo={}", billNo, e);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("error", "金蝶查询失败");
|
||||
return result;
|
||||
@@ -62,7 +62,7 @@ public class KingdeeSyncService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建报销单数据
|
||||
* 构建付款申请关联单据数据
|
||||
*/
|
||||
private Map<String, Object> buildReimbursementData(ReimApplication app) {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
|
||||
@@ -115,6 +115,7 @@ public class LocalDataInitializer implements CommandLineRunner {
|
||||
bank.setUserId(employee.getId());
|
||||
SysPayee payee = SysPayee.builder().tenantId(employee.getTenantId())
|
||||
.organizationId(employee.getOrganizationId()).payeeType("EMPLOYEE")
|
||||
.relationType("INTERNAL").countryRegion("中国")
|
||||
.displayName(employee.getRealName()).employeeUserId(employee.getId())
|
||||
.employeeOpenId(employee.getFeishuOpenId()).status("ACTIVE").build();
|
||||
payee = payees.save(payee);
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -52,9 +53,12 @@ public class CashierController {
|
||||
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) {
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
String resolvedIdempotencyKey = resolveIdempotencyKey(idempotencyKey, request.getIdempotencyKey());
|
||||
BigDecimal amount = resolveAmount(request);
|
||||
String method = resolveAlias(request.getPaymentMethod(), request.getActualPaymentMethod(), "付款方式");
|
||||
String reference = resolveAlias(request.getReferenceNo(), request.getBankTransactionNo(), "银行流水号");
|
||||
PaymentResultDto result = reimPaymentService.executePayment(request.getApplicationId(),
|
||||
request.getPaymentAmount(), userId, request.getPaymentMethod(), request.getReferenceNo(),
|
||||
request.getRemark(), resolvedIdempotencyKey);
|
||||
amount, userId, method, reference, requiredPaymentDate(request.getActualPaymentDate()),
|
||||
request.getPaymentReceipt(), request.getSource(), request.getRemark(), resolvedIdempotencyKey);
|
||||
return ResponseEntity.ok(ApiResponse.success(result));
|
||||
}
|
||||
|
||||
@@ -64,11 +68,14 @@ public class CashierController {
|
||||
@RequestBody CreatePaymentRequest request,
|
||||
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) {
|
||||
Long applicationId = request.getApplicationId();
|
||||
BigDecimal amount = request.getPaymentAmount();
|
||||
BigDecimal amount = resolveAmount(request);
|
||||
Long userId = AuditUtil.getCurrentUserId();
|
||||
String resolvedIdempotencyKey = resolveIdempotencyKey(idempotencyKey, request.getIdempotencyKey());
|
||||
String method = resolveAlias(request.getPaymentMethod(), request.getActualPaymentMethod(), "付款方式");
|
||||
String reference = resolveAlias(request.getReferenceNo(), request.getBankTransactionNo(), "银行流水号");
|
||||
PaymentResultDto result = reimPaymentService.processPartialPayment(applicationId, amount, userId,
|
||||
request.getPaymentMethod(), request.getReferenceNo(), request.getRemark(), resolvedIdempotencyKey);
|
||||
method, reference, requiredPaymentDate(request.getActualPaymentDate()), request.getPaymentReceipt(),
|
||||
request.getSource(), request.getRemark(), resolvedIdempotencyKey);
|
||||
return ResponseEntity.ok(ApiResponse.success(result));
|
||||
}
|
||||
|
||||
@@ -91,6 +98,15 @@ public class CashierController {
|
||||
request.getPaymentId(), AuditUtil.getCurrentUserId(), request.getRejectionCode())));
|
||||
}
|
||||
|
||||
@PatchMapping("/payments/{paymentId}/receipt")
|
||||
@PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.register')")
|
||||
public ResponseEntity<ApiResponse<PaymentResultDto>> attachPaymentReceipt(
|
||||
@PathVariable Long paymentId,
|
||||
@javax.validation.Valid @RequestBody PaymentReceiptRequest request) {
|
||||
return ResponseEntity.ok(ApiResponse.success(reimPaymentService.attachPaymentReceipt(
|
||||
paymentId, request.getPaymentReceipt(), AuditUtil.getCurrentUserId())));
|
||||
}
|
||||
|
||||
@GetMapping("/history")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
public ResponseEntity<ApiResponse<List<PaymentRecordDto>>> getPaymentHistory() {
|
||||
@@ -122,4 +138,28 @@ public class CashierController {
|
||||
if (normalized.length() > 100) throw new BadRequestException("幂等键长度不能超过100个字符");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private BigDecimal resolveAmount(CreatePaymentRequest request) {
|
||||
BigDecimal legacy = request.getPaymentAmount();
|
||||
BigDecimal actual = request.getActualPaymentAmount();
|
||||
if (legacy != null && actual != null && legacy.compareTo(actual) != 0) {
|
||||
throw new BadRequestException("付款金额与 actualPaymentAmount 不一致");
|
||||
}
|
||||
return actual != null ? actual : legacy;
|
||||
}
|
||||
|
||||
private String resolveAlias(String legacy, String current, String label) {
|
||||
String left = StringUtils.hasText(legacy) ? legacy.trim() : null;
|
||||
String right = StringUtils.hasText(current) ? current.trim() : null;
|
||||
if (left != null && right != null && !left.equals(right)) {
|
||||
throw new BadRequestException(label + "字段值不一致");
|
||||
}
|
||||
return right != null ? right : left;
|
||||
}
|
||||
|
||||
private LocalDate requiredPaymentDate(LocalDate value) {
|
||||
if (value == null) throw new BadRequestException("实际付款日期不能为空");
|
||||
if (value.isAfter(LocalDate.now())) throw new BadRequestException("实际付款日期不能晚于今天");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -364,7 +364,7 @@ public class FeishuAuthController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据报销单ID获取审批进度
|
||||
* 根据付款申请ID获取审批进度
|
||||
*/
|
||||
@GetMapping("/approval/application/{applicationId}")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.applications') || @permissionChecker.has(authentication, 'page.finance-receipt')")
|
||||
|
||||
@@ -24,18 +24,19 @@ public class MetadataController {
|
||||
private final PayeeAccountService payeeAccountService;
|
||||
|
||||
/**
|
||||
* 获取费用类型列表
|
||||
* 获取付款情形列表(保留旧接口路径兼容)
|
||||
*/
|
||||
@GetMapping("/expense-types")
|
||||
@GetMapping({"/payment-scenarios", "/expense-types"})
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.expense-types') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExpenseTypes() {
|
||||
List<Map<String,Object>> result = expenseTypeRepository
|
||||
.findByStatusIgnoreCaseOrderBySortOrderAscIdAsc("ACTIVE").stream().map(type -> {
|
||||
Map<String,Object> value = new LinkedHashMap<>();
|
||||
value.put("id", type.getId());
|
||||
value.put("code", type.getTypeCode());
|
||||
value.put("name", type.getTypeName());
|
||||
value.put("category", type.getCategory());
|
||||
value.put("scenarioCode", type.getScenarioCode());
|
||||
value.put("scenarioName", type.getScenarioName());
|
||||
value.put("scenarioGroup", type.getScenarioGroup());
|
||||
value.put("status", type.getStatus());
|
||||
value.put("description", null);
|
||||
return value;
|
||||
}).collect(Collectors.toList());
|
||||
@@ -43,7 +44,7 @@ public class MetadataController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取收款人列表
|
||||
* 获取收款方列表
|
||||
*/
|
||||
@GetMapping("/payees")
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')")
|
||||
|
||||
@@ -16,7 +16,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/reimbursements")
|
||||
@RequestMapping({"/api/v1/payment-applications", "/api/v1/reimbursements"})
|
||||
@RequiredArgsConstructor
|
||||
public class ReimApplicationController {
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ public class RoleController {
|
||||
ROLE_PROFILES.add(profile(1, "SUPER_ADMIN", "超级管理员", "历史兼容角色 - 全功能访问", "*"));
|
||||
ROLE_PROFILES.add(profile(2, "FINANCE", "财务人员", "财务人员 - 收单管理、付款登记、审批查看、基础数据",
|
||||
"reimbursement:view-all", "receipt:manage", "payment:register", "approval:view", "master-data:manage"));
|
||||
ROLE_PROFILES.add(profile(3, "EMPLOYEE", "员工", "普通员工 - 发起报销、查看个人报销进度",
|
||||
ROLE_PROFILES.add(profile(3, "EMPLOYEE", "员工", "普通员工 - 发起付款申请、查看个人申请进度",
|
||||
"reimbursement:create", "reimbursement:view-own"));
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ public class SourceDocumentController {
|
||||
s1.put("sourceDocType", "费用报销单");
|
||||
s1.put("sourceSystem", "金蝶 ERP");
|
||||
s1.put("sourceDate", "2026-07-28");
|
||||
s1.put("sourceStatus", "已同步");
|
||||
s1.put("syncStatus", "已同步");
|
||||
s1.put("title", "上海项目住宿费");
|
||||
s1.put("amount", new BigDecimal("4100.00"));
|
||||
s1.put("payee", "赵海峰");
|
||||
@@ -45,7 +45,7 @@ public class SourceDocumentController {
|
||||
s2.put("sourceDocType", "费用报销单");
|
||||
s2.put("sourceSystem", "金蝶 ERP");
|
||||
s2.put("sourceDate", "2026-08-01");
|
||||
s2.put("sourceStatus", "已同步");
|
||||
s2.put("syncStatus", "已同步");
|
||||
s2.put("title", "苏州园区客户拜访费用");
|
||||
s2.put("amount", new BigDecimal("2180.00"));
|
||||
s2.put("payee", "赵海峰");
|
||||
@@ -62,7 +62,7 @@ public class SourceDocumentController {
|
||||
s3.put("sourceDocType", "费用报销单");
|
||||
s3.put("sourceSystem", "金蝶 ERP");
|
||||
s3.put("sourceDate", "2026-07-31");
|
||||
s3.put("sourceStatus", "已同步");
|
||||
s3.put("syncStatus", "已同步");
|
||||
s3.put("title", "七月云资源差旅补贴");
|
||||
s3.put("amount", new BigDecimal("3200.00"));
|
||||
s3.put("payee", "王忠辉");
|
||||
@@ -79,7 +79,7 @@ public class SourceDocumentController {
|
||||
s4.put("sourceDocType", "费用报销单");
|
||||
s4.put("sourceSystem", "金蝶 ERP");
|
||||
s4.put("sourceDate", "2026-08-09");
|
||||
s4.put("sourceStatus", "已同步");
|
||||
s4.put("syncStatus", "已同步");
|
||||
s4.put("title", "八月客户拜访交通费");
|
||||
s4.put("amount", new BigDecimal("1260.00"));
|
||||
s4.put("payee", "李志豪");
|
||||
@@ -96,7 +96,7 @@ public class SourceDocumentController {
|
||||
s5.put("sourceDocType", "费用报销单");
|
||||
s5.put("sourceSystem", "金蝶 ERP");
|
||||
s5.put("sourceDate", "2026-07-26");
|
||||
s5.put("sourceStatus", "已同步");
|
||||
s5.put("syncStatus", "已同步");
|
||||
s5.put("title", "上海项目住宿费");
|
||||
s5.put("amount", new BigDecimal("4100.00"));
|
||||
s5.put("payee", "赵海峰");
|
||||
@@ -113,7 +113,7 @@ public class SourceDocumentController {
|
||||
s6.put("sourceDocType", "费用报销单");
|
||||
s6.put("sourceSystem", "金蝶 ERP");
|
||||
s6.put("sourceDate", "2026-07-28");
|
||||
s6.put("sourceStatus", "已同步");
|
||||
s6.put("syncStatus", "已同步");
|
||||
s6.put("title", "上海客户现场技术交流差旅");
|
||||
s6.put("amount", new BigDecimal("3286.50"));
|
||||
s6.put("payee", "李志豪");
|
||||
@@ -132,7 +132,7 @@ public class SourceDocumentController {
|
||||
@PreAuthorize("@permissionChecker.has(authentication, 'page.source-documents')")
|
||||
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listSources(
|
||||
@RequestParam(required = false) String sourceSystem,
|
||||
@RequestParam(required = false) String sourceStatus) {
|
||||
@RequestParam(required = false) String syncStatus) {
|
||||
try {
|
||||
List<Map<String, Object>> result = MOCK_SOURCES.stream()
|
||||
.map(this::safeSource)
|
||||
@@ -141,8 +141,8 @@ public class SourceDocumentController {
|
||||
if (sourceSystem != null && !sourceSystem.isEmpty()) {
|
||||
result.removeIf(s -> !sourceSystem.equals(s.get("sourceSystem")));
|
||||
}
|
||||
if (sourceStatus != null && !sourceStatus.isEmpty()) {
|
||||
result.removeIf(s -> !sourceStatus.equals(s.get("sourceStatus")));
|
||||
if (syncStatus != null && !syncStatus.isEmpty()) {
|
||||
result.removeIf(s -> !syncStatus.equals(s.get("syncStatus")));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(result));
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
@@ -9,13 +11,34 @@ import java.util.Map;
|
||||
@Data
|
||||
public class CreateApplicationRequest {
|
||||
private String title;
|
||||
private Long expenseTypeId;
|
||||
private String category;
|
||||
private BigDecimal totalAmount;
|
||||
@JsonAlias("expenseTypeId")
|
||||
private Long paymentScenarioId;
|
||||
private String paymentScenario;
|
||||
@JsonAlias("category")
|
||||
private String expenseItemCategory;
|
||||
@JsonAlias("totalAmount")
|
||||
private BigDecimal requestedAmount;
|
||||
private String payerEntityName;
|
||||
private String costCenterName;
|
||||
private String currencyCode;
|
||||
private String paymentReason;
|
||||
private LocalDate plannedPaymentDate;
|
||||
private Long linkedTravelApplicationId;
|
||||
private String description;
|
||||
private String payeeName;
|
||||
private Long payeeBankId;
|
||||
private List<ExpenseItemDto> items;
|
||||
@JsonAlias("items")
|
||||
private List<ExpenseItemDto> expenseItems;
|
||||
private String formFingerprint;
|
||||
private Map<String, Object> formValues;
|
||||
|
||||
/** Internal compatibility accessors; JSON is canonical-only. */
|
||||
@JsonIgnore public Long getExpenseTypeId() { return paymentScenarioId; }
|
||||
@JsonIgnore public void setExpenseTypeId(Long value) { paymentScenarioId = value; }
|
||||
@JsonIgnore public String getCategory() { return expenseItemCategory; }
|
||||
@JsonIgnore public void setCategory(String value) { expenseItemCategory = value; }
|
||||
@JsonIgnore public BigDecimal getTotalAmount() { return requestedAmount; }
|
||||
@JsonIgnore public void setTotalAmount(BigDecimal value) { requestedAmount = value; }
|
||||
@JsonIgnore public List<ExpenseItemDto> getItems() { return expenseItems; }
|
||||
@JsonIgnore public void setItems(List<ExpenseItemDto> value) { expenseItems = value; }
|
||||
}
|
||||
@@ -1,16 +1,34 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
public class CreatePaymentRequest {
|
||||
private Long applicationId;
|
||||
private BigDecimal paymentAmount;
|
||||
private String paymentMethod;
|
||||
@JsonAlias("paymentAmount")
|
||||
private BigDecimal actualPaymentAmount;
|
||||
@JsonAlias("paymentMethod")
|
||||
private String actualPaymentMethod;
|
||||
private String bankAccountNo;
|
||||
private String referenceNo;
|
||||
@JsonAlias("referenceNo")
|
||||
private String bankTransactionNo;
|
||||
private LocalDate actualPaymentDate;
|
||||
/** Persistent reference to a payment receipt or external evidence object. */
|
||||
private String paymentReceipt;
|
||||
/** MANUAL or EXTERNAL_SYSTEM. */
|
||||
private String source;
|
||||
/** Optional body fallback; the HTTP Idempotency-Key header takes precedence. */
|
||||
private String idempotencyKey;
|
||||
private String remark;
|
||||
|
||||
@JsonIgnore public BigDecimal getPaymentAmount() { return actualPaymentAmount; }
|
||||
@JsonIgnore public void setPaymentAmount(BigDecimal value) { actualPaymentAmount = value; }
|
||||
@JsonIgnore public String getPaymentMethod() { return actualPaymentMethod; }
|
||||
@JsonIgnore public void setPaymentMethod(String value) { actualPaymentMethod = value; }
|
||||
@JsonIgnore public String getReferenceNo() { return bankTransactionNo; }
|
||||
@JsonIgnore public void setReferenceNo(String value) { bankTransactionNo = value; }
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -17,7 +19,8 @@ public class ExpenseItemDto {
|
||||
private Long id;
|
||||
private Integer seqNo;
|
||||
private LocalDate expenseDate;
|
||||
private String category;
|
||||
@JsonAlias("category")
|
||||
private String expenseItemName;
|
||||
private String description;
|
||||
private BigDecimal amount;
|
||||
@Builder.Default
|
||||
@@ -25,4 +28,7 @@ public class ExpenseItemDto {
|
||||
/** Safe display metadata for attachments claimed by this expense row. */
|
||||
@Builder.Default
|
||||
private List<AttachmentDto> attachments = new ArrayList<>();
|
||||
|
||||
@JsonIgnore public String getCategory() { return expenseItemName; }
|
||||
@JsonIgnore public void setCategory(String value) { expenseItemName = value; }
|
||||
}
|
||||
@@ -11,8 +11,13 @@ import java.time.LocalDateTime;
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class PayeeSubjectDto {
|
||||
Long id;
|
||||
String payeeCode;
|
||||
String payeeType;
|
||||
String displayName;
|
||||
String relationType;
|
||||
String countryRegion;
|
||||
String identityType;
|
||||
Boolean identityValueMaintained;
|
||||
String employeeOpenId;
|
||||
String identityNumber;
|
||||
String supplierCreditCode;
|
||||
|
||||
@@ -10,10 +10,22 @@ import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
public class PayeeSubjectRequest {
|
||||
@NotBlank(message = "付款对象类型不能为空")
|
||||
@Pattern(regexp = "(?i)EMPLOYEE|SUPPLIER", message = "付款对象类型必须为EMPLOYEE或SUPPLIER")
|
||||
@NotBlank(message = "收款方类型不能为空")
|
||||
@Pattern(regexp = "(?i)EMPLOYEE|SUPPLIER|GOVERNMENT", message = "收款方类型必须为EMPLOYEE、SUPPLIER或GOVERNMENT")
|
||||
private String payeeType;
|
||||
|
||||
@Pattern(regexp = "(?i)INTERNAL|EXTERNAL", message = "内外部属性必须为INTERNAL或EXTERNAL")
|
||||
private String relationType;
|
||||
|
||||
@Size(max = 100, message = "国家或地区不能超过100个字符")
|
||||
private String countryRegion;
|
||||
|
||||
@Size(max = 50, message = "身份标识类型不能超过50个字符")
|
||||
private String identityType;
|
||||
|
||||
@Size(max = 100, message = "身份唯一标识不能超过100个字符")
|
||||
private String identityValue;
|
||||
|
||||
private String employeeOpenId;
|
||||
|
||||
@Size(max = 18, message = "身份证号不能超过18个字符")
|
||||
@@ -22,7 +34,7 @@ public class PayeeSubjectRequest {
|
||||
@Valid
|
||||
private PayeeInitialAccountRequest initialAccount;
|
||||
|
||||
@Size(max = 200, message = "付款对象名称不能超过200个字符")
|
||||
@Size(max = 200, message = "收款方名称不能超过200个字符")
|
||||
private String displayName;
|
||||
|
||||
@Size(max = 18, message = "统一社会信用代码不能超过18个字符")
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@@ -19,8 +21,15 @@ public class PaymentDetailDto {
|
||||
private String title;
|
||||
private String payeeName;
|
||||
private String departmentName;
|
||||
private BigDecimal totalAmount;
|
||||
private String payerEntityName;
|
||||
private String costCenterName;
|
||||
private String currencyCode;
|
||||
private String paymentReason;
|
||||
private LocalDate plannedPaymentDate;
|
||||
private BigDecimal requestedAmount;
|
||||
private BigDecimal approvedAmount;
|
||||
private BigDecimal paidAmount;
|
||||
private BigDecimal actualPaymentAmount;
|
||||
private BigDecimal remainingAmount;
|
||||
private String paymentStatus;
|
||||
private String bankName;
|
||||
@@ -31,4 +40,7 @@ public class PaymentDetailDto {
|
||||
private List<String> availableActions;
|
||||
private Boolean canVerify;
|
||||
private Boolean canReject;
|
||||
|
||||
@JsonIgnore public BigDecimal getTotalAmount() { return requestedAmount; }
|
||||
@JsonIgnore public void setTotalAmount(BigDecimal value) { requestedAmount = value; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
public class PaymentReceiptRequest {
|
||||
@NotBlank(message = "付款回单引用不能为空")
|
||||
@Size(max = 500, message = "付款回单引用长度不能超过500个字符")
|
||||
private String paymentReceipt;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -18,17 +20,31 @@ public class PaymentRecordDto {
|
||||
private Long id;
|
||||
private Long applicationId;
|
||||
private String paymentNo;
|
||||
private BigDecimal paymentAmount;
|
||||
private BigDecimal totalAmount;
|
||||
private BigDecimal actualPaymentAmount;
|
||||
private BigDecimal approvedAmount;
|
||||
private BigDecimal paidAmount;
|
||||
private BigDecimal remainingAmount;
|
||||
private String paymentMethod;
|
||||
private String referenceNo;
|
||||
private String actualPaymentMethod;
|
||||
private String bankTransactionNo;
|
||||
private LocalDate actualPaymentDate;
|
||||
private String paymentReceipt;
|
||||
private String source;
|
||||
private String paymentStatus;
|
||||
private String operatorName;
|
||||
private LocalDateTime paymentTime;
|
||||
private LocalDateTime resultRecordedAt;
|
||||
private String remark;
|
||||
private List<String> availableActions;
|
||||
private Boolean canVerify;
|
||||
private Boolean canReject;
|
||||
|
||||
@JsonIgnore public BigDecimal getPaymentAmount() { return actualPaymentAmount; }
|
||||
@JsonIgnore public void setPaymentAmount(BigDecimal value) { actualPaymentAmount = value; }
|
||||
@JsonIgnore public BigDecimal getTotalAmount() { return approvedAmount; }
|
||||
@JsonIgnore public void setTotalAmount(BigDecimal value) { approvedAmount = value; }
|
||||
@JsonIgnore public String getPaymentMethod() { return actualPaymentMethod; }
|
||||
@JsonIgnore public void setPaymentMethod(String value) { actualPaymentMethod = value; }
|
||||
@JsonIgnore public String getReferenceNo() { return bankTransactionNo; }
|
||||
@JsonIgnore public void setReferenceNo(String value) { bankTransactionNo = value; }
|
||||
@JsonIgnore public LocalDateTime getPaymentTime() { return resultRecordedAt; }
|
||||
@JsonIgnore public void setPaymentTime(LocalDateTime value) { resultRecordedAt = value; }
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@@ -12,7 +13,12 @@ import java.math.BigDecimal;
|
||||
@AllArgsConstructor
|
||||
public class PaymentResultDto {
|
||||
private String paymentNo;
|
||||
private BigDecimal amount;
|
||||
private BigDecimal actualPaymentAmount;
|
||||
private LocalDate actualPaymentDate;
|
||||
private String actualPaymentMethod;
|
||||
private String bankTransactionNo;
|
||||
private String paymentReceipt;
|
||||
private String source;
|
||||
private String paymentStatus;
|
||||
private String message;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.finance.system.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -21,12 +23,19 @@ public class PaymentTaskDto {
|
||||
private String title;
|
||||
private String payeeName;
|
||||
private String departmentName;
|
||||
private String expenseTypeName;
|
||||
private BigDecimal totalAmount;
|
||||
private String paymentScenario;
|
||||
private String payerEntityName;
|
||||
private String costCenterName;
|
||||
private String currencyCode;
|
||||
private String paymentReason;
|
||||
private LocalDate plannedPaymentDate;
|
||||
private BigDecimal requestedAmount;
|
||||
private BigDecimal approvedAmount;
|
||||
private BigDecimal paidAmount;
|
||||
private BigDecimal actualPaymentAmount;
|
||||
private BigDecimal remainingAmount;
|
||||
private String paymentStatus;
|
||||
private String receiptStatus;
|
||||
private String financeCheckStatus;
|
||||
private String approvalStatus;
|
||||
private String bankName;
|
||||
private String bankAccountMask;
|
||||
@@ -35,4 +44,11 @@ public class PaymentTaskDto {
|
||||
private List<String> availableActions;
|
||||
private Boolean canVerify;
|
||||
private Boolean canReject;
|
||||
|
||||
@JsonIgnore public String getExpenseTypeName() { return paymentScenario; }
|
||||
@JsonIgnore public void setExpenseTypeName(String value) { paymentScenario = value; }
|
||||
@JsonIgnore public BigDecimal getTotalAmount() { return requestedAmount; }
|
||||
@JsonIgnore public void setTotalAmount(BigDecimal value) { requestedAmount = value; }
|
||||
@JsonIgnore public String getReceiptStatus() { return financeCheckStatus; }
|
||||
@JsonIgnore public void setReceiptStatus(String value) { financeCheckStatus = value; }
|
||||
}
|
||||
@@ -26,24 +26,34 @@ public class ReimApplicationDetail {
|
||||
private String applicantEmployeeNo;
|
||||
private Long departmentId;
|
||||
private String departmentName;
|
||||
private Long expenseTypeId;
|
||||
private String expenseTypeName;
|
||||
private String category;
|
||||
private BigDecimal totalAmount;
|
||||
private Long paymentScenarioId;
|
||||
private String paymentScenario;
|
||||
private String expenseItemCategory;
|
||||
private BigDecimal requestedAmount;
|
||||
private BigDecimal approvedAmount;
|
||||
private BigDecimal actualPaymentAmount;
|
||||
private BigDecimal paidAmount;
|
||||
private BigDecimal remainingAmount;
|
||||
private String payerEntityName;
|
||||
private String costCenterName;
|
||||
private String currencyCode;
|
||||
private String paymentReason;
|
||||
private LocalDate plannedPaymentDate;
|
||||
private Long linkedTravelApplicationId;
|
||||
private String description;
|
||||
private String applicationStatus;
|
||||
private String approvalStatus;
|
||||
private String currentApprovalNode;
|
||||
private Long currentApproverId;
|
||||
private String currentApproverName;
|
||||
private String receiptStatus;
|
||||
private String financeCheckStatus;
|
||||
private String paymentStatus;
|
||||
private String budgetStatus;
|
||||
private String sourceDocNo;
|
||||
private String sourceDocType;
|
||||
private String sourceSystem;
|
||||
private LocalDate sourceDocDate;
|
||||
private String sourceStatus;
|
||||
private String syncStatus;
|
||||
private String payeeName;
|
||||
@JsonIgnore
|
||||
private Long payeeBankId;
|
||||
|
||||
@@ -6,6 +6,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@@ -19,17 +20,28 @@ public class ReimApplicationSummary {
|
||||
private String title;
|
||||
private String applicantName;
|
||||
private String departmentName;
|
||||
private String expenseTypeName;
|
||||
private String category;
|
||||
private BigDecimal totalAmount;
|
||||
private Long paymentScenarioId;
|
||||
private String paymentScenario;
|
||||
private String expenseItemCategory;
|
||||
private BigDecimal requestedAmount;
|
||||
private BigDecimal approvedAmount;
|
||||
private BigDecimal actualPaymentAmount;
|
||||
private BigDecimal paidAmount;
|
||||
private BigDecimal remainingAmount;
|
||||
private String payerEntityName;
|
||||
private String costCenterName;
|
||||
private String currencyCode;
|
||||
private String paymentReason;
|
||||
private LocalDate plannedPaymentDate;
|
||||
private Long linkedTravelApplicationId;
|
||||
private String applicationStatus;
|
||||
private String approvalStatus;
|
||||
private String currentApprovalNode;
|
||||
private String receiptStatus;
|
||||
private String financeCheckStatus;
|
||||
private String paymentStatus;
|
||||
private String budgetStatus;
|
||||
private String sourceDocNo;
|
||||
private String sourceStatus;
|
||||
private String syncStatus;
|
||||
private String returnReason;
|
||||
private LocalDateTime submitTime;
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@@ -28,4 +28,5 @@ public class TravelApplicationDto {
|
||||
String status;
|
||||
String approvalSystem;
|
||||
LocalDateTime syncedAt;
|
||||
long linkedPaymentApplicationCount;
|
||||
}
|
||||
@@ -12,7 +12,12 @@ import java.util.List;
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchDto {
|
||||
private UserProfile user;
|
||||
private List<ReimApplicationSummary> reimbursements;
|
||||
/** 统一付款业务对象。 */
|
||||
private List<ReimApplicationSummary> paymentApplications;
|
||||
private List<PaymentRecordDto> payments;
|
||||
private DashboardStats stats;
|
||||
/** 是否启用独立财务核对门禁;原型口径默认关闭。 */
|
||||
private Boolean financeCheckEnabled;
|
||||
/** 是否启用付款结果独立复核;原型口径默认关闭。 */
|
||||
private Boolean independentPaymentReviewEnabled;
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 飞书审批同步表
|
||||
* 记录审批实例与报销单的关联关系
|
||||
* 记录审批实例与付款申请的关联关系
|
||||
*/
|
||||
@Data
|
||||
@Entity
|
||||
@@ -22,7 +22,7 @@ public class IntFeishuApproval {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
/** 关联报销申请ID */
|
||||
/** 关联付款申请ID */
|
||||
@Column(name = "application_id", nullable = false)
|
||||
private Long applicationId;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import javax.persistence.*;
|
||||
import org.hibernate.annotations.Where;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -17,7 +18,7 @@ import java.util.List;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_application")
|
||||
@Table(name = "payment_application")
|
||||
@Where(clause = "deleted = false")
|
||||
public class ReimApplication {
|
||||
|
||||
@@ -40,14 +41,35 @@ public class ReimApplication {
|
||||
@Column(name = "department_id", nullable = false)
|
||||
private Long departmentId;
|
||||
|
||||
@Column(name = "expense_type_id", nullable = false)
|
||||
private Long expenseTypeId;
|
||||
@Column(name = "payment_scenario_id", nullable = false)
|
||||
private Long paymentScenarioId;
|
||||
|
||||
@Column(length = 100)
|
||||
private String category;
|
||||
@Column(name = "expense_item_category", length = 100)
|
||||
private String expenseItemCategory;
|
||||
|
||||
@Column(name = "total_amount", nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal totalAmount;
|
||||
@Column(name = "payer_entity_name", length = 200)
|
||||
private String payerEntityName;
|
||||
|
||||
@Column(name = "cost_center_name", length = 200)
|
||||
private String costCenterName;
|
||||
|
||||
@Column(name = "currency_code", length = 3, nullable = false)
|
||||
private String currencyCode;
|
||||
|
||||
@Column(name = "payment_reason", length = 1000)
|
||||
private String paymentReason;
|
||||
|
||||
@Column(name = "planned_payment_date")
|
||||
private LocalDate plannedPaymentDate;
|
||||
|
||||
@Column(name = "linked_travel_application_id")
|
||||
private Long linkedTravelApplicationId;
|
||||
|
||||
@Column(name = "requested_amount", nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal requestedAmount;
|
||||
|
||||
@Column(name = "approved_amount", precision = 18, scale = 2)
|
||||
private BigDecimal approvedAmount;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String description;
|
||||
@@ -64,14 +86,14 @@ public class ReimApplication {
|
||||
@Column(name = "current_approver_id")
|
||||
private Long currentApproverId;
|
||||
|
||||
@Column(name = "receipt_status", length = 30)
|
||||
private String receiptStatus;
|
||||
@Column(name = "finance_check_status", length = 30)
|
||||
private String financeCheckStatus;
|
||||
|
||||
@Column(name = "received_by")
|
||||
private Long receivedBy;
|
||||
@Column(name = "finance_checked_by")
|
||||
private Long financeCheckedBy;
|
||||
|
||||
@Column(name = "received_at")
|
||||
private LocalDateTime receivedAt;
|
||||
@Column(name = "finance_checked_at")
|
||||
private LocalDateTime financeCheckedAt;
|
||||
|
||||
@Column(name = "payment_status", length = 30)
|
||||
private String paymentStatus;
|
||||
@@ -91,8 +113,8 @@ public class ReimApplication {
|
||||
@Column(name = "source_doc_date")
|
||||
private LocalDate sourceDocDate;
|
||||
|
||||
@Column(name = "source_status", length = 30)
|
||||
private String sourceStatus;
|
||||
@Column(name = "sync_status", length = 30)
|
||||
private String syncStatus;
|
||||
|
||||
@Column(name = "feishu_form_fingerprint", length = 64)
|
||||
private String feishuFormFingerprint;
|
||||
@@ -144,4 +166,17 @@ public class ReimApplication {
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@JsonIgnore public Long getExpenseTypeId() { return paymentScenarioId; }
|
||||
@JsonIgnore public void setExpenseTypeId(Long value) { paymentScenarioId = value; }
|
||||
@JsonIgnore public String getCategory() { return expenseItemCategory; }
|
||||
@JsonIgnore public void setCategory(String value) { expenseItemCategory = value; }
|
||||
@JsonIgnore public BigDecimal getTotalAmount() { return requestedAmount; }
|
||||
@JsonIgnore public void setTotalAmount(BigDecimal value) { requestedAmount = value; }
|
||||
@JsonIgnore public String getReceiptStatus() { return financeCheckStatus; }
|
||||
@JsonIgnore public void setReceiptStatus(String value) { financeCheckStatus = value; }
|
||||
@JsonIgnore public Long getReceivedBy() { return financeCheckedBy; }
|
||||
@JsonIgnore public void setReceivedBy(Long value) { financeCheckedBy = value; }
|
||||
@JsonIgnore public LocalDateTime getReceivedAt() { return financeCheckedAt; }
|
||||
@JsonIgnore public void setReceivedAt(LocalDateTime value) { financeCheckedAt = value; }
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import java.time.LocalDateTime;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_approval_record")
|
||||
@Table(name = "payment_approval_record")
|
||||
public class ReimApprovalRecord {
|
||||
|
||||
@Id
|
||||
|
||||
@@ -14,7 +14,7 @@ import java.time.ZoneId;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_attachment")
|
||||
@Table(name = "payment_attachment")
|
||||
public class ReimAttachment {
|
||||
private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import javax.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -15,7 +16,7 @@ import java.time.LocalDateTime;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_expense_item")
|
||||
@Table(name = "payment_expense_item")
|
||||
public class ReimExpenseItem {
|
||||
|
||||
@Id
|
||||
@@ -31,8 +32,8 @@ public class ReimExpenseItem {
|
||||
@Column(name = "expense_date", nullable = false)
|
||||
private LocalDate expenseDate;
|
||||
|
||||
@Column(length = 100, nullable = false)
|
||||
private String category;
|
||||
@Column(name = "expense_item_name", length = 100, nullable = false)
|
||||
private String expenseItemName;
|
||||
|
||||
@Column(length = 500)
|
||||
private String description;
|
||||
@@ -53,4 +54,7 @@ public class ReimExpenseItem {
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@JsonIgnore public String getCategory() { return expenseItemName; }
|
||||
@JsonIgnore public void setCategory(String value) { expenseItemName = value; }
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import java.time.LocalDateTime;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_invoice")
|
||||
@Table(name = "payment_invoice")
|
||||
public class ReimInvoice {
|
||||
|
||||
@Id
|
||||
|
||||
@@ -9,6 +9,7 @@ import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@@ -16,7 +17,7 @@ import java.time.LocalDateTime;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_payment")
|
||||
@Table(name = "payment_result")
|
||||
public class ReimPayment {
|
||||
|
||||
@Id
|
||||
@@ -38,11 +39,11 @@ public class ReimPayment {
|
||||
@Column(name = "payee_bank_id")
|
||||
private Long payeeBankId;
|
||||
|
||||
@Column(name = "total_amount", nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal totalAmount;
|
||||
@Column(name = "approved_amount", nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal approvedAmount;
|
||||
|
||||
@Column(name = "payment_amount", nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal paymentAmount;
|
||||
@Column(name = "actual_payment_amount", nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal actualPaymentAmount;
|
||||
|
||||
@Column(name = "paid_amount", precision = 18, scale = 2)
|
||||
private BigDecimal paidAmount;
|
||||
@@ -50,8 +51,8 @@ public class ReimPayment {
|
||||
@Column(name = "remaining_amount", precision = 18, scale = 2)
|
||||
private BigDecimal remainingAmount;
|
||||
|
||||
@Column(name = "payment_method", length = 50)
|
||||
private String paymentMethod;
|
||||
@Column(name = "actual_payment_method", length = 50)
|
||||
private String actualPaymentMethod;
|
||||
|
||||
@Column(name = "bank_account_no", length = 100)
|
||||
@JsonIgnore
|
||||
@@ -61,8 +62,17 @@ public class ReimPayment {
|
||||
@Column(name = "bank_account_name", length = 200)
|
||||
private String bankAccountName;
|
||||
|
||||
@Column(name = "reference_no", length = 100)
|
||||
private String referenceNo;
|
||||
@Column(name = "bank_transaction_no", length = 100)
|
||||
private String bankTransactionNo;
|
||||
|
||||
@Column(name = "actual_payment_date")
|
||||
private LocalDate actualPaymentDate;
|
||||
|
||||
@Column(name = "payment_receipt", length = 500)
|
||||
private String paymentReceipt;
|
||||
|
||||
@Column(name = "result_source", length = 30)
|
||||
private String resultSource;
|
||||
|
||||
@Column(name = "operator_id", nullable = false)
|
||||
private Long operatorId;
|
||||
@@ -76,8 +86,8 @@ public class ReimPayment {
|
||||
@Column(name = "payment_status", length = 30)
|
||||
private String paymentStatus;
|
||||
|
||||
@Column(name = "payment_time")
|
||||
private LocalDateTime paymentTime;
|
||||
@Column(name = "result_recorded_at")
|
||||
private LocalDateTime resultRecordedAt;
|
||||
|
||||
@Column(name = "verified_at")
|
||||
private LocalDateTime verifiedAt;
|
||||
@@ -117,4 +127,15 @@ public class ReimPayment {
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@JsonIgnore public BigDecimal getTotalAmount() { return approvedAmount; }
|
||||
@JsonIgnore public void setTotalAmount(BigDecimal value) { approvedAmount = value; }
|
||||
@JsonIgnore public BigDecimal getPaymentAmount() { return actualPaymentAmount; }
|
||||
@JsonIgnore public void setPaymentAmount(BigDecimal value) { actualPaymentAmount = value; }
|
||||
@JsonIgnore public String getPaymentMethod() { return actualPaymentMethod; }
|
||||
@JsonIgnore public void setPaymentMethod(String value) { actualPaymentMethod = value; }
|
||||
@JsonIgnore public String getReferenceNo() { return bankTransactionNo; }
|
||||
@JsonIgnore public void setReferenceNo(String value) { bankTransactionNo = value; }
|
||||
@JsonIgnore public LocalDateTime getPaymentTime() { return resultRecordedAt; }
|
||||
@JsonIgnore public void setPaymentTime(LocalDateTime value) { resultRecordedAt = value; }
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import java.time.LocalDateTime;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "reim_payment_installment")
|
||||
@Table(name = "payment_installment")
|
||||
public class ReimPaymentInstallment {
|
||||
|
||||
@Id
|
||||
@@ -30,10 +30,10 @@ public class ReimPaymentInstallment {
|
||||
@Column(nullable = false, precision = 18, scale = 2)
|
||||
private BigDecimal amount;
|
||||
|
||||
@Column(name = "payment_method", length = 50)
|
||||
@Column(name = "actual_payment_method", length = 50)
|
||||
private String paymentMethod;
|
||||
|
||||
@Column(name = "reference_no", length = 100)
|
||||
@Column(name = "bank_transaction_no", length = 100)
|
||||
private String referenceNo;
|
||||
|
||||
@Column(length = 30)
|
||||
|
||||
@@ -5,7 +5,7 @@ import javax.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data @Builder @NoArgsConstructor @AllArgsConstructor
|
||||
@Entity @Table(name = "reim_route_preview_token")
|
||||
@Entity @Table(name = "payment_route_preview_token")
|
||||
public class ReimRoutePreviewToken {
|
||||
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
|
||||
@Column(name = "token_hash", nullable = false, unique = true, length = 64) private String tokenHash;
|
||||
|
||||
@@ -49,7 +49,7 @@ public class SysBankAccount {
|
||||
@Column(name = "account_no_mask", length = 50)
|
||||
private String accountNoMask;
|
||||
|
||||
@Column(name = "account_fingerprint", length = 64)
|
||||
@Column(name = "account_fingerprint", length = 64, columnDefinition = "CHAR(64)")
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
private String accountFingerprint;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.finance.system.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import javax.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -13,24 +14,24 @@ import java.time.LocalDateTime;
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "sys_expense_type")
|
||||
@Table(name = "sys_payment_scenario")
|
||||
public class SysExpenseType {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "type_code", length = 50, nullable = false, unique = true)
|
||||
private String typeCode;
|
||||
@Column(name = "scenario_code", length = 50, nullable = false, unique = true)
|
||||
private String scenarioCode;
|
||||
|
||||
@Column(name = "type_name", length = 200, nullable = false)
|
||||
private String typeName;
|
||||
@Column(name = "scenario_name", length = 200, nullable = false)
|
||||
private String scenarioName;
|
||||
|
||||
@Column(length = 50, nullable = false)
|
||||
private String category;
|
||||
@Column(name = "scenario_group", length = 50, nullable = false)
|
||||
private String scenarioGroup;
|
||||
|
||||
@Column(name = "parent_id")
|
||||
private Long parentId;
|
||||
@Column(name = "parent_scenario_id")
|
||||
private Long parentScenarioId;
|
||||
|
||||
@Column(name = "sort_order")
|
||||
private Integer sortOrder;
|
||||
@@ -54,4 +55,13 @@ public class SysExpenseType {
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@JsonIgnore public String getTypeCode() { return scenarioCode; }
|
||||
@JsonIgnore public void setTypeCode(String value) { scenarioCode = value; }
|
||||
@JsonIgnore public String getTypeName() { return scenarioName; }
|
||||
@JsonIgnore public void setTypeName(String value) { scenarioName = value; }
|
||||
@JsonIgnore public String getCategory() { return scenarioGroup; }
|
||||
@JsonIgnore public void setCategory(String value) { scenarioGroup = value; }
|
||||
@JsonIgnore public Long getParentId() { return parentScenarioId; }
|
||||
@JsonIgnore public void setParentId(Long value) { parentScenarioId = value; }
|
||||
}
|
||||
@@ -32,9 +32,24 @@ public class SysPayee {
|
||||
@Column(name = "organization_id", nullable = false)
|
||||
private Long organizationId;
|
||||
|
||||
@Column(name = "payee_code", length = 50)
|
||||
private String payeeCode;
|
||||
|
||||
@Column(name = "payee_type", nullable = false, length = 20)
|
||||
private String payeeType;
|
||||
|
||||
@Column(name = "relation_type", nullable = false, length = 20)
|
||||
private String relationType;
|
||||
|
||||
@Column(name = "country_region", nullable = false, length = 100)
|
||||
private String countryRegion;
|
||||
|
||||
@Column(name = "identity_type", length = 50)
|
||||
private String identityType;
|
||||
|
||||
@Column(name = "identity_value", length = 100)
|
||||
private String identityValue;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 200)
|
||||
private String displayName;
|
||||
|
||||
|
||||
@@ -7,13 +7,24 @@ import java.math.BigDecimal;
|
||||
public final class FinancialBusinessRules {
|
||||
private FinancialBusinessRules() { }
|
||||
|
||||
/** Compatibility entry point for existing callers that only model employee and supplier payees. */
|
||||
public static void payee(String type, Long employeeUserId, String supplierCreditCode) {
|
||||
String legacyPayeeCode = "SUPPLIER".equals(type) && supplierCreditCode != null ? "LEGACY" : null;
|
||||
payee(type, employeeUserId, supplierCreditCode, legacyPayeeCode, supplierCreditCode);
|
||||
}
|
||||
|
||||
public static void payee(String type, Long employeeUserId, String supplierCreditCode,
|
||||
String payeeCode, String identityValue) {
|
||||
boolean employee = "EMPLOYEE".equals(type);
|
||||
boolean supplier = "SUPPLIER".equals(type);
|
||||
require(employee || supplier, "付款对象类型不正确");
|
||||
require(employee ? employeeUserId != null && supplierCreditCode == null
|
||||
: employeeUserId == null && supplierCreditCode != null,
|
||||
"付款对象类型与员工、供应商身份必须匹配且互斥");
|
||||
boolean government = "GOVERNMENT".equals(type);
|
||||
require(employee || supplier || government, "收款方类型不正确");
|
||||
require(employee
|
||||
? employeeUserId != null && supplierCreditCode == null
|
||||
&& payeeCode == null && identityValue == null
|
||||
: employeeUserId == null && payeeCode != null && identityValue != null
|
||||
&& (supplier == (supplierCreditCode != null)),
|
||||
"收款方类型与员工、供应商或政府机构身份必须匹配且互斥");
|
||||
}
|
||||
|
||||
public static void currency(Integer decimalPlaces, BigDecimal exchangeRate) {
|
||||
|
||||
@@ -183,8 +183,8 @@ public final class TenantBackfillTool {
|
||||
private static Map<String, TableSpec> tableSpecs() {
|
||||
Map<String, TableSpec> result = new LinkedHashMap<>();
|
||||
for (TableSpec spec : Arrays.asList(
|
||||
new TableSpec("reim_application", "id", true),
|
||||
new TableSpec("reim_payment", "id", true),
|
||||
new TableSpec("payment_application", "id", true),
|
||||
new TableSpec("payment_result", "id", true),
|
||||
new TableSpec("sys_integration_config", "id", true),
|
||||
new TableSpec("sys_user_kingdee_account", "user_id", true),
|
||||
new TableSpec("sys_kingdee_sync_config", "id", true),
|
||||
|
||||
@@ -13,7 +13,8 @@ public final class LogText {
|
||||
private static final Map<String, String> RESOURCE_TYPES = new LinkedHashMap<>();
|
||||
|
||||
static {
|
||||
API_DOMAINS.put("/api/v1/reimbursements", "报销申请");
|
||||
API_DOMAINS.put("/api/v1/payment-applications", "付款申请");
|
||||
API_DOMAINS.put("/api/v1/reimbursements", "付款申请(兼容接口)");
|
||||
API_DOMAINS.put("/api/v1/travel-applications", "出差申请");
|
||||
API_DOMAINS.put("/api/v1/accounts-payable", "财务处理");
|
||||
API_DOMAINS.put("/api/v1/cashier", "出纳付款");
|
||||
@@ -24,15 +25,16 @@ public final class LogText {
|
||||
API_DOMAINS.put("/api/integrations/config", "集成配置");
|
||||
API_DOMAINS.put("/api/kingdee/account-bindings", "金蝶账号绑定");
|
||||
API_DOMAINS.put("/api/business-config", "业务配置");
|
||||
API_DOMAINS.put("/api/payees", "付款对象");
|
||||
API_DOMAINS.put("/api/payees", "收款方");
|
||||
API_DOMAINS.put("/api/user-groups", "用户组");
|
||||
API_DOMAINS.put("/api/roles", "角色权限");
|
||||
API_DOMAINS.put("/api/auth", "登录与用户");
|
||||
API_DOMAINS.put("/api/scheduled-tasks", "自动任务");
|
||||
API_DOMAINS.put("/api/scheduled-tasks", "定时任务");
|
||||
API_DOMAINS.put("/api/audit/events", "审计日志");
|
||||
API_DOMAINS.put("/api/logs", "访问日志");
|
||||
API_DOMAINS.put("/api/metadata/expense-types", "费用类型");
|
||||
API_DOMAINS.put("/api/metadata/payees", "付款对象元数据");
|
||||
API_DOMAINS.put("/api/metadata/payment-scenarios", "付款情形");
|
||||
API_DOMAINS.put("/api/metadata/expense-types", "付款情形(兼容接口)");
|
||||
API_DOMAINS.put("/api/metadata/payees", "收款方元数据");
|
||||
API_DOMAINS.put("/api/sources", "来源单据");
|
||||
API_DOMAINS.put("/api/v1/dashboard", "首页统计");
|
||||
|
||||
@@ -45,20 +47,20 @@ public final class LogText {
|
||||
AUDIT_ACTIONS.put("iam.role.update", "更新角色");
|
||||
AUDIT_ACTIONS.put("iam.role.delete", "删除角色");
|
||||
AUDIT_ACTIONS.put("iam.role.permission.update", "更新角色权限");
|
||||
AUDIT_ACTIONS.put("payee.subject.create", "新增付款对象");
|
||||
AUDIT_ACTIONS.put("payee.subject.update", "更新付款对象");
|
||||
AUDIT_ACTIONS.put("payee.subject.deactivate", "停用付款对象");
|
||||
AUDIT_ACTIONS.put("payee.subject.create", "新增收款方");
|
||||
AUDIT_ACTIONS.put("payee.subject.update", "更新收款方");
|
||||
AUDIT_ACTIONS.put("payee.subject.deactivate", "停用收款方");
|
||||
AUDIT_ACTIONS.put("payee.account.create", "新增收款账户");
|
||||
AUDIT_ACTIONS.put("payee.account.update", "更新收款账户");
|
||||
AUDIT_ACTIONS.put("payee.account.default", "设置默认收款账户");
|
||||
AUDIT_ACTIONS.put("payee.account.deactivate", "停用收款账户");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.create", "新增报销申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.update", "更新报销申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.submit", "提交报销申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.delete", "删除报销申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.attachment.upload", "上传报销附件");
|
||||
AUDIT_ACTIONS.put("reimbursement.attachment.delete", "删除报销附件");
|
||||
AUDIT_ACTIONS.put("finance.receipt.receive", "财务收单");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.create", "新增付款申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.update", "更新付款申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.submit", "提交付款申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.application.delete", "删除付款申请");
|
||||
AUDIT_ACTIONS.put("reimbursement.attachment.upload", "上传付款申请附件");
|
||||
AUDIT_ACTIONS.put("reimbursement.attachment.delete", "删除付款申请附件");
|
||||
AUDIT_ACTIONS.put("finance.receipt.receive", "财务核对");
|
||||
AUDIT_ACTIONS.put("finance.approval.approve", "审批通过");
|
||||
AUDIT_ACTIONS.put("finance.approval.reject", "审批退回");
|
||||
AUDIT_ACTIONS.put("finance.approval.transfer", "转交审批");
|
||||
@@ -78,11 +80,14 @@ public final class LogText {
|
||||
RESOURCE_TYPES.put("FEISHU_APPROVAL_DEFINITION", "飞书审批定义");
|
||||
RESOURCE_TYPES.put("IAM_GROUP", "用户组");
|
||||
RESOURCE_TYPES.put("IAM_ROLE", "角色");
|
||||
RESOURCE_TYPES.put("SYS_PAYEE", "付款对象");
|
||||
RESOURCE_TYPES.put("SYS_PAYEE", "收款方");
|
||||
RESOURCE_TYPES.put("SYS_BANK_ACCOUNT", "收款账户");
|
||||
RESOURCE_TYPES.put("REIM_APPLICATION", "报销申请");
|
||||
RESOURCE_TYPES.put("REIM_ATTACHMENT", "报销附件");
|
||||
RESOURCE_TYPES.put("REIM_PAYMENT", "付款记录");
|
||||
RESOURCE_TYPES.put("REIM_APPLICATION", "付款申请(历史标识)");
|
||||
RESOURCE_TYPES.put("REIM_ATTACHMENT", "付款申请附件(历史标识)");
|
||||
RESOURCE_TYPES.put("REIM_PAYMENT", "付款结果(历史标识)");
|
||||
RESOURCE_TYPES.put("PAYMENT_APPLICATION", "付款申请");
|
||||
RESOURCE_TYPES.put("PAYMENT_ATTACHMENT", "付款申请附件");
|
||||
RESOURCE_TYPES.put("PAYMENT_RESULT", "付款结果");
|
||||
RESOURCE_TYPES.put("BIZ_LEGAL_ENTITY", "法人主体");
|
||||
RESOURCE_TYPES.put("BIZ_COST_CENTER", "成本中心");
|
||||
RESOURCE_TYPES.put("BIZ_PAYMENT_METHOD", "付款方式");
|
||||
@@ -116,7 +121,7 @@ public final class LogText {
|
||||
if (route.endsWith("/submit")) return "提交申请";
|
||||
if (route.endsWith("/route-preview")) return "预览审批流转节点";
|
||||
if (route.endsWith("/route-timeline")) return "查询审批流转记录";
|
||||
if (route.endsWith("/receive")) return "财务收单";
|
||||
if (route.endsWith("/receive")) return "财务核对";
|
||||
if (route.endsWith("/approve")) return "审批通过";
|
||||
if (route.endsWith("/reject")) return "审批退回";
|
||||
if (route.endsWith("/transfer")) return "转交审批";
|
||||
|
||||
@@ -23,6 +23,8 @@ public interface ReimApplicationRepository extends JpaRepository<ReimApplication
|
||||
|
||||
List<ReimApplication> findBySourceDocNoAndSourceSystem(String sourceDocNo, String sourceSystem);
|
||||
|
||||
long countByLinkedTravelApplicationIdAndDeletedFalse(Long linkedTravelApplicationId);
|
||||
|
||||
List<ReimApplication> findTopByApplicationNoStartingWithOrderByApplicationNoDesc(String prefix);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@@ -86,8 +88,8 @@ public interface ReimApplicationRepository extends JpaRepository<ReimApplication
|
||||
+ "sum(case when a.approvalStatus = 'REJECTED' then 1 else 0 end), "
|
||||
+ "sum(case when a.paymentStatus = 'UNPAID' then 1 else 0 end), "
|
||||
+ "sum(case when a.paymentStatus in ('UNPAID','PARTIAL') then 1 else 0 end), "
|
||||
+ "coalesce(sum(a.totalAmount),0), "
|
||||
+ "coalesce(sum(case when a.paymentStatus = 'PAID' then a.totalAmount else 0 end),0) "
|
||||
+ "coalesce(sum(a.requestedAmount),0), "
|
||||
+ "coalesce(sum(case when a.paymentStatus = 'PAID' then a.requestedAmount else 0 end),0) "
|
||||
+ "from ReimApplication a where a.tenantId = :tenantId and a.deleted = false and "
|
||||
+ SCOPE_PREDICATE)
|
||||
Object[] aggregateScoped(@Param("tenantId") String tenantId, @Param("scope") String scope,
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.springframework.data.repository.query.Param;
|
||||
|
||||
import javax.persistence.LockModeType;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -19,6 +20,11 @@ public interface ReimPaymentRepository extends JpaRepository<ReimPayment, Long>
|
||||
|
||||
List<ReimPayment> findByApplicationId(Long applicationId);
|
||||
|
||||
@Query("select coalesce(sum(p.actualPaymentAmount), 0) from ReimPayment p "
|
||||
+ "where p.applicationId = :applicationId and p.deleted = false "
|
||||
+ "and p.paymentStatus in ('COMPLETED','PENDING_RECEIPT')")
|
||||
BigDecimal sumEffectiveAmountByApplicationId(@Param("applicationId") Long applicationId);
|
||||
|
||||
ReimPayment findByIdempotencyKey(String idempotencyKey);
|
||||
|
||||
List<ReimPayment> findTopByPaymentNoStartingWithOrderByPaymentNoDesc(String prefix);
|
||||
|
||||
@@ -9,9 +9,9 @@ import java.util.List;
|
||||
@Repository
|
||||
public interface SysExpenseTypeRepository extends JpaRepository<SysExpenseType, Long> {
|
||||
|
||||
SysExpenseType findByTypeCode(String typeCode);
|
||||
SysExpenseType findByScenarioCode(String scenarioCode);
|
||||
|
||||
List<SysExpenseType> findByCategory(String category);
|
||||
List<SysExpenseType> findByScenarioGroup(String scenarioGroup);
|
||||
|
||||
List<SysExpenseType> findByStatus(String status);
|
||||
|
||||
|
||||
@@ -21,6 +21,10 @@ public interface SysPayeeRepository extends JpaRepository<SysPayee, Long> {
|
||||
boolean existsByTenantIdAndSupplierCreditCodeAndIdNot(
|
||||
String tenantId, String supplierCreditCode, Long id);
|
||||
|
||||
boolean existsByTenantIdAndPayeeCode(String tenantId, String payeeCode);
|
||||
|
||||
boolean existsByTenantIdAndIdentityValueAndIdNot(String tenantId, String identityValue, Long id);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select p from SysPayee p where p.id = :id")
|
||||
Optional<SysPayee> findByIdForUpdate(@Param("id") Long id);
|
||||
|
||||
@@ -66,8 +66,7 @@ public class PermissionChecker {
|
||||
/** Canonical IAM/resource check. This path always enforces and never falls back to page permissions. */
|
||||
public boolean check(Authentication authentication, String resource, String action) {
|
||||
SubjectContext subject = authenticatedSubject(authentication);
|
||||
ResourceContext context = isGlobalIam(resource)
|
||||
? ResourceContext.global(resource) : ResourceContext.unscoped(resource);
|
||||
ResourceContext context = methodSecurityContext(resource, subject);
|
||||
authorizationService.check(AuthorizationRequest.builder().subject(subject)
|
||||
.resource(resource).action(action).resourceContext(context).build());
|
||||
return true;
|
||||
@@ -76,12 +75,26 @@ public class PermissionChecker {
|
||||
public boolean can(Authentication authentication, String resource, String action) {
|
||||
SubjectContext subject = authenticatedSubject(authentication);
|
||||
if (subject == null) return false;
|
||||
ResourceContext context = isGlobalIam(resource)
|
||||
? ResourceContext.global(resource) : ResourceContext.unscoped(resource);
|
||||
ResourceContext context = methodSecurityContext(resource, subject);
|
||||
return authorizationService.can(AuthorizationRequest.builder().subject(subject)
|
||||
.resource(resource).action(action).resourceContext(context).build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Method-level integration checks know the caller boundary, but not a target
|
||||
* resource. Supplying only tenant and organization allows ALL policies while
|
||||
* keeping SELF, department and current-approver policies fail-closed until a
|
||||
* controller/service supplies the concrete resource context.
|
||||
*/
|
||||
private ResourceContext methodSecurityContext(String resource, SubjectContext subject) {
|
||||
if (isGlobalIam(resource)) return ResourceContext.global(resource);
|
||||
if (subject == null) return ResourceContext.unscoped(resource);
|
||||
return ResourceContext.builder().resourceType(resource)
|
||||
.tenantId(subject.getTenantId())
|
||||
.organizationId(subject.getOrganizationId())
|
||||
.build();
|
||||
}
|
||||
|
||||
private boolean isGlobalIam(String resource) {
|
||||
return resource != null && resource.startsWith("iam.");
|
||||
}
|
||||
|
||||
@@ -97,10 +97,10 @@ public class FinanceAuthorization {
|
||||
|
||||
private AuthorizationRequest applicationRequest(Long actorId, String resource, String action,
|
||||
ReimApplication application) {
|
||||
if (application == null) throw new ResourceNotFoundException("报销申请不存在");
|
||||
if (application == null) throw new ResourceNotFoundException("付款申请不存在");
|
||||
SubjectContext subject = subject(actorId);
|
||||
SysUser owner = users.findById(application.getApplicantId())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
return AuthorizationRequest.builder()
|
||||
.subject(subject).resource(resource).action(action)
|
||||
.resourceContext(ResourceContext.builder().resourceType(resource)
|
||||
@@ -116,7 +116,7 @@ public class FinanceAuthorization {
|
||||
public AuthorizationDecision checkProspectiveApprover(Long actorId, ReimApplication application) {
|
||||
SubjectContext subject = subject(actorId);
|
||||
SysUser owner = users.findById(application.getApplicantId())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
return authorizationService.check(AuthorizationRequest.builder().subject(subject)
|
||||
.resource("finance.approval").action("decide")
|
||||
.resourceContext(ResourceContext.builder().resourceType("finance.approval")
|
||||
|
||||
@@ -18,10 +18,16 @@ public class FinanceFieldProjection {
|
||||
if (!readable(decision, "applicantEmployeeNo")) value.setApplicantEmployeeNo(null);
|
||||
else if (masked(decision, "applicantEmployeeNo")) value.setApplicantEmployeeNo(mask(value.getApplicantEmployeeNo()));
|
||||
if (hidden(decision, "departmentId")) value.setDepartmentId(null);
|
||||
if (hidden(decision, "expenseTypeId")) value.setExpenseTypeId(null);
|
||||
if (!readable(decision, "totalAmount")) value.setTotalAmount(null);
|
||||
if (!readable(decision, "description")) value.setDescription(null);
|
||||
else if (masked(decision, "description")) value.setDescription(mask(value.getDescription()));
|
||||
if (hidden(decision, "expenseTypeId")) value.setPaymentScenarioId(null);
|
||||
if (!readable(decision, "totalAmount")) {
|
||||
value.setRequestedAmount(null); value.setApprovedAmount(null);
|
||||
value.setActualPaymentAmount(null); value.setPaidAmount(null); value.setRemainingAmount(null);
|
||||
}
|
||||
if (!readable(decision, "description")) {
|
||||
value.setDescription(null); value.setPaymentReason(null);
|
||||
} else if (masked(decision, "description")) {
|
||||
value.setDescription(mask(value.getDescription())); value.setPaymentReason(mask(value.getPaymentReason()));
|
||||
}
|
||||
if (hidden(decision, "currentApproverId")) value.setCurrentApproverId(null);
|
||||
if (!readable(decision, "payeeName")) value.setPayeeName(null);
|
||||
else if (masked(decision, "payeeName")) value.setPayeeName(mask(value.getPayeeName()));
|
||||
@@ -45,7 +51,10 @@ public class FinanceFieldProjection {
|
||||
public ReimApplicationSummary application(ReimApplicationSummary value, AuthorizationDecision decision) {
|
||||
if (!readable(decision, "applicantName")) value.setApplicantName(null);
|
||||
else if (masked(decision, "applicantName")) value.setApplicantName(mask(value.getApplicantName()));
|
||||
if (!readable(decision, "totalAmount")) value.setTotalAmount(null);
|
||||
if (!readable(decision, "totalAmount")) {
|
||||
value.setRequestedAmount(null); value.setApprovedAmount(null);
|
||||
value.setActualPaymentAmount(null); value.setPaidAmount(null); value.setRemainingAmount(null);
|
||||
}
|
||||
if (!readable(decision, "returnReason")) value.setReturnReason(null);
|
||||
else if (masked(decision, "returnReason")) value.setReturnReason(mask(value.getReturnReason()));
|
||||
return value;
|
||||
@@ -55,7 +64,8 @@ public class FinanceFieldProjection {
|
||||
if (!readable(decision, "payeeName")) value.setPayeeName(null);
|
||||
else if (masked(decision, "payeeName")) value.setPayeeName(mask(value.getPayeeName()));
|
||||
if (!readable(decision, "amount")) {
|
||||
value.setTotalAmount(null); value.setPaidAmount(null); value.setRemainingAmount(null);
|
||||
value.setTotalAmount(null); value.setRequestedAmount(null); value.setApprovedAmount(null);
|
||||
value.setPaidAmount(null); value.setActualPaymentAmount(null); value.setRemainingAmount(null);
|
||||
}
|
||||
if (!readable(decision, "bankAccount")) {
|
||||
value.setBankName(null); value.setBankAccountMask(null);
|
||||
@@ -67,7 +77,8 @@ public class FinanceFieldProjection {
|
||||
if (!readable(decision, "payeeName")) value.setPayeeName(null);
|
||||
else if (masked(decision, "payeeName")) value.setPayeeName(mask(value.getPayeeName()));
|
||||
if (!readable(decision, "amount")) {
|
||||
value.setTotalAmount(null); value.setPaidAmount(null); value.setRemainingAmount(null);
|
||||
value.setTotalAmount(null); value.setRequestedAmount(null); value.setApprovedAmount(null);
|
||||
value.setPaidAmount(null); value.setActualPaymentAmount(null); value.setRemainingAmount(null);
|
||||
}
|
||||
if (!readable(decision, "bankAccount")) {
|
||||
value.setBankName(null); value.setBranchName(null); value.setBankAccountMask(null);
|
||||
@@ -81,11 +92,15 @@ public class FinanceFieldProjection {
|
||||
|
||||
public PaymentRecordDto payment(PaymentRecordDto value, AuthorizationDecision decision) {
|
||||
if (!readable(decision, "amount")) {
|
||||
value.setPaymentAmount(null); value.setTotalAmount(null);
|
||||
value.setActualPaymentAmount(null); value.setApprovedAmount(null);
|
||||
value.setPaidAmount(null); value.setRemainingAmount(null);
|
||||
}
|
||||
if (!readable(decision, "referenceNo")) value.setReferenceNo(null);
|
||||
else if (masked(decision, "referenceNo")) value.setReferenceNo(mask(value.getReferenceNo()));
|
||||
if (!readable(decision, "referenceNo")) {
|
||||
value.setBankTransactionNo(null); value.setPaymentReceipt(null);
|
||||
} else if (masked(decision, "referenceNo")) {
|
||||
value.setBankTransactionNo(mask(value.getBankTransactionNo()));
|
||||
value.setPaymentReceipt(mask(value.getPaymentReceipt()));
|
||||
}
|
||||
if (!readable(decision, "remark")) value.setRemark(null);
|
||||
else if (masked(decision, "remark")) value.setRemark(mask(value.getRemark()));
|
||||
return value;
|
||||
|
||||
@@ -107,8 +107,9 @@ public class ApiAccessLogService {
|
||||
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/v1/reimbursements") || value.startsWith("/api/applications")
|
||||
|| value.startsWith("/api/reim") || value.contains("/attachment")) return "报销申请";
|
||||
if (value.startsWith("/api/v1/payment-applications") || value.startsWith("/api/v1/reimbursements")
|
||||
|| value.startsWith("/api/applications") || value.startsWith("/api/reim")
|
||||
|| value.contains("/attachment")) return "付款申请";
|
||||
if (value.startsWith("/api/v1/travel-applications")) return "出差申请";
|
||||
if (value.startsWith("/api/v1/cashier") || value.startsWith("/api/payments") || value.contains("/payment")) return "付款操作";
|
||||
if (value.startsWith("/api/v1/accounts-payable") || value.contains("/finance") || value.contains("/receipt")) return "财务处理";
|
||||
@@ -118,7 +119,7 @@ public class ApiAccessLogService {
|
||||
if (value.contains("/group") || value.contains("/role") || value.contains("/permission") || value.contains("/users")) return "人员权限";
|
||||
if (value.startsWith("/api/business-config") || value.contains("/expense-type")
|
||||
|| value.contains("/payee") || value.contains("/source")) return "业务配置";
|
||||
if (value.contains("/scheduled")) return "自动任务";
|
||||
if (value.contains("/scheduled")) return "定时任务";
|
||||
return "接口访问";
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import com.finance.system.security.finance.FinanceAuthorization;
|
||||
import com.finance.system.util.AuditUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@@ -25,6 +26,9 @@ public class BankAccountPaymentSecretService {
|
||||
private final BankAccountProtection protection;
|
||||
private final FinanceAuditEvents audit;
|
||||
|
||||
@Value("${finance.payment.require-receipt-before-registration:false}")
|
||||
private boolean requireFinanceCheckBeforeRegistration;
|
||||
|
||||
public BankAccountPaymentSecretService(ReimApplicationRepository applications,
|
||||
SysBankAccountRepository accounts,
|
||||
FinanceAuthorization authorization,
|
||||
@@ -43,17 +47,17 @@ public class BankAccountPaymentSecretService {
|
||||
throw new UnauthorizedException("无权使用其他用户身份读取付款账号");
|
||||
}
|
||||
ReimApplication application = applications.findById(applicationId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
if (Boolean.TRUE.equals(application.getDeleted())) {
|
||||
throw new ResourceNotFoundException("报销申请不存在");
|
||||
throw new ResourceNotFoundException("付款申请不存在");
|
||||
}
|
||||
authorization.checkApplication(actorId, "finance.payment", "register", application);
|
||||
if (!"APPROVED".equals(application.getApprovalStatus())
|
||||
|| !"RECEIVED".equals(application.getReceiptStatus())) {
|
||||
throw new BusinessException("报销申请尚未满足付款条件", 409);
|
||||
|| (requireFinanceCheckBeforeRegistration && !"RECEIVED".equals(application.getReceiptStatus()))) {
|
||||
throw new BusinessException("付款申请尚未满足付款条件", 409);
|
||||
}
|
||||
if (application.getPayeeBankId() == null) {
|
||||
throw new BusinessException("报销申请未指定收款账户", 409);
|
||||
throw new BusinessException("付款申请未指定收款账户", 409);
|
||||
}
|
||||
SysBankAccount account = accounts.findById(application.getPayeeBankId())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("收款账户不存在"));
|
||||
|
||||
@@ -86,7 +86,7 @@ public class PayeeAccountService {
|
||||
boolean canEdit = authorization.canUserResource(subject, REIMBURSEMENT_RESOURCE,
|
||||
"edit", actor, String.valueOf(actor.getId()));
|
||||
if (!canCreate && !canEdit) {
|
||||
throw new AccessDeniedException("当前账号没有发起或编辑报销权限");
|
||||
throw new AccessDeniedException("当前账号没有发起或编辑付款申请权限");
|
||||
}
|
||||
Map<Long, String> departmentNames = departmentNames(Collections.singletonList(actor));
|
||||
return accounts.findByUserId(actorId).stream()
|
||||
@@ -160,7 +160,7 @@ public class PayeeAccountService {
|
||||
try {
|
||||
account = accounts.saveAndFlush(account);
|
||||
} catch (DataIntegrityViolationException conflict) {
|
||||
throw new BusinessException("付款对象数据冲突,请刷新后重试", 409);
|
||||
throw new BusinessException("收款方数据冲突,请刷新后重试", 409);
|
||||
}
|
||||
audit.business("payee.account.create", actorId, "SYS_BANK_ACCOUNT", account.getId(),
|
||||
account.getStatus(), null, changes("userId", "bankName", "branchName",
|
||||
@@ -172,20 +172,20 @@ public class PayeeAccountService {
|
||||
public PayeeAccountDto update(Long actorId, Long accountId, PayeeAccountRequest request) {
|
||||
Access access = access(actorId);
|
||||
SysBankAccount initial = accounts.findById(accountId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款对象不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("收款方不存在"));
|
||||
Long originalUserId = initial.getUserId();
|
||||
Long requestedUserId = request.getUserId();
|
||||
SysUser user = lockActiveTarget(originalUserId, access);
|
||||
if (!Objects.equals(originalUserId, requestedUserId)) {
|
||||
throw new BusinessException("付款对象所属员工创建后不可变,请停用旧账户后新增", 400);
|
||||
throw new BusinessException("收款方所属员工创建后不可变,请停用旧账户后新增", 400);
|
||||
}
|
||||
entityManager.refresh(initial, LockModeType.PESSIMISTIC_WRITE);
|
||||
if (!Objects.equals(initial.getUserId(), originalUserId)) {
|
||||
throw new BusinessException("付款对象数据已变化,请刷新后重试", 409);
|
||||
throw new BusinessException("收款方数据已变化,请刷新后重试", 409);
|
||||
}
|
||||
List<SysBankAccount> existing = accounts.findByUserIdForUpdate(originalUserId);
|
||||
SysBankAccount account = existing.stream().filter(value -> Objects.equals(value.getId(), accountId))
|
||||
.findFirst().orElseThrow(() -> new ResourceNotFoundException("付款对象不存在"));
|
||||
.findFirst().orElseThrow(() -> new ResourceNotFoundException("收款方不存在"));
|
||||
if (account.getPayeeId() == null) {
|
||||
account.setPayeeId(payeeSubjects.ensureEmployeePayee(user).getId());
|
||||
}
|
||||
@@ -209,12 +209,12 @@ public class PayeeAccountService {
|
||||
public PayeeAccountDto deactivate(Long actorId, Long accountId) {
|
||||
Access access = access(actorId);
|
||||
SysBankAccount initial = accounts.findById(accountId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款对象不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("收款方不存在"));
|
||||
SysUser user = lockActiveTarget(initial.getUserId(), access);
|
||||
entityManager.refresh(initial, LockModeType.PESSIMISTIC_WRITE);
|
||||
List<SysBankAccount> existing = accounts.findByUserIdForUpdate(user.getId());
|
||||
SysBankAccount account = existing.stream().filter(value -> Objects.equals(value.getId(), accountId))
|
||||
.findFirst().orElseThrow(() -> new ResourceNotFoundException("付款对象不存在"));
|
||||
.findFirst().orElseThrow(() -> new ResourceNotFoundException("收款方不存在"));
|
||||
account.setStatus(INACTIVE);
|
||||
account.setIsDefault(false);
|
||||
account = accounts.save(account);
|
||||
@@ -227,7 +227,7 @@ public class PayeeAccountService {
|
||||
SubjectContext subject = authorization.subject(actorId);
|
||||
if (subject == null || !StringUtils.hasText(subject.getTenantId())
|
||||
|| subject.getOrganizationId() == null) {
|
||||
throw new AccessDeniedException("付款对象访问边界无效");
|
||||
throw new AccessDeniedException("收款方访问边界无效");
|
||||
}
|
||||
return new Access(subject);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@@ -40,6 +41,9 @@ public class PayeeSubjectService {
|
||||
private static final String RESOURCE = "payee.account";
|
||||
private static final String EMPLOYEE = "EMPLOYEE";
|
||||
private static final String SUPPLIER = "SUPPLIER";
|
||||
private static final String GOVERNMENT = "GOVERNMENT";
|
||||
private static final String INTERNAL = "INTERNAL";
|
||||
private static final String EXTERNAL = "EXTERNAL";
|
||||
private static final String ACTIVE = "ACTIVE";
|
||||
private static final String INACTIVE = "INACTIVE";
|
||||
|
||||
@@ -74,6 +78,8 @@ public class PayeeSubjectService {
|
||||
.filter(payee -> can(access, payee, "read"))
|
||||
.map(payee -> toSubjectDto(payee, can(access, payee, "manage")))
|
||||
.filter(dto -> search == null || contains(dto.getDisplayName(), search)
|
||||
|| contains(dto.getPayeeCode(), search)
|
||||
|| contains(dto.getCountryRegion(), search)
|
||||
|| contains(dto.getIdentityNumber(), search)
|
||||
|| contains(dto.getSupplierCreditCode(), search))
|
||||
.collect(Collectors.toList());
|
||||
@@ -103,7 +109,7 @@ public class PayeeSubjectService {
|
||||
payee = payees.findByEmployeeOpenId(employee.getFeishuOpenId())
|
||||
.orElseGet(() -> payees.findByEmployeeUserId(employee.getId())
|
||||
.filter(value -> !StringUtils.hasText(value.getEmployeeOpenId())).orElseGet(SysPayee::new));
|
||||
if (payee.getId() != null) throw new BusinessException("该员工已存在付款对象主体", 409);
|
||||
if (payee.getId() != null) throw new BusinessException("该员工已存在收款方主体", 409);
|
||||
employee.setIdentityNumber(identityNumber(request.getIdentityNumber()));
|
||||
users.save(employee);
|
||||
payee.setTenantId(employee.getTenantId());
|
||||
@@ -111,15 +117,33 @@ public class PayeeSubjectService {
|
||||
payee.setEmployeeOpenId(employee.getFeishuOpenId());
|
||||
payee.setEmployeeUserId(employee.getId()); // Legacy FK mirror; business identity is openId.
|
||||
payee.setDisplayName(employee.getRealName());
|
||||
payee.setPayeeCode(null);
|
||||
payee.setRelationType(INTERNAL);
|
||||
payee.setCountryRegion("中国");
|
||||
payee.setIdentityType(null);
|
||||
payee.setIdentityValue(null);
|
||||
payee.setSupplierCreditCode(null);
|
||||
} else {
|
||||
rejectSupplierIdentityNumber(request);
|
||||
rejectExternalIdentityNumber(request);
|
||||
checkSupplierAccess(access, "manage", null);
|
||||
payee = new SysPayee();
|
||||
payee.setTenantId(access.subject.getTenantId());
|
||||
payee.setOrganizationId(access.subject.getOrganizationId());
|
||||
payee.setDisplayName(text(request.getDisplayName(), "供应商名称", 200, true));
|
||||
payee.setSupplierCreditCode(creditCode(request.getSupplierCreditCode()));
|
||||
assertSupplierCodeAvailable(payee);
|
||||
payee.setDisplayName(text(request.getDisplayName(), externalTypeLabel(type) + "名称", 200, true));
|
||||
String requestedIdentity = StringUtils.hasText(request.getIdentityValue())
|
||||
? request.getIdentityValue() : request.getSupplierCreditCode();
|
||||
String identityValue = StringUtils.hasText(requestedIdentity)
|
||||
? creditCode(requestedIdentity) : payee.getIdentityValue();
|
||||
if (!StringUtils.hasText(identityValue)) {
|
||||
throw new BusinessException("统一社会信用代码不能为空", 400);
|
||||
}
|
||||
payee.setPayeeCode(nextPayeeCode(payee.getTenantId(), type));
|
||||
payee.setRelationType(normalizeRelation(request.getRelationType()));
|
||||
payee.setCountryRegion(countryRegion(request.getCountryRegion()));
|
||||
payee.setIdentityType(identityType(request.getIdentityType()));
|
||||
payee.setIdentityValue(identityValue);
|
||||
payee.setSupplierCreditCode(SUPPLIER.equals(type) ? identityValue : null);
|
||||
assertExternalIdentityAvailable(payee);
|
||||
}
|
||||
payee.setPayeeType(type);
|
||||
payee.setStatus(normalizeStatus(request.getStatus()));
|
||||
@@ -127,11 +151,11 @@ public class PayeeSubjectService {
|
||||
try {
|
||||
payee = payees.saveAndFlush(payee);
|
||||
} catch (DataIntegrityViolationException conflict) {
|
||||
throw new BusinessException("付款对象主体数据冲突,请刷新后重试", 409);
|
||||
throw new BusinessException("收款方主体数据冲突,请刷新后重试", 409);
|
||||
}
|
||||
audit.business("payee.subject.create", actorId, "SYS_PAYEE", payee.getId(),
|
||||
payee.getStatus(), null, changes("payeeType", "displayName", "employeeOpenId",
|
||||
"identityNumber", "supplierCreditCode", "status"));
|
||||
payee.getStatus(), null, changes("payeeCode", "payeeType", "displayName", "employeeOpenId",
|
||||
"identityNumber", "relationType", "countryRegion", "identityType", "status"));
|
||||
SysBankAccount initialAccount = new SysBankAccount();
|
||||
initialAccount.setPayeeId(payee.getId());
|
||||
initialAccount.setUserId(employeeId(payee));
|
||||
@@ -153,15 +177,15 @@ public class PayeeSubjectService {
|
||||
SysPayee payee = requirePayee(payeeId, access, "manage", true);
|
||||
String requestedType = normalizeType(request.getPayeeType());
|
||||
if (!requestedType.equals(payee.getPayeeType())) {
|
||||
throw new BusinessException("付款对象类型创建后不可变", 400);
|
||||
throw new BusinessException("收款方类型创建后不可变", 400);
|
||||
}
|
||||
if (EMPLOYEE.equals(requestedType)) {
|
||||
if (request.getEmployeeOpenId() != null
|
||||
&& !Objects.equals(request.getEmployeeOpenId(), employeeOpenId(payee))) {
|
||||
throw new BusinessException("关联员工创建后不可变", 400);
|
||||
}
|
||||
if (StringUtils.hasText(request.getSupplierCreditCode())) {
|
||||
throw new BusinessException("员工付款对象不能填写统一社会信用代码", 400);
|
||||
if (StringUtils.hasText(request.getSupplierCreditCode()) || StringUtils.hasText(request.getIdentityValue())) {
|
||||
throw new BusinessException("员工收款方不能填写统一社会信用代码", 400);
|
||||
}
|
||||
SysUser employee = requireEmployee(employeeOpenId(payee), access);
|
||||
if (request.getIdentityNumber() != null) {
|
||||
@@ -170,18 +194,34 @@ public class PayeeSubjectService {
|
||||
}
|
||||
payee.setEmployeeOpenId(employee.getFeishuOpenId());
|
||||
payee.setDisplayName(employee.getRealName());
|
||||
payee.setRelationType(INTERNAL);
|
||||
payee.setCountryRegion("中国");
|
||||
} else {
|
||||
rejectSupplierIdentityNumber(request);
|
||||
payee.setDisplayName(text(request.getDisplayName(), "供应商名称", 200, true));
|
||||
payee.setSupplierCreditCode(creditCode(request.getSupplierCreditCode()));
|
||||
assertSupplierCodeAvailable(payee);
|
||||
rejectExternalIdentityNumber(request);
|
||||
payee.setDisplayName(text(request.getDisplayName(), externalTypeLabel(requestedType) + "名称", 200, true));
|
||||
String requestedIdentity = StringUtils.hasText(request.getIdentityValue())
|
||||
? request.getIdentityValue() : request.getSupplierCreditCode();
|
||||
String identityValue = StringUtils.hasText(requestedIdentity)
|
||||
? creditCode(requestedIdentity) : payee.getIdentityValue();
|
||||
if (!StringUtils.hasText(identityValue)) {
|
||||
throw new BusinessException("统一社会信用代码不能为空", 400);
|
||||
}
|
||||
payee.setRelationType(StringUtils.hasText(request.getRelationType())
|
||||
? normalizeRelation(request.getRelationType()) : payee.getRelationType());
|
||||
payee.setCountryRegion(StringUtils.hasText(request.getCountryRegion())
|
||||
? countryRegion(request.getCountryRegion()) : payee.getCountryRegion());
|
||||
payee.setIdentityType(StringUtils.hasText(request.getIdentityType())
|
||||
? identityType(request.getIdentityType()) : payee.getIdentityType());
|
||||
payee.setIdentityValue(identityValue);
|
||||
payee.setSupplierCreditCode(SUPPLIER.equals(requestedType) ? identityValue : null);
|
||||
assertExternalIdentityAvailable(payee);
|
||||
}
|
||||
payee.setStatus(normalizeStatus(request.getStatus()));
|
||||
validatePayee(payee);
|
||||
payee = payees.save(payee);
|
||||
audit.business("payee.subject.update", actorId, "SYS_PAYEE", payee.getId(),
|
||||
payee.getStatus(), null, changes("displayName", "identityNumber",
|
||||
"supplierCreditCode", "status"));
|
||||
payee.getStatus(), null, changes("displayName", "identityNumber", "relationType",
|
||||
"countryRegion", "identityType", "identityValue", "status"));
|
||||
return toSubjectDto(payee, true);
|
||||
}
|
||||
|
||||
@@ -220,7 +260,7 @@ public class PayeeSubjectService {
|
||||
Access access = access(actorId);
|
||||
SysPayee payee = requirePayee(payeeId, access, "manage", true);
|
||||
if (!ACTIVE.equalsIgnoreCase(payee.getStatus())) {
|
||||
throw new BusinessException("付款对象主体已停用", 400);
|
||||
throw new BusinessException("收款方主体已停用", 400);
|
||||
}
|
||||
List<SysBankAccount> existing = accounts.findByPayeeIdForUpdate(payeeId);
|
||||
String accountNo = accountNo(request.getAccountNo(), true);
|
||||
@@ -266,7 +306,7 @@ public class PayeeSubjectService {
|
||||
Access access = access(actorId);
|
||||
SysPayee payee = requirePayee(payeeId, access, "manage", true);
|
||||
if (!ACTIVE.equalsIgnoreCase(payee.getStatus())) {
|
||||
throw new BusinessException("付款对象主体已停用", 400);
|
||||
throw new BusinessException("收款方主体已停用", 400);
|
||||
}
|
||||
List<SysBankAccount> existing = accounts.findByPayeeIdForUpdate(payeeId);
|
||||
SysBankAccount account = existing.stream()
|
||||
@@ -319,6 +359,7 @@ public class PayeeSubjectService {
|
||||
return existing.orElseGet(() -> {
|
||||
SysPayee value = SysPayee.builder().tenantId(employee.getTenantId())
|
||||
.organizationId(employee.getOrganizationId()).payeeType(EMPLOYEE)
|
||||
.relationType(INTERNAL).countryRegion("中国")
|
||||
.displayName(employee.getRealName()).employeeOpenId(employee.getFeishuOpenId())
|
||||
.employeeUserId(employee.getId())
|
||||
.status(ACTIVE).build();
|
||||
@@ -332,25 +373,26 @@ public class PayeeSubjectService {
|
||||
}
|
||||
|
||||
private void validatePayee(SysPayee payee) {
|
||||
FinancialBusinessRules.payee(payee.getPayeeType(), payee.getEmployeeUserId(), payee.getSupplierCreditCode());
|
||||
FinancialBusinessRules.payee(payee.getPayeeType(), payee.getEmployeeUserId(),
|
||||
payee.getSupplierCreditCode(), payee.getPayeeCode(), payee.getIdentityValue());
|
||||
}
|
||||
|
||||
private Access access(Long actorId) {
|
||||
SubjectContext subject = authorization.subject(actorId);
|
||||
SysUser actor = users.findById(actorId).orElseThrow(() -> new AccessDeniedException("当前用户不存在"));
|
||||
if (!StringUtils.hasText(subject.getTenantId()) || subject.getOrganizationId() == null) {
|
||||
throw new AccessDeniedException("付款对象访问边界无效");
|
||||
throw new AccessDeniedException("收款方访问边界无效");
|
||||
}
|
||||
return new Access(subject, actor);
|
||||
}
|
||||
|
||||
private SysPayee requirePayee(Long id, Access access, String action, boolean lock) {
|
||||
SysPayee payee = (lock ? payees.findByIdForUpdate(id) : payees.findById(id))
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款对象主体不存在"));
|
||||
if (!sameBoundary(payee, access.subject)) throw new ResourceNotFoundException("付款对象主体不存在");
|
||||
.orElseThrow(() -> new ResourceNotFoundException("收款方主体不存在"));
|
||||
if (!sameBoundary(payee, access.subject)) throw new ResourceNotFoundException("收款方主体不存在");
|
||||
if (EMPLOYEE.equals(payee.getPayeeType())) {
|
||||
SysUser owner = java.util.Optional.ofNullable(employee(payee))
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款对象主体不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("收款方主体不存在"));
|
||||
authorization.checkUserResource(access.subject, RESOURCE, action, owner, String.valueOf(id));
|
||||
} else {
|
||||
checkSupplierAccess(access, action, String.valueOf(id));
|
||||
@@ -409,6 +451,9 @@ public class PayeeSubjectService {
|
||||
private PayeeSubjectDto toSubjectDto(SysPayee payee, boolean manageable) {
|
||||
SysUser employee = employee(payee);
|
||||
return PayeeSubjectDto.builder().id(payee.getId()).payeeType(payee.getPayeeType())
|
||||
.payeeCode(payee.getPayeeCode()).relationType(payee.getRelationType())
|
||||
.countryRegion(payee.getCountryRegion()).identityType(payee.getIdentityType())
|
||||
.identityValueMaintained(StringUtils.hasText(payee.getIdentityValue()))
|
||||
.displayName(payee.getDisplayName()).employeeOpenId(employeeOpenId(payee))
|
||||
.identityNumber(employee == null ? null
|
||||
: FinanceFieldProjection.maskIdentityNumber(employee.getIdentityNumber()))
|
||||
@@ -462,7 +507,7 @@ public class PayeeSubjectService {
|
||||
boolean duplicate = existing.stream().anyMatch(value -> !Objects.equals(value.getId(), currentId)
|
||||
&& Objects.equals(canonical(value.getBankName()), bank)
|
||||
&& Objects.equals(value.getAccountFingerprint(), fingerprint));
|
||||
if (duplicate) throw new BusinessException("该付款对象已存在相同收款账户", 409);
|
||||
if (duplicate) throw new BusinessException("该收款方已存在相同收款账户", 409);
|
||||
}
|
||||
|
||||
private String requireProtectedFingerprint(SysBankAccount account) {
|
||||
@@ -473,14 +518,28 @@ public class PayeeSubjectService {
|
||||
return account.getAccountFingerprint();
|
||||
}
|
||||
|
||||
private void assertSupplierCodeAvailable(SysPayee payee) {
|
||||
private void assertExternalIdentityAvailable(SysPayee payee) {
|
||||
long excludedId = payee.getId() == null ? -1L : payee.getId();
|
||||
if (payees.existsByTenantIdAndSupplierCreditCodeAndIdNot(
|
||||
payee.getTenantId(), payee.getSupplierCreditCode(), excludedId)) {
|
||||
boolean duplicateIdentity = payees.existsByTenantIdAndIdentityValueAndIdNot(
|
||||
payee.getTenantId(), payee.getIdentityValue(), excludedId);
|
||||
boolean duplicateSupplier = SUPPLIER.equals(payee.getPayeeType())
|
||||
&& payees.existsByTenantIdAndSupplierCreditCodeAndIdNot(
|
||||
payee.getTenantId(), payee.getSupplierCreditCode(), excludedId);
|
||||
if (duplicateIdentity || duplicateSupplier) {
|
||||
throw new BusinessException("统一社会信用代码已存在", 409);
|
||||
}
|
||||
}
|
||||
|
||||
private String nextPayeeCode(String tenantId, String type) {
|
||||
String prefix = SUPPLIER.equals(type) ? "SUP-" : "GOV-";
|
||||
for (int attempt = 0; attempt < 20; attempt++) {
|
||||
String code = prefix + String.format(Locale.ROOT, "%06d",
|
||||
ThreadLocalRandom.current().nextInt(1_000_000));
|
||||
if (!payees.existsByTenantIdAndPayeeCode(tenantId, code)) return code;
|
||||
}
|
||||
throw new BusinessException("无法生成收款方业务编码,请重试", 409);
|
||||
}
|
||||
|
||||
private String creditCode(String value) {
|
||||
String code = text(value, "统一社会信用代码", 18, true).toUpperCase(Locale.ROOT);
|
||||
if (!code.matches("[0-9A-HJ-NPQRTUWXY]{18}")) {
|
||||
@@ -498,12 +557,37 @@ public class PayeeSubjectService {
|
||||
return number.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private void rejectSupplierIdentityNumber(PayeeSubjectRequest request) {
|
||||
private void rejectExternalIdentityNumber(PayeeSubjectRequest request) {
|
||||
if (request.getIdentityNumber() != null) {
|
||||
throw new BusinessException("供应商付款对象不能填写身份证号", 400);
|
||||
throw new BusinessException("外部收款方不能填写员工身份证号", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeRelation(String value) {
|
||||
if (!StringUtils.hasText(value)) return EXTERNAL;
|
||||
String relation = value.trim().toUpperCase(Locale.ROOT);
|
||||
if (!INTERNAL.equals(relation) && !EXTERNAL.equals(relation)) {
|
||||
throw new BusinessException("内外部属性必须为INTERNAL或EXTERNAL", 400);
|
||||
}
|
||||
return relation;
|
||||
}
|
||||
|
||||
private String countryRegion(String value) {
|
||||
return StringUtils.hasText(value) ? text(value, "国家或地区", 100, true) : "中国";
|
||||
}
|
||||
|
||||
private String identityType(String value) {
|
||||
String type = StringUtils.hasText(value) ? text(value, "身份标识类型", 50, true) : "统一社会信用代码";
|
||||
if (!"统一社会信用代码".equals(type)) {
|
||||
throw new BusinessException("供应商或政府机构的身份标识类型必须为统一社会信用代码", 400);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private String externalTypeLabel(String type) {
|
||||
return GOVERNMENT.equals(type) ? "政府机构" : "供应商";
|
||||
}
|
||||
|
||||
private String accountNo(String value, boolean required) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
if (required) throw new BusinessException("银行账号不能为空", 400);
|
||||
@@ -524,8 +608,8 @@ public class PayeeSubjectService {
|
||||
|
||||
private String normalizeType(String value) {
|
||||
String type = value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
|
||||
if (!EMPLOYEE.equals(type) && !SUPPLIER.equals(type)) {
|
||||
throw new BusinessException("付款对象类型必须为EMPLOYEE或SUPPLIER", 400);
|
||||
if (!EMPLOYEE.equals(type) && !SUPPLIER.equals(type) && !GOVERNMENT.equals(type)) {
|
||||
throw new BusinessException("收款方类型必须为EMPLOYEE、SUPPLIER或GOVERNMENT", 400);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
@@ -123,6 +123,7 @@ public class PrototypeBusinessConfigService {
|
||||
|
||||
public Map<String, Object> budgetOverview(Authentication authentication) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
int currentYear = Year.now().getValue();
|
||||
List<Map<String, Object>> subjects = jdbc.queryForList(
|
||||
"SELECT s.id,s.code,s.name,s.level,s.parent_id parentId,p.code parentCode,p.name parentName,s.description,s.status " +
|
||||
"FROM biz_budget_subject s LEFT JOIN biz_budget_subject p ON p.id=s.parent_id ORDER BY s.level,s.code");
|
||||
@@ -134,7 +135,8 @@ public class PrototypeBusinessConfigService {
|
||||
"l.executed_amount executedAmount,(l.limit_amount-l.occupied_amount-l.executed_amount) availableAmount,l.status " +
|
||||
"FROM biz_budget_ledger l JOIN biz_legal_entity le ON le.id=l.legal_entity_id " +
|
||||
"JOIN biz_cost_center cc ON cc.id=l.cost_center_id JOIN biz_budget_subject s ON s.id=l.budget_subject_id " +
|
||||
"LEFT JOIN biz_budget_subject p ON p.id=s.parent_id ORDER BY l.fiscal_year DESC,s.code,cc.code");
|
||||
"LEFT JOIN biz_budget_subject p ON p.id=s.parent_id " +
|
||||
"WHERE l.fiscal_year=? ORDER BY s.code,cc.code", currentYear);
|
||||
for (Map<String, Object> ledger : ledgers) {
|
||||
BigDecimal limit = decimalValue(ledger.get("limitAmount"));
|
||||
BigDecimal committed = decimalValue(ledger.get("occupiedAmount")).add(decimalValue(ledger.get("executedAmount")));
|
||||
@@ -148,10 +150,11 @@ public class PrototypeBusinessConfigService {
|
||||
"FROM biz_budget_adjustment a JOIN biz_budget_ledger l ON l.id=a.budget_ledger_id " +
|
||||
"JOIN biz_legal_entity le ON le.id=l.legal_entity_id JOIN biz_cost_center cc ON cc.id=l.cost_center_id " +
|
||||
"JOIN biz_budget_subject s ON s.id=l.budget_subject_id LEFT JOIN biz_budget_subject p ON p.id=s.parent_id " +
|
||||
"LEFT JOIN sys_user u ON u.id=a.applicant_user_id ORDER BY a.created_at DESC,a.id DESC");
|
||||
"LEFT JOIN sys_user u ON u.id=a.applicant_user_id " +
|
||||
"WHERE l.fiscal_year=? ORDER BY a.created_at DESC,a.id DESC", currentYear);
|
||||
List<Map<String, Object>> summary = budgetSummary(ledgers);
|
||||
filterBudgetOverview(subjects, ledgers, adjustments, summary, authentication);
|
||||
result.put("fiscalYear", Year.now().getValue());
|
||||
result.put("fiscalYear", currentYear);
|
||||
result.put("subjects", subjects);
|
||||
result.put("ledgers", ledgers);
|
||||
result.put("adjustments", adjustments);
|
||||
@@ -163,14 +166,14 @@ public class PrototypeBusinessConfigService {
|
||||
public Map<String, Object> createBudgetSubject(Map<String, Object> body, Authentication authentication) {
|
||||
assertBody(body, "parentId", "name", "description");
|
||||
requireEditable(authentication, "dialog.budgets.subject.parentId", "所属预算分类");
|
||||
requireEditable(authentication, "dialog.budgets.subject.name", "二级科目名称");
|
||||
requireEditable(authentication, "dialog.budgets.subject.name", "预算科目名称");
|
||||
requireEditable(authentication, "dialog.budgets.subject.description", "适用说明");
|
||||
Long parentId = longValue(body.get("parentId"), "所属预算分类");
|
||||
Map<String, Object> parent = queryOne("SELECT id,code,name,status,level FROM biz_budget_subject WHERE id=? FOR UPDATE", parentId);
|
||||
if (parent == null || number(parent.get("level")) != 1 || !"ACTIVE".equals(parent.get("status"))) {
|
||||
throw new BadRequestException("只能在启用的一级预算分类下新增二级科目");
|
||||
throw new BadRequestException("只能在启用的一级预算分类下新增预算科目");
|
||||
}
|
||||
String name = text(body.get("name"), "二级科目名称", 120);
|
||||
String name = text(body.get("name"), "预算科目名称", 120);
|
||||
String description = text(body.get("description"), "适用说明", 500);
|
||||
if (count("SELECT COUNT(*) FROM biz_budget_subject WHERE level=2 AND name=?", name) > 0) throw new BadRequestException("预算科目名称已存在");
|
||||
String code = nextSubjectCode(String.valueOf(parent.get("code")));
|
||||
@@ -187,7 +190,7 @@ public class PrototypeBusinessConfigService {
|
||||
public Map<String, Object> changeBudgetSubjectStatus(Long id, Map<String, Object> body) {
|
||||
String status = enumValue(body, "status", "状态", "ACTIVE", "INACTIVE");
|
||||
Map<String, Object> subject = queryOne("SELECT id,code,name,level,status FROM biz_budget_subject WHERE id=?", id);
|
||||
if (subject == null || number(subject.get("level")) != 2) throw new ResourceNotFoundException("二级预算科目不存在");
|
||||
if (subject == null || number(subject.get("level")) != 2) throw new ResourceNotFoundException("预算科目不存在");
|
||||
if ("INACTIVE".equals(status) && count("SELECT COUNT(*) FROM biz_budget_ledger WHERE budget_subject_id=? AND status='ACTIVE'", id) > 0) {
|
||||
throw new BadRequestException("该预算科目仍存在启用中的预算台账,不能停用");
|
||||
}
|
||||
@@ -223,7 +226,7 @@ public class PrototypeBusinessConfigService {
|
||||
requireActive("biz_legal_entity", legalId, "法人主体");
|
||||
requireActive("biz_cost_center", costId, "成本中心");
|
||||
if (count("SELECT COUNT(*) FROM biz_cost_center WHERE id=? AND legal_entity_id=?", costId, legalId) == 0) throw new BadRequestException("成本中心不属于所选法人主体");
|
||||
if (count("SELECT COUNT(*) FROM biz_budget_subject WHERE id=? AND level=2 AND status='ACTIVE'", subjectId) == 0) throw new BadRequestException("请选择启用的二级预算科目");
|
||||
if (count("SELECT COUNT(*) FROM biz_budget_subject WHERE id=? AND level=2 AND status='ACTIVE'", subjectId) == 0) throw new BadRequestException("请选择启用的预算科目");
|
||||
if (count("SELECT COUNT(*) FROM biz_currency WHERE code=? AND status='ACTIVE'", currency) == 0) throw new BadRequestException("请选择启用的币种");
|
||||
Long ledgerId = findOrCreateLedger(year, legalId, costId, subjectId, currency);
|
||||
Map<String, Object> ledger = queryOne("SELECT limit_amount limitAmount,occupied_amount occupiedAmount,executed_amount executedAmount FROM biz_budget_ledger WHERE id=? FOR UPDATE", ledgerId);
|
||||
@@ -452,7 +455,7 @@ public class PrototypeBusinessConfigService {
|
||||
removeWithout(authentication, subject, "ui.budgets.column.name", "name");
|
||||
removeWithout(authentication, subject, "ui.budgets.column.category", "parentCode", "parentName");
|
||||
removeWithout(authentication, subject, "ui.budgets.column.description", "description");
|
||||
removeWithout(authentication, subject, "ui.budgets.column.status", "status");
|
||||
// 科目状态同时是新增科目和预算调整下拉框的业务可选条件,不能按列表列权限移除。
|
||||
}
|
||||
for (Map<String, Object> ledger : ledgers) {
|
||||
removeWithout(authentication, ledger, "ui.budgets.column.fiscalYear", "fiscalYear");
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
public interface ReimPaymentService {
|
||||
@@ -18,15 +19,19 @@ public interface ReimPaymentService {
|
||||
}
|
||||
|
||||
PaymentResultDto executePayment(Long applicationId, BigDecimal amount, Long operatorId,
|
||||
String paymentMethod, String referenceNo, String remark, String idempotencyKey);
|
||||
String paymentMethod, String referenceNo, LocalDate actualPaymentDate,
|
||||
String paymentReceipt, String source, String remark, String idempotencyKey);
|
||||
|
||||
PaymentResultDto processPartialPayment(Long applicationId, BigDecimal amount, Long operatorId,
|
||||
String paymentMethod, String referenceNo, String remark, String idempotencyKey);
|
||||
String paymentMethod, String referenceNo, LocalDate actualPaymentDate,
|
||||
String paymentReceipt, String source, String remark, String idempotencyKey);
|
||||
|
||||
PaymentResultDto verifyPayment(Long paymentId, Long checkerId);
|
||||
|
||||
PaymentResultDto rejectPayment(Long paymentId, Long checkerId, String rejectionCode);
|
||||
|
||||
PaymentResultDto attachPaymentReceipt(Long paymentId, String paymentReceipt, Long operatorId);
|
||||
|
||||
List<PaymentRecordDto> getPaymentHistoryByOperator(Long operatorId);
|
||||
|
||||
PaymentRecordDto getPaymentByNo(String paymentNo, Long operatorId);
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ public class ReimbursementApplicantDepartmentService {
|
||||
}
|
||||
if (user.getDepartmentId() != null && !externalDepartmentRequired) return user.getDepartmentId();
|
||||
if (!"ACTIVE".equalsIgnoreCase(user.getStatus())) {
|
||||
throw new BusinessException("当前用户状态不可发起报销", 403);
|
||||
throw new BusinessException("当前用户状态不可发起付款申请", 403);
|
||||
}
|
||||
if (!same(deploymentTenant, requestTenant) || !same(deploymentTenant, user.getTenantId())
|
||||
|| !same(deploymentOrganizationId, user.getOrganizationId())) {
|
||||
|
||||
@@ -121,7 +121,7 @@ public class ReimbursementAttachmentService {
|
||||
row.setUploadStatus(UPLOADED);
|
||||
ReimAttachment saved = attachments.saveAndFlush(row);
|
||||
if (financeAudit != null) financeAudit.business("reimbursement.attachment.upload", userId,
|
||||
"REIM_ATTACHMENT", saved.getId(), null, null, null);
|
||||
"PAYMENT_ATTACHMENT", saved.getId(), null, null, null);
|
||||
return dto(saved);
|
||||
});
|
||||
if (result == null) throw new BusinessException("附件上传记录保存失败", 500);
|
||||
@@ -172,7 +172,7 @@ public class ReimbursementAttachmentService {
|
||||
ReimApplication claimedApplication = null;
|
||||
if (row.getApplicationId() != null) {
|
||||
claimedApplication = applications.findByIdForUpdate(row.getApplicationId())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
if (!userId.equals(claimedApplication.getApplicantId())
|
||||
|| !ApplicationStatus.DRAFT.name().equals(claimedApplication.getApplicationStatus()))
|
||||
throw new BusinessException("只能移除暂存附件或本人草稿附件", 409);
|
||||
@@ -182,7 +182,7 @@ public class ReimbursementAttachmentService {
|
||||
attachments.flush();
|
||||
storageCleanup.enqueue(row, "用户主动删除附件");
|
||||
if (financeAudit != null) financeAudit.business("reimbursement.attachment.delete", userId,
|
||||
"REIM_ATTACHMENT", row.getId(), null, null, null);
|
||||
"PAYMENT_ATTACHMENT", row.getId(), null, null, null);
|
||||
if (claimedApplication != null) {
|
||||
claimedApplication.setFeishuFormDisplayValues(forms.buildDisplayValues(claimedApplication));
|
||||
applications.save(claimedApplication);
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.finance.system.dto.TravelApplicationDto;
|
||||
import com.finance.system.entity.FeishuTravelApplication;
|
||||
import com.finance.system.exception.ResourceNotFoundException;
|
||||
import com.finance.system.repository.FeishuTravelApplicationRepository;
|
||||
import com.finance.system.repository.ReimApplicationRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -18,10 +19,13 @@ public class TravelApplicationService {
|
||||
private static final TypeReference<List<String>> STRING_LIST = new TypeReference<List<String>>() { };
|
||||
private final FeishuTravelApplicationRepository repository;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ReimApplicationRepository applicationRepository;
|
||||
|
||||
public TravelApplicationService(FeishuTravelApplicationRepository repository, ObjectMapper objectMapper) {
|
||||
public TravelApplicationService(FeishuTravelApplicationRepository repository, ObjectMapper objectMapper,
|
||||
ReimApplicationRepository applicationRepository) {
|
||||
this.repository = repository;
|
||||
this.objectMapper = objectMapper;
|
||||
this.applicationRepository = applicationRepository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
@@ -49,7 +53,9 @@ public class TravelApplicationService {
|
||||
.destination(value.getDestination()).purpose(value.getPurpose())
|
||||
.startDate(value.getStartDate()).endDate(value.getEndDate())
|
||||
.estimate(value.getEstimatedAmount()).status(value.getStatus())
|
||||
.approvalSystem(value.getApprovalSystem()).syncedAt(value.getSyncedAt()).build();
|
||||
.approvalSystem(value.getApprovalSystem()).syncedAt(value.getSyncedAt())
|
||||
.linkedPaymentApplicationCount(applicationRepository
|
||||
.countByLinkedTravelApplicationIdAndDeletedFalse(value.getId())).build();
|
||||
}
|
||||
|
||||
private List<String> stringList(String json) {
|
||||
|
||||
@@ -100,13 +100,14 @@ public class DashboardServiceImpl implements DashboardService {
|
||||
.title(app.getTitle())
|
||||
.applicantName(applicant != null ? applicant.getRealName() : null)
|
||||
.departmentName(dept != null ? dept.getDeptName() : null)
|
||||
.expenseTypeName(expenseType != null ? expenseType.getTypeName() : null)
|
||||
.category(app.getCategory())
|
||||
.totalAmount(app.getTotalAmount())
|
||||
.paymentScenario(expenseType != null ? expenseType.getTypeName() : null)
|
||||
.paymentScenarioId(app.getExpenseTypeId())
|
||||
.expenseItemCategory(app.getCategory())
|
||||
.requestedAmount(app.getTotalAmount())
|
||||
.applicationStatus(app.getApplicationStatus())
|
||||
.approvalStatus(app.getApprovalStatus())
|
||||
.currentApprovalNode(app.getCurrentApprovalNode())
|
||||
.receiptStatus(app.getReceiptStatus())
|
||||
.financeCheckStatus(app.getReceiptStatus())
|
||||
.paymentStatus(app.getPaymentStatus())
|
||||
.budgetStatus(app.getBudgetStatus())
|
||||
.submitTime(app.getSubmitTime())
|
||||
|
||||
@@ -28,6 +28,7 @@ import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.LockModeType;
|
||||
@@ -58,6 +59,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
private final ReimAttachmentRepository reimAttachmentRepository;
|
||||
private final ReimApprovalRecordRepository reimApprovalRecordRepository;
|
||||
private final ReimPaymentRepository reimPaymentRepository;
|
||||
private final FeishuTravelApplicationRepository feishuTravelApplicationRepository;
|
||||
private final SysApprovalNodeRepository sysApprovalNodeRepository;
|
||||
private final KingdeeConfig kingdeeConfig;
|
||||
private final ReimbursementFormService reimbursementFormService;
|
||||
@@ -76,6 +78,12 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Value("${finance.payment.require-receipt-before-registration:false}")
|
||||
private boolean financeCheckEnabled;
|
||||
|
||||
@Value("${finance.payment.require-independent-review:false}")
|
||||
private boolean independentPaymentReviewEnabled;
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setFeishuApprovalService(FeishuApprovalService feishuApprovalService) {
|
||||
this.feishuApprovalService = feishuApprovalService;
|
||||
@@ -192,9 +200,11 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
|
||||
WorkbenchDto workbench = new WorkbenchDto();
|
||||
workbench.setUser(userProfile);
|
||||
workbench.setReimbursements(summaries);
|
||||
workbench.setPaymentApplications(summaries);
|
||||
workbench.setPayments(paymentDtos);
|
||||
workbench.setStats(stats);
|
||||
workbench.setFinanceCheckEnabled(financeCheckEnabled);
|
||||
workbench.setIndependentPaymentReviewEnabled(independentPaymentReviewEnabled);
|
||||
return workbench;
|
||||
}
|
||||
|
||||
@@ -237,7 +247,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
FinanceScope access = scope(userId, "reimbursement.application", "read");
|
||||
ReimApplication app = reimApplicationRepository.findScopedByApplicationNo(applicationNo, access.getTenantId(),
|
||||
access.code(), access.getActorId(), access.getDepartmentIds()).orElse(null);
|
||||
if (app == null) throw new ResourceNotFoundException("报销申请不存在");
|
||||
if (app == null) throw new ResourceNotFoundException("付款申请不存在");
|
||||
AuthorizationDecision decision = checkApplication(userId, "reimbursement.application", "read", app);
|
||||
return projectDetailWithActions(app, userId, decision);
|
||||
}
|
||||
@@ -255,6 +265,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
// Refresh under the same write lock before deciding whether an automatic
|
||||
// directory mapping is allowed, so a concurrent manual assignment wins.
|
||||
entityManager.refresh(user, LockModeType.PESSIMISTIC_WRITE);
|
||||
normalizePrototypeAliases(request);
|
||||
validateFieldPermissions(request, userId, null, true);
|
||||
validateRequest(request, userId);
|
||||
ReimbursementFormService.PinnedForm pinnedForm = reimbursementFormService.validateForWrite(
|
||||
@@ -276,6 +287,13 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
app.setDepartmentId(departmentId);
|
||||
app.setExpenseTypeId(request.getExpenseTypeId());
|
||||
app.setCategory(request.getCategory());
|
||||
app.setPayerEntityName(request.getPayerEntityName());
|
||||
app.setCostCenterName(request.getCostCenterName());
|
||||
app.setCurrencyCode(request.getCurrencyCode());
|
||||
app.setPaymentReason(request.getPaymentReason());
|
||||
app.setPlannedPaymentDate(request.getPlannedPaymentDate());
|
||||
app.setLinkedTravelApplicationId(validateLinkedTravelApplication(
|
||||
request.getLinkedTravelApplicationId(), userId));
|
||||
app.setTotalAmount(request.getTotalAmount());
|
||||
app.setDescription(request.getDescription());
|
||||
app.setPayeeName(request.getPayeeName());
|
||||
@@ -286,7 +304,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
app.setPaymentStatus(PaymentStatus.UNPAID.name());
|
||||
app.setBudgetStatus(BudgetStatus.PENDING.name());
|
||||
app.setSourceSystem("LOCAL");
|
||||
app.setSourceStatus(kingdeeConfig.isEnabled() ? SyncStatus.PENDING.name() : "NOT_CONFIGURED");
|
||||
app.setSyncStatus(kingdeeConfig.isEnabled() ? SyncStatus.PENDING.name() : "NOT_CONFIGURED");
|
||||
app.setFeishuFormFingerprint(pinnedForm.getFingerprint());
|
||||
app.setFeishuFormSchema(pinnedForm.getSchema());
|
||||
app.setFeishuFormValues(pinnedForm.getValues());
|
||||
@@ -300,8 +318,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
app = reimApplicationRepository.save(app);
|
||||
|
||||
financeAudit.business("reimbursement.application.create", userId,
|
||||
"REIM_APPLICATION", app.getId(), app.getApplicationStatus(), app.getTotalAmount(), null);
|
||||
log.info("创建报销申请: applicationNo={}, userId={}", app.getApplicationNo(), userId);
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getApplicationStatus(), app.getTotalAmount(), null);
|
||||
log.info("创建付款申请: applicationNo={}, userId={}", app.getApplicationNo(), userId);
|
||||
AuthorizationDecision decision = checkApplication(userId, "reimbursement.application", "read", app);
|
||||
return projectDetailWithActions(app, userId, decision);
|
||||
}
|
||||
@@ -313,6 +331,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
FinanceScope access = scope(userId, "reimbursement.application", "edit");
|
||||
ReimApplication app = findScopedForUpdate(id, access);
|
||||
AuthorizationDecision writeDecision = checkApplication(userId, "reimbursement.application", "edit", app);
|
||||
normalizePrototypeAliases(request);
|
||||
mergeProtectedWrite(request, app, writeDecision);
|
||||
ensureNoCreationInProgress(app.getId());
|
||||
if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) {
|
||||
@@ -332,6 +351,15 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
app.setTitle(request.getTitle());
|
||||
app.setExpenseTypeId(request.getExpenseTypeId());
|
||||
app.setCategory(request.getCategory());
|
||||
app.setPayerEntityName(request.getPayerEntityName());
|
||||
app.setCostCenterName(request.getCostCenterName());
|
||||
app.setCurrencyCode(request.getCurrencyCode());
|
||||
app.setPaymentReason(request.getPaymentReason());
|
||||
app.setPlannedPaymentDate(request.getPlannedPaymentDate());
|
||||
if (request.getLinkedTravelApplicationId() != null) {
|
||||
app.setLinkedTravelApplicationId(validateLinkedTravelApplication(
|
||||
request.getLinkedTravelApplicationId(), app.getApplicantId()));
|
||||
}
|
||||
app.setTotalAmount(request.getTotalAmount());
|
||||
app.setDescription(request.getDescription());
|
||||
app.setPayeeName(request.getPayeeName());
|
||||
@@ -361,7 +389,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
app.setReturnReason(null);
|
||||
app = reimApplicationRepository.save(app);
|
||||
financeAudit.business("reimbursement.application.update", userId,
|
||||
"REIM_APPLICATION", app.getId(), app.getApplicationStatus(), app.getTotalAmount(),
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getApplicationStatus(), app.getTotalAmount(),
|
||||
Collections.<String, Object>singletonMap("changedFieldCodes",
|
||||
java.util.Arrays.asList("title", "expenseType", "amount", "payee", "form")));
|
||||
return projectDetailWithActions(app, userId, checkApplication(userId,
|
||||
@@ -381,8 +409,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
checkApplication(userId, "reimbursement.application", "submit", before);
|
||||
ReimApplication app = submissionCoordinator.submit(id, userId, previewToken);
|
||||
financeAudit.business("reimbursement.application.submit", userId,
|
||||
"REIM_APPLICATION", app.getId(), app.getApplicationStatus(), null, null);
|
||||
log.info("提交报销申请: applicationNo={}", app.getApplicationNo());
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getApplicationStatus(), null, null);
|
||||
log.info("提交付款申请: applicationNo={}", app.getApplicationNo());
|
||||
return projectDetailWithActions(app, userId, checkApplication(userId,
|
||||
"reimbursement.application", "read", app));
|
||||
}
|
||||
@@ -404,7 +432,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
try {
|
||||
sodEvaluator.check(operatorId, app.getApplicantId(), "REQUESTER", "RECEIVER");
|
||||
} catch (org.springframework.security.access.AccessDeniedException denied) {
|
||||
financeAudit.sodDenied(operatorId, "REIM_APPLICATION", app.getId(),
|
||||
financeAudit.sodDenied(operatorId, "PAYMENT_APPLICATION", app.getId(),
|
||||
"receipt.receive", "REQUESTER_RECEIVER");
|
||||
throw denied;
|
||||
}
|
||||
@@ -426,17 +454,17 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
// action is deliberately recorded without changing approval or amount.
|
||||
ReimApprovalRecord auditRecord = new ReimApprovalRecord();
|
||||
auditRecord.setApplicationId(app.getId());
|
||||
auditRecord.setNodeName("财务收单");
|
||||
auditRecord.setNodeName("财务核对");
|
||||
auditRecord.setApproverId(operatorId);
|
||||
auditRecord.setAction("RECEIVE");
|
||||
auditRecord.setComment("财务收单完成");
|
||||
auditRecord.setComment("财务核对完成");
|
||||
auditRecord.setActionTime(LocalDateTime.now());
|
||||
reimApprovalRecordRepository.save(auditRecord);
|
||||
|
||||
financeAudit.business("finance.receipt.receive", operatorId,
|
||||
"REIM_APPLICATION", app.getId(), app.getReceiptStatus(), null, null);
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getReceiptStatus(), null, null);
|
||||
|
||||
log.info("财务收单: applicationNo={}, operatorId={}", app.getApplicationNo(), operatorId);
|
||||
log.info("财务核对: applicationNo={}, operatorId={}", app.getApplicationNo(), operatorId);
|
||||
return projectDetail(buildDetail(app), checkApplication(operatorId,
|
||||
"reimbursement.application", "read", app));
|
||||
}
|
||||
@@ -456,7 +484,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
app.setDeleted(true);
|
||||
reimApplicationRepository.save(app);
|
||||
financeAudit.business("reimbursement.application.delete", userId,
|
||||
"REIM_APPLICATION", app.getId(), "DELETED", null, null);
|
||||
"PAYMENT_APPLICATION", app.getId(), "DELETED", null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -489,6 +517,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null;
|
||||
SysExpenseType expenseType = app.getExpenseTypeId() != null ?
|
||||
sysExpenseTypeRepository.findById(app.getExpenseTypeId()).orElse(null) : null;
|
||||
BigDecimal actualPaymentAmount = effectivePaymentAmount(app.getId());
|
||||
BigDecimal payableAmount = approvedAmount(app) != null ? approvedAmount(app) : app.getTotalAmount();
|
||||
|
||||
return ReimApplicationSummary.builder()
|
||||
.id(app.getId())
|
||||
@@ -496,17 +526,28 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
.title(app.getTitle())
|
||||
.applicantName(applicant != null ? applicant.getRealName() : null)
|
||||
.departmentName(dept != null ? dept.getDeptName() : null)
|
||||
.expenseTypeName(expenseType != null ? expenseType.getTypeName() : null)
|
||||
.category(app.getCategory())
|
||||
.totalAmount(app.getTotalAmount())
|
||||
.paymentScenarioId(app.getExpenseTypeId())
|
||||
.paymentScenario(expenseType != null ? expenseType.getTypeName() : null)
|
||||
.expenseItemCategory(app.getCategory())
|
||||
.requestedAmount(app.getTotalAmount())
|
||||
.approvedAmount(approvedAmount(app))
|
||||
.actualPaymentAmount(actualPaymentAmount)
|
||||
.paidAmount(actualPaymentAmount)
|
||||
.remainingAmount(payableAmount.subtract(actualPaymentAmount).max(BigDecimal.ZERO))
|
||||
.payerEntityName(app.getPayerEntityName())
|
||||
.costCenterName(app.getCostCenterName())
|
||||
.currencyCode(app.getCurrencyCode())
|
||||
.paymentReason(app.getPaymentReason())
|
||||
.plannedPaymentDate(app.getPlannedPaymentDate())
|
||||
.linkedTravelApplicationId(app.getLinkedTravelApplicationId())
|
||||
.applicationStatus(app.getApplicationStatus())
|
||||
.approvalStatus(app.getApprovalStatus())
|
||||
.currentApprovalNode(app.getCurrentApprovalNode())
|
||||
.receiptStatus(app.getReceiptStatus())
|
||||
.financeCheckStatus(app.getReceiptStatus())
|
||||
.paymentStatus(app.getPaymentStatus())
|
||||
.budgetStatus(app.getBudgetStatus())
|
||||
.sourceDocNo(app.getSourceDocNo())
|
||||
.sourceStatus(app.getSourceStatus())
|
||||
.syncStatus(app.getSyncStatus())
|
||||
.returnReason(app.getReturnReason())
|
||||
.submitTime(app.getSubmitTime())
|
||||
.createdAt(app.getCreatedAt())
|
||||
@@ -574,9 +615,9 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
private void validateFieldPermissions(CreateApplicationRequest request, Long userId,
|
||||
ReimApplication existing, boolean creating) {
|
||||
checkField(request == null ? null : request.getTotalAmount(), existing == null ? null : existing.getTotalAmount(),
|
||||
userId, "application:amount", creating, "报销金额");
|
||||
userId, "application:amount", creating, "申请付款金额");
|
||||
checkField(request == null ? null : request.getPayeeName(), existing == null ? null : existing.getPayeeName(),
|
||||
userId, "application:payeeName", creating, "收款人");
|
||||
userId, "application:payeeName", creating, "收款方");
|
||||
checkField(request == null ? null : request.getPayeeBankId(), existing == null ? null : existing.getPayeeBankId(),
|
||||
userId, "application:bankAccount", creating, "收款账户");
|
||||
if (!creating && existing != null && !roleService.canEditField(userId, "application:amount")
|
||||
@@ -616,6 +657,68 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
|
||||
private static final BigDecimal MAX_MONEY_AMOUNT = new BigDecimal("99999999.99");
|
||||
|
||||
private void normalizePrototypeAliases(CreateApplicationRequest request) {
|
||||
if (request == null) return;
|
||||
Long legacyScenarioId = request.getExpenseTypeId();
|
||||
Long paymentScenarioId = request.getPaymentScenarioId();
|
||||
if (legacyScenarioId != null && paymentScenarioId != null
|
||||
&& !legacyScenarioId.equals(paymentScenarioId)) {
|
||||
throw new BusinessException("付款情形字段值不一致", 400);
|
||||
}
|
||||
if (legacyScenarioId == null) request.setExpenseTypeId(paymentScenarioId);
|
||||
if (paymentScenarioId == null) request.setPaymentScenarioId(legacyScenarioId);
|
||||
String legacyCategory = trimToNull(request.getCategory());
|
||||
String expenseItemCategory = trimToNull(request.getExpenseItemCategory());
|
||||
if (legacyCategory != null && expenseItemCategory != null
|
||||
&& !legacyCategory.equals(expenseItemCategory)) {
|
||||
throw new BusinessException("费用项目分类字段值不一致", 400);
|
||||
}
|
||||
request.setCategory(legacyCategory != null ? legacyCategory : expenseItemCategory);
|
||||
request.setExpenseItemCategory(expenseItemCategory != null ? expenseItemCategory : legacyCategory);
|
||||
if (request.getItems() != null) for (ExpenseItemDto item : request.getItems()) {
|
||||
if (item == null) continue;
|
||||
String legacyName = trimToNull(item.getCategory());
|
||||
String expenseItemName = trimToNull(item.getExpenseItemName());
|
||||
if (legacyName != null && expenseItemName != null && !legacyName.equals(expenseItemName)) {
|
||||
throw new BusinessException("费用项目名称字段值不一致", 400);
|
||||
}
|
||||
item.setCategory(legacyName != null ? legacyName : expenseItemName);
|
||||
item.setExpenseItemName(expenseItemName != null ? expenseItemName : legacyName);
|
||||
}
|
||||
BigDecimal total = request.getTotalAmount();
|
||||
BigDecimal requested = request.getRequestedAmount();
|
||||
if (total != null && requested != null && total.compareTo(requested) != 0) {
|
||||
throw new BusinessException("申请金额与 requestedAmount 不一致", 400);
|
||||
}
|
||||
if (total == null) request.setTotalAmount(requested);
|
||||
if (requested == null) request.setRequestedAmount(total);
|
||||
if (!hasText(request.getPaymentReason())) request.setPaymentReason(request.getDescription());
|
||||
if (!hasText(request.getDescription())) request.setDescription(request.getPaymentReason());
|
||||
if (!hasText(request.getTitle()) && hasText(request.getPaymentReason())) {
|
||||
String reason = request.getPaymentReason().trim();
|
||||
request.setTitle(reason.length() > 500 ? reason.substring(0, 500) : reason);
|
||||
}
|
||||
request.setPayerEntityName(trimToNull(request.getPayerEntityName()));
|
||||
request.setCostCenterName(trimToNull(request.getCostCenterName()));
|
||||
request.setCurrencyCode(trimToNull(request.getCurrencyCode()) == null
|
||||
? null : request.getCurrencyCode().trim().toUpperCase(java.util.Locale.ROOT));
|
||||
request.setPaymentReason(trimToNull(request.getPaymentReason()));
|
||||
}
|
||||
|
||||
private BigDecimal approvedAmount(ReimApplication app) {
|
||||
if (app == null) return null;
|
||||
if (app.getApprovedAmount() != null) return app.getApprovedAmount();
|
||||
return ApprovalStatus.APPROVED.name().equals(app.getApprovalStatus()) ? app.getTotalAmount() : null;
|
||||
}
|
||||
|
||||
private boolean hasText(String value) {
|
||||
return value != null && !value.trim().isEmpty();
|
||||
}
|
||||
|
||||
private String trimToNull(String value) {
|
||||
return hasText(value) ? value.trim() : null;
|
||||
}
|
||||
|
||||
private void validateRequest(CreateApplicationRequest request, Long userId) {
|
||||
if (request == null || request.getTotalAmount() == null) {
|
||||
throw new BusinessException("请填写申请金额", 400);
|
||||
@@ -624,8 +727,23 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
if (request.getTitle() == null || request.getTitle().trim().isEmpty()) {
|
||||
throw new BusinessException("标题不能为空", 400);
|
||||
}
|
||||
if (!hasText(request.getPayerEntityName())) {
|
||||
throw new BusinessException("付款单位不能为空", 400);
|
||||
}
|
||||
if (!hasText(request.getCostCenterName())) {
|
||||
throw new BusinessException("成本中心不能为空", 400);
|
||||
}
|
||||
if (!hasText(request.getCurrencyCode()) || !request.getCurrencyCode().matches("[A-Z]{3}")) {
|
||||
throw new BusinessException("币种必须使用三位英文代码", 400);
|
||||
}
|
||||
if (!hasText(request.getPaymentReason())) {
|
||||
throw new BusinessException("付款事由不能为空", 400);
|
||||
}
|
||||
if (request.getPlannedPaymentDate() == null) {
|
||||
throw new BusinessException("计划付款日期不能为空", 400);
|
||||
}
|
||||
if (request.getPayeeName() == null || request.getPayeeName().trim().isEmpty()) {
|
||||
throw new BusinessException("收款人不能为空", 400);
|
||||
throw new BusinessException("收款方不能为空", 400);
|
||||
}
|
||||
if (request.getItems() == null || request.getItems().isEmpty()) {
|
||||
throw new BusinessException("费用明细不能为空");
|
||||
@@ -633,7 +751,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
SysExpenseType type = request.getExpenseTypeId() == null ? null :
|
||||
sysExpenseTypeRepository.findById(request.getExpenseTypeId()).orElse(null);
|
||||
if (type == null || (type.getStatus() != null && !"ACTIVE".equalsIgnoreCase(type.getStatus()))) {
|
||||
throw new BusinessException("费用类型不存在或已停用");
|
||||
throw new BusinessException("付款情形不存在或已停用");
|
||||
}
|
||||
BigDecimal sum = BigDecimal.ZERO;
|
||||
int index = 0;
|
||||
@@ -659,6 +777,17 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
}
|
||||
}
|
||||
|
||||
private Long validateLinkedTravelApplication(Long travelApplicationId, Long applicantId) {
|
||||
if (travelApplicationId == null) return null;
|
||||
FeishuTravelApplication travel = feishuTravelApplicationRepository
|
||||
.findByIdAndApplicantUserId(travelApplicationId, applicantId)
|
||||
.orElseThrow(() -> new BusinessException("关联的出差申请不存在或不属于当前申请人", 400));
|
||||
if (!"APPROVED".equalsIgnoreCase(travel.getStatus()) && !"审批通过".equals(travel.getStatus())) {
|
||||
throw new BusinessException("只有审批通过的出差申请可以关联员工报销", 400);
|
||||
}
|
||||
return travel.getId();
|
||||
}
|
||||
|
||||
private void assertMoneyAmount(BigDecimal amount, String label) {
|
||||
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
throw new BusinessException(label + "须大于 0", 400);
|
||||
@@ -678,6 +807,10 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
}
|
||||
BigDecimal sum = items.stream().map(ReimExpenseItem::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
if (sum.compareTo(app.getTotalAmount()) != 0) throw new BusinessException("费用明细合计必须等于总金额");
|
||||
if (!hasText(app.getPayerEntityName()) || !hasText(app.getPaymentReason())
|
||||
|| app.getPlannedPaymentDate() == null) {
|
||||
throw new BusinessException("付款单位、付款事由和计划付款日期必须完整", 400);
|
||||
}
|
||||
if (app.getPayeeBankId() == null || !sysBankAccountRepository.findById(app.getPayeeBankId())
|
||||
.map(b -> app.getApplicantId().equals(b.getUserId())
|
||||
&& "ACTIVE".equalsIgnoreCase(b.getStatus())).orElse(false)) {
|
||||
@@ -740,6 +873,11 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
List<ReimApprovalRecord> approvalRecords = reimApprovalRecordRepository
|
||||
.findByApplicationIdOrderByActionTimeAsc(app.getId());
|
||||
List<ReimPayment> payments = reimPaymentRepository.findByApplicationId(app.getId());
|
||||
BigDecimal actualPaymentAmount = payments.stream()
|
||||
.filter(this::isEffectivePayment)
|
||||
.map(ReimPayment::getPaymentAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal payableAmount = approvedAmount(app) != null ? approvedAmount(app) : app.getTotalAmount();
|
||||
SysBankAccount bank = app.getPayeeBankId() == null ? null
|
||||
: sysBankAccountRepository.findById(app.getPayeeBankId()).orElse(null);
|
||||
SysUser currentApprover = app.getCurrentApproverId() == null ? null
|
||||
@@ -754,24 +892,34 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
.applicantEmployeeNo(applicant != null ? applicant.getEmployeeNo() : null)
|
||||
.departmentId(app.getDepartmentId())
|
||||
.departmentName(dept != null ? dept.getDeptName() : null)
|
||||
.expenseTypeId(app.getExpenseTypeId())
|
||||
.expenseTypeName(expenseType != null ? expenseType.getTypeName() : null)
|
||||
.category(app.getCategory())
|
||||
.totalAmount(app.getTotalAmount())
|
||||
.paymentScenarioId(app.getExpenseTypeId())
|
||||
.paymentScenario(expenseType != null ? expenseType.getTypeName() : null)
|
||||
.expenseItemCategory(app.getCategory())
|
||||
.requestedAmount(app.getTotalAmount())
|
||||
.approvedAmount(approvedAmount(app))
|
||||
.actualPaymentAmount(actualPaymentAmount)
|
||||
.paidAmount(actualPaymentAmount)
|
||||
.remainingAmount(payableAmount.subtract(actualPaymentAmount).max(BigDecimal.ZERO))
|
||||
.payerEntityName(app.getPayerEntityName())
|
||||
.costCenterName(app.getCostCenterName())
|
||||
.currencyCode(app.getCurrencyCode())
|
||||
.paymentReason(app.getPaymentReason())
|
||||
.plannedPaymentDate(app.getPlannedPaymentDate())
|
||||
.linkedTravelApplicationId(app.getLinkedTravelApplicationId())
|
||||
.description(app.getDescription())
|
||||
.applicationStatus(app.getApplicationStatus())
|
||||
.approvalStatus(app.getApprovalStatus())
|
||||
.currentApprovalNode(app.getCurrentApprovalNode())
|
||||
.currentApproverId(app.getCurrentApproverId())
|
||||
.currentApproverName(currentApprover != null ? currentApprover.getRealName() : null)
|
||||
.receiptStatus(app.getReceiptStatus())
|
||||
.financeCheckStatus(app.getReceiptStatus())
|
||||
.paymentStatus(app.getPaymentStatus())
|
||||
.budgetStatus(app.getBudgetStatus())
|
||||
.sourceDocNo(app.getSourceDocNo())
|
||||
.sourceDocType(app.getSourceDocType())
|
||||
.sourceSystem(app.getSourceSystem())
|
||||
.sourceDocDate(app.getSourceDocDate())
|
||||
.sourceStatus(app.getSourceStatus())
|
||||
.syncStatus(app.getSyncStatus())
|
||||
.payeeName(app.getPayeeName())
|
||||
.payeeBankId(app.getPayeeBankId())
|
||||
.bankName(bank != null ? bank.getBankName() : null)
|
||||
@@ -790,6 +938,16 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private BigDecimal effectivePaymentAmount(Long applicationId) {
|
||||
BigDecimal amount = reimPaymentRepository.sumEffectiveAmountByApplicationId(applicationId);
|
||||
return amount == null ? BigDecimal.ZERO : amount;
|
||||
}
|
||||
|
||||
private boolean isEffectivePayment(ReimPayment payment) {
|
||||
return payment != null && ("COMPLETED".equals(payment.getPaymentStatus())
|
||||
|| "PENDING_RECEIPT".equals(payment.getPaymentStatus()));
|
||||
}
|
||||
|
||||
private ReimApplicationDetail.FormSnapshot buildFormSnapshot(ReimApplication app) {
|
||||
if (!org.springframework.util.StringUtils.hasText(app.getFeishuFormSchema())) {
|
||||
return ReimApplicationDetail.FormSnapshot.builder().mode("LEGACY")
|
||||
@@ -810,6 +968,7 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
dto.setId(item.getId());
|
||||
dto.setSeqNo(item.getSeqNo());
|
||||
dto.setExpenseDate(item.getExpenseDate());
|
||||
dto.setExpenseItemName(item.getCategory());
|
||||
dto.setCategory(item.getCategory());
|
||||
dto.setDescription(item.getDescription());
|
||||
dto.setAmount(item.getAmount());
|
||||
@@ -865,10 +1024,17 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
dto.setId(payment.getId());
|
||||
dto.setPaymentNo(payment.getPaymentNo());
|
||||
dto.setPaymentAmount(payment.getPaymentAmount());
|
||||
dto.setActualPaymentAmount(payment.getPaymentAmount());
|
||||
dto.setTotalAmount(payment.getTotalAmount());
|
||||
dto.setPaidAmount(payment.getPaidAmount());
|
||||
dto.setRemainingAmount(payment.getRemainingAmount());
|
||||
dto.setPaymentMethod(payment.getPaymentMethod());
|
||||
dto.setActualPaymentMethod(payment.getPaymentMethod());
|
||||
dto.setReferenceNo(payment.getReferenceNo());
|
||||
dto.setBankTransactionNo(payment.getReferenceNo());
|
||||
dto.setActualPaymentDate(payment.getActualPaymentDate());
|
||||
dto.setPaymentReceipt(payment.getPaymentReceipt());
|
||||
dto.setSource(payment.getResultSource());
|
||||
dto.setPaymentStatus(payment.getPaymentStatus());
|
||||
dto.setOperatorName(operator != null ? operator.getRealName() : null);
|
||||
dto.setPaymentTime(payment.getPaymentTime());
|
||||
@@ -902,13 +1068,13 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
private ReimApplication findScoped(Long id, FinanceScope access) {
|
||||
return reimApplicationRepository.findScopedById(id, access.getTenantId(), access.code(),
|
||||
access.getActorId(), access.getDepartmentIds())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
}
|
||||
|
||||
private ReimApplication findScopedForUpdate(Long id, FinanceScope access) {
|
||||
return reimApplicationRepository.findScopedByIdForUpdate(id, access.getTenantId(), access.code(),
|
||||
access.getActorId(), access.getDepartmentIds())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
}
|
||||
|
||||
private AuthorizationDecision checkApplication(Long actorId, String resource, String action,
|
||||
@@ -935,15 +1101,31 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
|
||||
private void mergeProtectedWrite(CreateApplicationRequest request, ReimApplication current,
|
||||
AuthorizationDecision decision) {
|
||||
if (request == null) return;
|
||||
if (decision.accessFor("title") != FieldAccess.EDIT) request.setTitle(current.getTitle());
|
||||
if (decision.accessFor("expenseTypeId") != FieldAccess.EDIT) request.setExpenseTypeId(current.getExpenseTypeId());
|
||||
if (decision.accessFor("category") != FieldAccess.EDIT) request.setCategory(current.getCategory());
|
||||
if (decision.accessFor("title") != FieldAccess.EDIT) {
|
||||
request.setTitle(current.getTitle());
|
||||
request.setPayerEntityName(current.getPayerEntityName());
|
||||
request.setCostCenterName(current.getCostCenterName());
|
||||
request.setCurrencyCode(current.getCurrencyCode());
|
||||
request.setPlannedPaymentDate(current.getPlannedPaymentDate());
|
||||
}
|
||||
if (decision.accessFor("expenseTypeId") != FieldAccess.EDIT) {
|
||||
request.setExpenseTypeId(current.getExpenseTypeId());
|
||||
request.setPaymentScenarioId(current.getExpenseTypeId());
|
||||
}
|
||||
if (decision.accessFor("category") != FieldAccess.EDIT) {
|
||||
request.setCategory(current.getCategory());
|
||||
request.setExpenseItemCategory(current.getCategory());
|
||||
}
|
||||
if (decision.accessFor("totalAmount") != FieldAccess.EDIT) {
|
||||
request.setTotalAmount(current.getTotalAmount());
|
||||
request.setRequestedAmount(current.getTotalAmount());
|
||||
request.setItems(reimExpenseItemRepository.findByApplicationId(current.getId()).stream()
|
||||
.map(this::buildExpenseItem).collect(Collectors.toList()));
|
||||
}
|
||||
if (decision.accessFor("description") != FieldAccess.EDIT) request.setDescription(current.getDescription());
|
||||
if (decision.accessFor("description") != FieldAccess.EDIT) {
|
||||
request.setDescription(current.getDescription());
|
||||
request.setPaymentReason(current.getPaymentReason());
|
||||
}
|
||||
if (decision.accessFor("payeeName") != FieldAccess.EDIT) request.setPayeeName(current.getPayeeName());
|
||||
if (decision.accessFor("payeeBankId") != FieldAccess.EDIT) request.setPayeeBankId(current.getPayeeBankId());
|
||||
if (decision.accessFor("formSnapshot") != FieldAccess.EDIT) {
|
||||
|
||||
@@ -104,13 +104,14 @@ public class ReimApprovalServiceImpl implements ReimApprovalService {
|
||||
app.setCurrentApprovalNode("流程已完成");
|
||||
app.setCurrentApproverId(null);
|
||||
app.setApproveTime(LocalDateTime.now());
|
||||
app.setApprovedAmount(app.getTotalAmount());
|
||||
app.setBudgetStatus(BudgetStatus.EXECUTED.name());
|
||||
}
|
||||
|
||||
reimApplicationRepository.save(app);
|
||||
|
||||
financeAudit.business("finance.approval.approve", approverId,
|
||||
"REIM_APPLICATION", app.getId(), app.getApprovalStatus(), null, null);
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getApprovalStatus(), null, null);
|
||||
|
||||
log.info("审批通过: applicationNo={}, approverId={}", app.getApplicationNo(), approverId);
|
||||
return buildApprovalRecordDto(record);
|
||||
@@ -142,13 +143,15 @@ public class ReimApprovalServiceImpl implements ReimApprovalService {
|
||||
// 退回申请
|
||||
app.setApplicationStatus(com.finance.system.enums.ApplicationStatus.DRAFT.name());
|
||||
app.setApprovalStatus(ApprovalStatus.REJECTED.name());
|
||||
app.setApprovedAmount(null);
|
||||
app.setApproveTime(null);
|
||||
app.setReturnReason(returnReason != null ? returnReason : comment);
|
||||
app.setCurrentApprovalNode("申请人补充材料");
|
||||
app.setCurrentApproverId(app.getApplicantId());
|
||||
reimApplicationRepository.save(app);
|
||||
|
||||
financeAudit.business("finance.approval.reject", approverId,
|
||||
"REIM_APPLICATION", app.getId(), app.getApprovalStatus(), null, null);
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getApprovalStatus(), null, null);
|
||||
|
||||
log.info("审批退回: applicationNo={}, approverId={}, reason={}",
|
||||
app.getApplicationNo(), approverId, returnReason);
|
||||
@@ -179,7 +182,7 @@ public class ReimApprovalServiceImpl implements ReimApprovalService {
|
||||
reimApplicationRepository.save(app);
|
||||
|
||||
financeAudit.business("finance.approval.transfer", fromUserId,
|
||||
"REIM_APPLICATION", app.getId(), app.getApprovalStatus(), null,
|
||||
"PAYMENT_APPLICATION", app.getId(), app.getApprovalStatus(), null,
|
||||
java.util.Collections.<String, Object>singletonMap("targetActorId", toUserId));
|
||||
|
||||
return buildApprovalRecordDto(record);
|
||||
@@ -242,7 +245,7 @@ public class ReimApprovalServiceImpl implements ReimApprovalService {
|
||||
FinanceScope access = financeAuthorization.scope(actorId, "finance.approval", "decide");
|
||||
return reimApplicationRepository.findScopedByIdForUpdate(applicationId, access.getTenantId(),
|
||||
access.code(), access.getActorId(), access.getDepartmentIds())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
}
|
||||
|
||||
private void checkSod(Long actorId, Long relatedActorId, String leftDuty, String rightDuty,
|
||||
@@ -250,7 +253,7 @@ public class ReimApprovalServiceImpl implements ReimApprovalService {
|
||||
try {
|
||||
sodEvaluator.check(actorId, relatedActorId, leftDuty, rightDuty);
|
||||
} catch (org.springframework.security.access.AccessDeniedException denied) {
|
||||
financeAudit.sodDenied(actorId, "REIM_APPLICATION", app.getId(),
|
||||
financeAudit.sodDenied(actorId, "PAYMENT_APPLICATION", app.getId(),
|
||||
operation, leftDuty + "_" + rightDuty);
|
||||
throw denied;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import com.finance.system.security.finance.FinanceFieldProjection;
|
||||
import com.finance.system.security.finance.FinanceScope;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
@@ -48,6 +49,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final SysBankAccountRepository sysBankAccountRepository;
|
||||
private final SysDepartmentRepository sysDepartmentRepository;
|
||||
private final SysExpenseTypeRepository sysExpenseTypeRepository;
|
||||
private final PaymentIdempotencyLock paymentIdempotencyLock;
|
||||
private final RoleService roleService;
|
||||
private final FinanceAuthorization financeAuthorization;
|
||||
@@ -55,6 +57,12 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
private final SegregationOfDutiesEvaluator sodEvaluator;
|
||||
private final FinanceAuditEvents financeAudit;
|
||||
|
||||
@Value("${finance.payment.require-receipt-before-registration:false}")
|
||||
private boolean requireReceiptBeforeRegistration;
|
||||
|
||||
@Value("${finance.payment.require-independent-review:false}")
|
||||
private boolean requireIndependentReview;
|
||||
|
||||
@Override
|
||||
public Page<PaymentTaskDto> getPendingPayments(Long operatorId, Pageable pageable) {
|
||||
requirePaymentPermission(operatorId);
|
||||
@@ -82,10 +90,10 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
.findByApplicationIdOrderByActionTimeAsc(applicationId);
|
||||
|
||||
BigDecimal paidAmount = payments.stream()
|
||||
.filter(p -> "COMPLETED".equals(p.getPaymentStatus()))
|
||||
.filter(this::isEffectivePayment)
|
||||
.map(ReimPayment::getPaymentAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal remainingAmount = app.getTotalAmount().subtract(paidAmount);
|
||||
BigDecimal remainingAmount = payableAmount(app).subtract(paidAmount);
|
||||
|
||||
PaymentDetailDto dto = new PaymentDetailDto();
|
||||
dto.setId(app.getId());
|
||||
@@ -93,8 +101,16 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
dto.setTitle(app.getTitle());
|
||||
dto.setPayeeName(app.getPayeeName());
|
||||
dto.setDepartmentName(dept != null ? dept.getDeptName() : app.getPayeeName());
|
||||
dto.setPayerEntityName(app.getPayerEntityName());
|
||||
dto.setCostCenterName(app.getCostCenterName());
|
||||
dto.setCurrencyCode(app.getCurrencyCode());
|
||||
dto.setPaymentReason(app.getPaymentReason());
|
||||
dto.setPlannedPaymentDate(app.getPlannedPaymentDate());
|
||||
dto.setTotalAmount(app.getTotalAmount());
|
||||
dto.setRequestedAmount(app.getTotalAmount());
|
||||
dto.setApprovedAmount(payableAmount(app));
|
||||
dto.setPaidAmount(paidAmount);
|
||||
dto.setActualPaymentAmount(paidAmount);
|
||||
dto.setRemainingAmount(remainingAmount);
|
||||
dto.setPaymentStatus(app.getPaymentStatus());
|
||||
|
||||
@@ -129,14 +145,15 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
@Override
|
||||
@Transactional
|
||||
public PaymentResultDto executePayment(Long applicationId, BigDecimal amount, Long operatorId,
|
||||
String paymentMethod, String referenceNo, String remark,
|
||||
String idempotencyKey) {
|
||||
String paymentMethod, String referenceNo, LocalDate actualPaymentDate,
|
||||
String paymentReceipt, String source, String remark, String idempotencyKey) {
|
||||
return executePaymentInternal(applicationId, amount, operatorId, paymentMethod, referenceNo,
|
||||
remark, idempotencyKey, true, false);
|
||||
actualPaymentDate, paymentReceipt, source, remark, idempotencyKey, true, false);
|
||||
}
|
||||
|
||||
private PaymentResultDto executePaymentInternal(Long applicationId, BigDecimal amount, Long operatorId,
|
||||
String paymentMethod, String referenceNo, String remark,
|
||||
String paymentMethod, String referenceNo, LocalDate actualPaymentDate,
|
||||
String paymentReceipt, String source, String remark,
|
||||
String idempotencyKey, boolean requireFullPayment, boolean partialOnly) {
|
||||
requirePaymentPermission(operatorId);
|
||||
if (operatorId == null || !operatorId.equals(AuditUtil.getCurrentUserId())) {
|
||||
@@ -146,6 +163,27 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
String normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey);
|
||||
ReimApplication app = findApplication(applicationId, access, true);
|
||||
financeAuthorization.checkApplication(operatorId, "finance.payment", "register", app);
|
||||
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
throw new BusinessException("付款金额必须大于0");
|
||||
}
|
||||
if (actualPaymentDate == null) throw new BadRequestException("实际付款日期不能为空");
|
||||
if (actualPaymentDate.isAfter(LocalDate.now())) {
|
||||
throw new BadRequestException("实际付款日期不能晚于今天");
|
||||
}
|
||||
if (!hasText(paymentMethod)) throw new BadRequestException("实际付款方式不能为空");
|
||||
String normalizedMethod = normalizePaymentMethod(paymentMethod);
|
||||
String normalizedReferenceNo = trimToNull(referenceNo);
|
||||
String normalizedReceipt = trimToNull(paymentReceipt);
|
||||
String normalizedSource = normalizeSource(source);
|
||||
if (normalizedMethod.length() > 50) {
|
||||
throw new BadRequestException("实际付款方式长度不能超过50个字符");
|
||||
}
|
||||
if (normalizedReferenceNo != null && normalizedReferenceNo.length() > 100) {
|
||||
throw new BadRequestException("银行流水号长度不能超过100个字符");
|
||||
}
|
||||
if (normalizedReceipt != null && normalizedReceipt.length() > 500) {
|
||||
throw new BadRequestException("付款回单引用长度不能超过500个字符");
|
||||
}
|
||||
if (normalizedIdempotencyKey != null) {
|
||||
// Acquire the transaction-scoped database lock before
|
||||
// reading the key. This serializes claims across application rows.
|
||||
@@ -153,7 +191,8 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
ReimPayment existing = reimPaymentRepository.findByIdempotencyKey(normalizedIdempotencyKey);
|
||||
if (existing != null) {
|
||||
if (!sameIdempotentRequest(existing, applicationId, amount, operatorId,
|
||||
paymentMethod, referenceNo, remark)) {
|
||||
normalizedMethod, normalizedReferenceNo, actualPaymentDate,
|
||||
normalizedReceipt, normalizedSource, remark)) {
|
||||
throw new BusinessException("幂等键已用于其他付款请求", 409);
|
||||
}
|
||||
return buildPaymentResult(existing);
|
||||
@@ -163,8 +202,8 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
if (!"APPROVED".equals(app.getApprovalStatus())) {
|
||||
throw new BusinessException("申请未通过审批,无法付款");
|
||||
}
|
||||
if (!"RECEIVED".equals(app.getReceiptStatus())) {
|
||||
throw new BusinessException("申请尚未完成财务收单,无法付款");
|
||||
if (requireReceiptBeforeRegistration && !"RECEIVED".equals(app.getReceiptStatus())) {
|
||||
throw new BusinessException("申请尚未完成财务核对,无法登记付款结果");
|
||||
}
|
||||
checkSod(operatorId, app.getApplicantId(), "REQUESTER", "PAYER", app, "payment.register");
|
||||
for (ReimApprovalRecord approval : reimApprovalRecordRepository
|
||||
@@ -173,15 +212,12 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
app, "payment.register");
|
||||
}
|
||||
|
||||
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
throw new BusinessException("付款金额必须大于0");
|
||||
}
|
||||
idempotencyKey = normalizedIdempotencyKey;
|
||||
|
||||
// 计算已付金额
|
||||
List<ReimPayment> existingPayments = reimPaymentRepository.findByApplicationId(applicationId);
|
||||
BigDecimal paidAmount = existingPayments.stream()
|
||||
.filter(p -> "COMPLETED".equals(p.getPaymentStatus()))
|
||||
.filter(this::isEffectivePayment)
|
||||
.map(ReimPayment::getPaymentAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal pendingAmount = existingPayments.stream()
|
||||
@@ -189,7 +225,8 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
.map(ReimPayment::getPaymentAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
BigDecimal remaining = app.getTotalAmount().subtract(paidAmount).subtract(pendingAmount);
|
||||
BigDecimal approvedAmount = payableAmount(app);
|
||||
BigDecimal remaining = approvedAmount.subtract(paidAmount).subtract(pendingAmount);
|
||||
|
||||
if (amount.compareTo(remaining) > 0) {
|
||||
throw new BusinessException("付款金额超过剩余未付金额");
|
||||
@@ -208,46 +245,65 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
payment.setApplicationId(applicationId);
|
||||
payment.setPayeeId(app.getApplicantId());
|
||||
payment.setPayeeBankId(app.getPayeeBankId());
|
||||
payment.setTotalAmount(app.getTotalAmount());
|
||||
payment.setTotalAmount(approvedAmount);
|
||||
payment.setPaymentAmount(amount);
|
||||
payment.setPaidAmount(paidAmount.add(amount));
|
||||
payment.setRemainingAmount(remaining.subtract(amount));
|
||||
payment.setPaymentMethod(paymentMethod == null || paymentMethod.trim().isEmpty()
|
||||
? "BANK_TRANSFER" : paymentMethod.trim());
|
||||
payment.setReferenceNo(referenceNo);
|
||||
payment.setPaymentMethod(normalizedMethod);
|
||||
payment.setReferenceNo(normalizedReferenceNo);
|
||||
payment.setActualPaymentDate(actualPaymentDate);
|
||||
payment.setPaymentReceipt(normalizedReceipt);
|
||||
payment.setResultSource(normalizedSource);
|
||||
payment.setBankAccountNo(null); // never persist a full account number
|
||||
payment.setOperatorId(operatorId);
|
||||
payment.setMakerId(operatorId);
|
||||
payment.setPaymentStatus("PENDING_REVIEW");
|
||||
payment.setPaymentTime(null);
|
||||
String recordedStatus = requireIndependentReview
|
||||
? "PENDING_REVIEW"
|
||||
: (hasText(normalizedReceipt) ? "COMPLETED" : "PENDING_RECEIPT");
|
||||
payment.setPaymentStatus(recordedStatus);
|
||||
payment.setPaymentTime(requireIndependentReview ? null : LocalDateTime.now());
|
||||
payment.setIdempotencyKey(idempotencyKey);
|
||||
payment.setRemark(remark);
|
||||
payment.setDeleted(false);
|
||||
payment = reimPaymentRepository.save(payment);
|
||||
|
||||
if (!requireIndependentReview) {
|
||||
updateApplicationPaymentState(app);
|
||||
}
|
||||
|
||||
financeAudit.business("finance.payment.register", operatorId,
|
||||
"REIM_PAYMENT", payment.getId(), payment.getPaymentStatus(), amount, null);
|
||||
log.info("付款待复核: paymentNo={}, applicationNo={}, amount={}",
|
||||
payment.getPaymentNo(), app.getApplicationNo(), amount);
|
||||
"PAYMENT_RESULT", payment.getId(), payment.getPaymentStatus(), amount, null);
|
||||
log.info("付款结果已登记: paymentNo={}, applicationNo={}, amount={}, status={}",
|
||||
payment.getPaymentNo(), app.getApplicationNo(), amount, recordedStatus);
|
||||
|
||||
PaymentResultDto result = new PaymentResultDto();
|
||||
result.setPaymentNo(payment.getPaymentNo());
|
||||
result.setAmount(amount);
|
||||
result.setPaymentStatus("PENDING_REVIEW");
|
||||
result.setMessage("付款登记成功,等待独立复核");
|
||||
result.setActualPaymentAmount(amount);
|
||||
result.setActualPaymentDate(actualPaymentDate);
|
||||
result.setActualPaymentMethod(normalizedMethod);
|
||||
result.setBankTransactionNo(normalizedReferenceNo);
|
||||
result.setPaymentReceipt(normalizedReceipt);
|
||||
result.setSource(normalizedSource);
|
||||
result.setPaymentStatus(recordedStatus);
|
||||
result.setMessage("PENDING_REVIEW".equals(recordedStatus)
|
||||
? "付款结果已登记,等待独立复核"
|
||||
: ("PENDING_RECEIPT".equals(recordedStatus)
|
||||
? "付款结果已登记,待补付款回单"
|
||||
: "付款结果已登记"));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public PaymentResultDto processPartialPayment(Long applicationId, BigDecimal amount, Long operatorId,
|
||||
String paymentMethod, String referenceNo, String remark,
|
||||
String paymentMethod, String referenceNo, LocalDate actualPaymentDate,
|
||||
String paymentReceipt, String source, String remark,
|
||||
String idempotencyKey) {
|
||||
// Keep all state and amount checks behind the application row lock. This
|
||||
// also makes an idempotent retry return its original result before any
|
||||
// duplicate validation can reject it.
|
||||
return executePaymentInternal(applicationId, amount, operatorId, paymentMethod, referenceNo,
|
||||
remark, idempotencyKey, false, true);
|
||||
actualPaymentDate, paymentReceipt, source, remark, idempotencyKey, false, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -259,7 +315,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
ReimPayment payment = findPaymentForUpdate(paymentId, access);
|
||||
ReimApplication app = findApplication(payment.getApplicationId(), access, true);
|
||||
financeAuthorization.checkApplication(checkerId, "finance.payment", "review", app);
|
||||
if ("COMPLETED".equals(payment.getPaymentStatus())) return buildPaymentResult(payment);
|
||||
if (isEffectivePayment(payment)) return buildPaymentResult(payment);
|
||||
if (!"PENDING_REVIEW".equals(payment.getPaymentStatus())) {
|
||||
throw new BusinessException("付款记录不在待复核状态", 409);
|
||||
}
|
||||
@@ -273,13 +329,15 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
payment.setCheckerId(checkerId);
|
||||
payment.setVerifiedAt(LocalDateTime.now());
|
||||
payment.setPaymentTime(payment.getVerifiedAt());
|
||||
payment.setPaymentStatus("COMPLETED");
|
||||
payment.setPaymentStatus(hasText(payment.getPaymentReceipt()) ? "COMPLETED" : "PENDING_RECEIPT");
|
||||
reimPaymentRepository.save(payment);
|
||||
updateApplicationPaymentState(app);
|
||||
financeAudit.business("finance.payment.verify", checkerId,
|
||||
"REIM_PAYMENT", payment.getId(), payment.getPaymentStatus(), payment.getPaymentAmount(), null);
|
||||
return PaymentResultDto.builder().paymentNo(payment.getPaymentNo()).amount(payment.getPaymentAmount())
|
||||
.paymentStatus(payment.getPaymentStatus()).message("付款复核通过").build();
|
||||
"PAYMENT_RESULT", payment.getId(), payment.getPaymentStatus(), payment.getPaymentAmount(), null);
|
||||
PaymentResultDto result = buildPaymentResult(payment);
|
||||
result.setMessage("COMPLETED".equals(payment.getPaymentStatus())
|
||||
? "付款复核通过" : "付款复核通过,待补付款回单");
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -312,12 +370,43 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
payment.setPaymentStatus("REJECTED");
|
||||
reimPaymentRepository.save(payment);
|
||||
financeAudit.business("finance.payment.reject", checkerId,
|
||||
"REIM_PAYMENT", payment.getId(), payment.getPaymentStatus(), null,
|
||||
"PAYMENT_RESULT", payment.getId(), payment.getPaymentStatus(), null,
|
||||
java.util.Collections.<String, Object>singletonMap("rejectionCode", rejectionCode));
|
||||
return PaymentResultDto.builder().paymentNo(payment.getPaymentNo()).amount(payment.getPaymentAmount())
|
||||
return PaymentResultDto.builder().paymentNo(payment.getPaymentNo()).actualPaymentAmount(payment.getPaymentAmount())
|
||||
.paymentStatus(payment.getPaymentStatus()).message("付款已拒绝").build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public PaymentResultDto attachPaymentReceipt(Long paymentId, String paymentReceipt, Long operatorId) {
|
||||
requirePaymentPermission(operatorId);
|
||||
requireCurrentActor(operatorId);
|
||||
String normalizedReceipt = trimToNull(paymentReceipt);
|
||||
if (normalizedReceipt == null) throw new BadRequestException("付款回单引用不能为空");
|
||||
if (normalizedReceipt.length() > 500) {
|
||||
throw new BadRequestException("付款回单引用长度不能超过500个字符");
|
||||
}
|
||||
FinanceScope access = scope(operatorId, "finance.payment", "register");
|
||||
ReimPayment payment = findPaymentForUpdate(paymentId, access);
|
||||
ReimApplication app = findApplication(payment.getApplicationId(), access, true);
|
||||
financeAuthorization.checkApplication(operatorId, "finance.payment", "register", app);
|
||||
if ("COMPLETED".equals(payment.getPaymentStatus())
|
||||
&& normalizedReceipt.equals(payment.getPaymentReceipt())) {
|
||||
return buildPaymentResult(payment);
|
||||
}
|
||||
if (!"PENDING_RECEIPT".equals(payment.getPaymentStatus())) {
|
||||
throw new BusinessException("仅待补回单的付款记录可以补录回单", 409);
|
||||
}
|
||||
payment.setPaymentReceipt(normalizedReceipt);
|
||||
payment.setPaymentStatus("COMPLETED");
|
||||
reimPaymentRepository.save(payment);
|
||||
financeAudit.business("finance.payment.receipt.attach", operatorId,
|
||||
"PAYMENT_RESULT", payment.getId(), payment.getPaymentStatus(), payment.getPaymentAmount(), null);
|
||||
PaymentResultDto result = buildPaymentResult(payment);
|
||||
result.setMessage("付款回单已补录");
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PaymentRecordDto> getPaymentHistoryByOperator(Long operatorId) {
|
||||
requirePaymentPermission(operatorId);
|
||||
@@ -346,13 +435,18 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
}
|
||||
|
||||
private boolean sameIdempotentRequest(ReimPayment existing, Long applicationId, BigDecimal amount,
|
||||
Long operatorId, String paymentMethod, String referenceNo, String remark) {
|
||||
Long operatorId, String paymentMethod, String referenceNo,
|
||||
LocalDate actualPaymentDate, String paymentReceipt,
|
||||
String source, String remark) {
|
||||
return java.util.Objects.equals(existing.getApplicationId(), applicationId)
|
||||
&& java.util.Objects.equals(existing.getOperatorId(), operatorId)
|
||||
&& sameAmount(existing.getPaymentAmount(), amount)
|
||||
&& java.util.Objects.equals(normalizePaymentMethod(existing.getPaymentMethod()),
|
||||
normalizePaymentMethod(paymentMethod))
|
||||
&& java.util.Objects.equals(existing.getReferenceNo(), referenceNo)
|
||||
&& java.util.Objects.equals(existing.getActualPaymentDate(), actualPaymentDate)
|
||||
&& java.util.Objects.equals(existing.getPaymentReceipt(), paymentReceipt)
|
||||
&& java.util.Objects.equals(existing.getResultSource(), source)
|
||||
&& java.util.Objects.equals(existing.getRemark(), remark);
|
||||
}
|
||||
|
||||
@@ -380,10 +474,10 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
|
||||
List<ReimPayment> payments = reimPaymentRepository.findByApplicationId(app.getId());
|
||||
BigDecimal paidAmount = payments.stream()
|
||||
.filter(p -> "COMPLETED".equals(p.getPaymentStatus()))
|
||||
.filter(this::isEffectivePayment)
|
||||
.map(ReimPayment::getPaymentAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal remaining = app.getTotalAmount().subtract(paidAmount);
|
||||
BigDecimal remaining = payableAmount(app).subtract(paidAmount);
|
||||
|
||||
PaymentTaskDto dto = new PaymentTaskDto();
|
||||
dto.setId(app.getId());
|
||||
@@ -392,8 +486,20 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
dto.setTitle(app.getTitle());
|
||||
dto.setPayeeName(app.getPayeeName());
|
||||
dto.setDepartmentName(dept != null ? dept.getDeptName() : null);
|
||||
SysExpenseType expenseType = app.getExpenseTypeId() != null
|
||||
? sysExpenseTypeRepository.findById(app.getExpenseTypeId()).orElse(null) : null;
|
||||
dto.setExpenseTypeName(expenseType != null ? expenseType.getTypeName() : null);
|
||||
dto.setPaymentScenario(expenseType != null ? expenseType.getTypeName() : null);
|
||||
dto.setPayerEntityName(app.getPayerEntityName());
|
||||
dto.setCostCenterName(app.getCostCenterName());
|
||||
dto.setCurrencyCode(app.getCurrencyCode());
|
||||
dto.setPaymentReason(app.getPaymentReason());
|
||||
dto.setPlannedPaymentDate(app.getPlannedPaymentDate());
|
||||
dto.setTotalAmount(app.getTotalAmount());
|
||||
dto.setRequestedAmount(app.getTotalAmount());
|
||||
dto.setApprovedAmount(payableAmount(app));
|
||||
dto.setPaidAmount(paidAmount);
|
||||
dto.setActualPaymentAmount(paidAmount);
|
||||
dto.setRemainingAmount(remaining);
|
||||
dto.setPaymentStatus(app.getPaymentStatus());
|
||||
dto.setReceiptStatus(app.getReceiptStatus());
|
||||
@@ -431,11 +537,17 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
dto.setApplicationId(payment.getApplicationId());
|
||||
dto.setPaymentNo(payment.getPaymentNo());
|
||||
dto.setPaymentAmount(payment.getPaymentAmount());
|
||||
dto.setActualPaymentAmount(payment.getPaymentAmount());
|
||||
dto.setTotalAmount(payment.getTotalAmount());
|
||||
dto.setPaidAmount(payment.getPaidAmount());
|
||||
dto.setRemainingAmount(payment.getRemainingAmount());
|
||||
dto.setPaymentMethod(payment.getPaymentMethod());
|
||||
dto.setActualPaymentMethod(payment.getPaymentMethod());
|
||||
dto.setReferenceNo(payment.getReferenceNo());
|
||||
dto.setBankTransactionNo(payment.getReferenceNo());
|
||||
dto.setActualPaymentDate(payment.getActualPaymentDate());
|
||||
dto.setPaymentReceipt(payment.getPaymentReceipt());
|
||||
dto.setSource(payment.getResultSource());
|
||||
dto.setPaymentStatus(payment.getPaymentStatus());
|
||||
dto.setOperatorName(operator != null ? operator.getRealName() : null);
|
||||
dto.setPaymentTime(payment.getPaymentTime());
|
||||
@@ -446,7 +558,13 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
|
||||
private PaymentResultDto buildPaymentResult(ReimPayment payment) {
|
||||
return PaymentResultDto.builder().paymentNo(payment.getPaymentNo())
|
||||
.amount(payment.getPaymentAmount()).paymentStatus(payment.getPaymentStatus())
|
||||
.actualPaymentAmount(payment.getPaymentAmount())
|
||||
.actualPaymentDate(payment.getActualPaymentDate())
|
||||
.actualPaymentMethod(payment.getPaymentMethod())
|
||||
.bankTransactionNo(payment.getReferenceNo())
|
||||
.paymentReceipt(payment.getPaymentReceipt())
|
||||
.source(payment.getResultSource())
|
||||
.paymentStatus(payment.getPaymentStatus())
|
||||
.message("重复请求,返回原付款结果").build();
|
||||
}
|
||||
|
||||
@@ -481,7 +599,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
access.code(), access.getActorId(), access.getDepartmentIds())
|
||||
: reimApplicationRepository.findScopedById(applicationId, access.getTenantId(),
|
||||
access.code(), access.getActorId(), access.getDepartmentIds()))
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
}
|
||||
|
||||
private ReimPayment findPaymentForUpdate(Long paymentId, FinanceScope access) {
|
||||
@@ -491,9 +609,9 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
|
||||
private void updateApplicationPaymentState(ReimApplication app) {
|
||||
BigDecimal completed = reimPaymentRepository.findByApplicationId(app.getId()).stream()
|
||||
.filter(payment -> "COMPLETED".equals(payment.getPaymentStatus()))
|
||||
.filter(this::isEffectivePayment)
|
||||
.map(ReimPayment::getPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
app.setPaymentStatus(completed.compareTo(app.getTotalAmount()) >= 0
|
||||
app.setPaymentStatus(completed.compareTo(payableAmount(app)) >= 0
|
||||
? PaymentStatus.PAID.name()
|
||||
: (completed.signum() > 0 ? PaymentStatus.PARTIAL.name() : PaymentStatus.UNPAID.name()));
|
||||
reimApplicationRepository.save(app);
|
||||
@@ -510,7 +628,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
try {
|
||||
sodEvaluator.check(actorId, relatedActorId, leftDuty, rightDuty);
|
||||
} catch (AccessDeniedException denied) {
|
||||
financeAudit.sodDenied(actorId, "REIM_APPLICATION", app.getId(),
|
||||
financeAudit.sodDenied(actorId, "PAYMENT_APPLICATION", app.getId(),
|
||||
operation, leftDuty + "_" + rightDuty);
|
||||
throw denied;
|
||||
}
|
||||
@@ -527,7 +645,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
private boolean canRegister(Long actorId, ReimApplication application) {
|
||||
if (actorId == null || application == null
|
||||
|| !"APPROVED".equals(application.getApprovalStatus())
|
||||
|| !"RECEIVED".equals(application.getReceiptStatus())) return false;
|
||||
|| (requireReceiptBeforeRegistration && !"RECEIVED".equals(application.getReceiptStatus()))) return false;
|
||||
if (!financeAuthorization.canApplication(actorId, "finance.payment", "register", application)) return false;
|
||||
if (!sodAllowed(actorId, application.getApplicantId(), "REQUESTER", "PAYER")) return false;
|
||||
for (ReimApprovalRecord approval : reimApprovalRecordRepository
|
||||
@@ -558,6 +676,10 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
List<String> actions = new ArrayList<>();
|
||||
if (canVerify) actions.add("PAYMENT_VERIFY");
|
||||
if (canReject) actions.add("PAYMENT_REJECT");
|
||||
if ("PENDING_RECEIPT".equals(payment.getPaymentStatus())
|
||||
&& financeAuthorization.canApplication(actorId, "finance.payment", "register", application)) {
|
||||
actions.add("PAYMENT_RECEIPT_ATTACH");
|
||||
}
|
||||
dto.setAvailableActions(Collections.unmodifiableList(actions));
|
||||
dto.setCanVerify(canVerify);
|
||||
dto.setCanReject(canReject);
|
||||
@@ -571,4 +693,35 @@ public class ReimPaymentServiceImpl implements ReimPaymentService {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isEffectivePayment(ReimPayment payment) {
|
||||
return payment != null && ("COMPLETED".equals(payment.getPaymentStatus())
|
||||
|| "PENDING_RECEIPT".equals(payment.getPaymentStatus()));
|
||||
}
|
||||
|
||||
private BigDecimal payableAmount(ReimApplication application) {
|
||||
return application.getApprovedAmount() != null
|
||||
? application.getApprovedAmount() : application.getTotalAmount();
|
||||
}
|
||||
|
||||
private String normalizeSource(String source) {
|
||||
String normalized = trimToNull(source);
|
||||
if (normalized == null) return "MANUAL";
|
||||
normalized = normalized.toUpperCase(java.util.Locale.ROOT);
|
||||
if ("EXTERNAL_CALLBACK".equals(normalized)) normalized = "EXTERNAL_SYSTEM";
|
||||
if (!"MANUAL".equals(normalized) && !"EXTERNAL_SYSTEM".equals(normalized)) {
|
||||
throw new BadRequestException("付款结果来源仅支持 MANUAL 或 EXTERNAL_SYSTEM");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private boolean hasText(String value) {
|
||||
return value != null && !value.trim().isEmpty();
|
||||
}
|
||||
|
||||
private String trimToNull(String value) {
|
||||
if (value == null) return null;
|
||||
String trimmed = value.trim();
|
||||
return trimmed.isEmpty() ? null : trimmed;
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -41,7 +41,7 @@ public class ReimbursementSubmissionStateService {
|
||||
@Transactional
|
||||
public PreparedSubmission prepare(Long applicationId, Long userId, String rawToken) {
|
||||
ReimApplication app = applications.findByIdForUpdate(applicationId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
requirePermission(userId);
|
||||
if (!Objects.equals(userId, app.getApplicantId()))
|
||||
throw new org.springframework.security.access.AccessDeniedException("只能操作本人申请");
|
||||
@@ -128,7 +128,7 @@ public class ReimbursementSubmissionStateService {
|
||||
@Transactional
|
||||
public void recordRemoteCreated(PreparedSubmission prepared, String instanceCode) {
|
||||
applications.findByIdForUpdate(prepared.applicationId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(prepared.applicationId)
|
||||
.orElseThrow(() -> new BusinessException("飞书创建意图不存在,请重试", 409));
|
||||
if (!Objects.equals(mapping.getRequestUuid(), prepared.requestUuid))
|
||||
@@ -144,7 +144,7 @@ public class ReimbursementSubmissionStateService {
|
||||
@Transactional
|
||||
public ReimApplication finalizeSubmission(PreparedSubmission prepared) {
|
||||
ReimApplication app = applications.findByIdForUpdate(prepared.applicationId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("报销申请不存在"));
|
||||
.orElseThrow(() -> new ResourceNotFoundException("付款申请不存在"));
|
||||
IntFeishuApproval mapping = null;
|
||||
if ("FEISHU".equals(prepared.source)) {
|
||||
mapping = approvals.findByApplicationIdForUpdate(app.getId())
|
||||
@@ -238,11 +238,11 @@ public class ReimbursementSubmissionStateService {
|
||||
private void applyApprovalStatus(ReimApplication app, String status) {
|
||||
app.setApprovalStatus(status); app.setCurrentApproverId(null);
|
||||
if (ApprovalStatus.PENDING.name().equals(status)) {
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode("飞书审批"); app.setApproveTime(null);
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode("飞书审批"); app.setApproveTime(null); app.setApprovedAmount(null);
|
||||
} else if (ApprovalStatus.APPROVED.name().equals(status)) {
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode(null); app.setApproveTime(LocalDateTime.now());
|
||||
app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode(null); app.setApproveTime(LocalDateTime.now()); app.setApprovedAmount(app.getTotalAmount());
|
||||
} else if (ApprovalStatus.REJECTED.name().equals(status) || ApprovalStatus.CANCELLED.name().equals(status)) {
|
||||
app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setCurrentApprovalNode(null); app.setApproveTime(null);
|
||||
app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setCurrentApprovalNode(null); app.setApproveTime(null); app.setApprovedAmount(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,11 @@ app:
|
||||
# Explicit, non-destructive backfill. It adds encrypted values but does not
|
||||
# clear legacy plaintext; final clearing requires a separately approved run.
|
||||
legacy-backfill-enabled: ${APP_BANK_ACCOUNT_LEGACY_BACKFILL_ENABLED:false}
|
||||
finance:
|
||||
payment:
|
||||
# 付款前财务核对门禁默认开启;付款后的银行回单缺失会单独标记为待补回单。
|
||||
require-receipt-before-registration: ${FINANCE_PAYMENT_REQUIRE_RECEIPT_BEFORE_REGISTRATION:false}
|
||||
require-independent-review: ${FINANCE_PAYMENT_REQUIRE_INDEPENDENT_REVIEW:false}
|
||||
kingdee:
|
||||
# System account for sync/query. Employee write ops require bound accounts.
|
||||
enabled: ${KINGDEE_ENABLED:false}
|
||||
|
||||
@@ -13,6 +13,8 @@ class FinancialBusinessRulesTest {
|
||||
@Test void payeeTypeAndIdentityAreExclusive() {
|
||||
assertDoesNotThrow(() -> FinancialBusinessRules.payee("EMPLOYEE", 1L, null));
|
||||
assertDoesNotThrow(() -> FinancialBusinessRules.payee("SUPPLIER", null, "credit"));
|
||||
assertDoesNotThrow(() -> FinancialBusinessRules.payee("GOVERNMENT", null, null,
|
||||
"GOV-000001", "91320000TEST000001"));
|
||||
for (String type : new String[]{null, "", "OTHER"}) {
|
||||
invalid(() -> FinancialBusinessRules.payee(type, 1L, null));
|
||||
}
|
||||
@@ -22,6 +24,9 @@ class FinancialBusinessRulesTest {
|
||||
invalid(() -> FinancialBusinessRules.payee("SUPPLIER", null, null));
|
||||
invalid(() -> FinancialBusinessRules.payee("SUPPLIER", 1L, "credit"));
|
||||
invalid(() -> FinancialBusinessRules.payee("SUPPLIER", 1L, null));
|
||||
invalid(() -> FinancialBusinessRules.payee("GOVERNMENT", null, null, null, "91320000TEST000001"));
|
||||
invalid(() -> FinancialBusinessRules.payee("GOVERNMENT", null, "credit",
|
||||
"GOV-000001", "91320000TEST000001"));
|
||||
}
|
||||
|
||||
@Test void currencyBoundaries() {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.finance.system.security;
|
||||
|
||||
import com.finance.system.authorization.AuthorizationDecision;
|
||||
import com.finance.system.authorization.AuthorizationRequest;
|
||||
import com.finance.system.authorization.AuthorizationService;
|
||||
import com.finance.system.authorization.ResourceContext;
|
||||
import com.finance.system.authorization.SubjectContext;
|
||||
import com.finance.system.service.RoleService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PermissionCheckerTest {
|
||||
|
||||
@Test
|
||||
void integrationCheckCarriesTrustedTenantAndOrganizationBoundary() {
|
||||
AuthorizationService authorization = mock(AuthorizationService.class);
|
||||
PermissionChecker checker = new PermissionChecker(mock(RoleService.class), authorization);
|
||||
UserPrincipal principal = UserPrincipal.builder().id(6L).tenantId("default")
|
||||
.organizationId(1L).departmentId(2L).build();
|
||||
SubjectContext subject = SubjectContext.builder().userId(6L).tenantId("default")
|
||||
.organizationId(1L).departmentId(2L).build();
|
||||
Authentication authentication = new UsernamePasswordAuthenticationToken(
|
||||
principal, null, Collections.emptyList());
|
||||
when(authorization.subject(principal)).thenReturn(subject);
|
||||
when(authorization.check(any(AuthorizationRequest.class)))
|
||||
.thenReturn(AuthorizationDecision.builder().allowed(true).build());
|
||||
|
||||
assertThat(checker.check(authentication, "integration.feishu", "read")).isTrue();
|
||||
|
||||
ArgumentCaptor<AuthorizationRequest> request = ArgumentCaptor.forClass(AuthorizationRequest.class);
|
||||
verify(authorization).check(request.capture());
|
||||
ResourceContext context = request.getValue().getResourceContext();
|
||||
assertThat(context.getResourceType()).isEqualTo("integration.feishu");
|
||||
assertThat(context.getTenantId()).isEqualTo("default");
|
||||
assertThat(context.getOrganizationId()).isEqualTo(1L);
|
||||
assertThat(context.getOwnerId()).isNull();
|
||||
assertThat(context.getDepartmentId()).isNull();
|
||||
assertThat(context.isExplicitGlobal()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamCheckRemainsExplicitlyGlobal() {
|
||||
AuthorizationService authorization = mock(AuthorizationService.class);
|
||||
PermissionChecker checker = new PermissionChecker(mock(RoleService.class), authorization);
|
||||
UserPrincipal principal = UserPrincipal.builder().id(6L).tenantId("default")
|
||||
.organizationId(1L).build();
|
||||
SubjectContext subject = SubjectContext.builder().userId(6L).tenantId("default")
|
||||
.organizationId(1L).build();
|
||||
Authentication authentication = new UsernamePasswordAuthenticationToken(
|
||||
principal, null, Collections.emptyList());
|
||||
when(authorization.subject(principal)).thenReturn(subject);
|
||||
when(authorization.check(any(AuthorizationRequest.class)))
|
||||
.thenReturn(AuthorizationDecision.builder().allowed(true).build());
|
||||
|
||||
assertThat(checker.check(authentication, "iam.role", "read")).isTrue();
|
||||
|
||||
ArgumentCaptor<AuthorizationRequest> request = ArgumentCaptor.forClass(AuthorizationRequest.class);
|
||||
verify(authorization).check(request.capture());
|
||||
assertThat(request.getValue().getResourceContext().isExplicitGlobal()).isTrue();
|
||||
}
|
||||
}
|
||||