From c3cdb9e2d62543643894301b6a2bf460a1a3b109 Mon Sep 17 00:00:00 2001 From: Weiming Date: Tue, 1 Dec 2026 17:18:54 +0800 Subject: [PATCH] =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E5=AE=89=E5=85=A8=E5=8A=A0?= =?UTF-8?q?=E5=AF=86=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 32 +- README.md | 57 +- pom.xml | 22 +- run.bat | 2 +- .../system/FinanceSystemApplication.java | 2 +- .../feishu/FeishuApprovalFileClient.java | 4 +- .../adapter/feishu/FeishuAuthService.java | 430 +++++++-- .../system/adapter/feishu/FeishuConfig.java | 6 +- .../feishu/FeishuDefinitionSyncService.java | 2 +- .../feishu/FeishuDirectoryAccessService.java | 8 +- .../FeishuDirectoryBindingProvisioner.java | 29 +- .../feishu/FeishuDirectoryBootstrap.java | 2 +- .../adapter/feishu/FeishuDirectoryClient.java | 47 +- .../feishu/FeishuDirectoryCurrentStore.java | 96 +- .../feishu/FeishuDirectoryPublisher.java | 16 +- .../feishu/FeishuDirectoryRunStore.java | 112 ++- .../feishu/FeishuDirectoryService.java | 29 +- .../feishu/FeishuDirectorySyncDispatcher.java | 2 +- .../feishu/FeishuDirectorySyncWorker.java | 2 +- .../feishu/FeishuLoginPersistenceService.java | 39 +- .../feishu/FeishuOAuthStateOriginStore.java | 81 ++ .../feishu/FeishuTenantTokenService.java | 39 +- .../adapter/feishu/FeishuTokenResponse.java | 4 +- .../feishu/FeishuUserProvisioningService.java | 170 ++++ .../adapter/feishu/FeishuUserResponse.java | 4 +- .../feishu/ReimbursementCanonicalizer.java | 5 +- .../system/adapter/kingdee/KingdeeClient.java | 8 +- .../system/audit/AuditDeliveryService.java | 128 +++ .../com/finance/system/audit/AuditEvent.java | 83 ++ .../system/audit/AuditEventAppender.java | 19 + .../system/audit/AuditEventCommand.java | 39 + .../system/audit/AuditEventPolicy.java | 154 +++ .../system/audit/AuditEventRepository.java | 14 + .../audit/AuditEventSchemaContributor.java | 8 + .../audit/AuditEventSchemaRegistry.java | 158 ++++ .../system/audit/AuditEventService.java | 118 +++ .../system/audit/AuditInstanceIdentity.java | 27 + .../audit/AuditIntegrityProperties.java | 200 ++++ .../audit/AuditIntegrityScanLeaseService.java | 19 + .../system/audit/AuditIntegrityScanState.java | 38 + .../AuditIntegrityScanStateRepository.java | 23 + .../system/audit/AuditIntegrityService.java | 147 +++ .../system/audit/AuditIntegrityVerifier.java | 131 +++ .../com/finance/system/audit/AuditOutbox.java | 71 ++ .../system/audit/AuditOutboxClaimService.java | 23 + .../system/audit/AuditOutboxDispatcher.java | 47 + .../system/audit/AuditOutboxRepository.java | 56 ++ .../com/finance/system/audit/AuditPort.java | 10 + .../AuditReliabilityHealthIndicator.java | 60 ++ .../system/audit/AuditReliabilityMetrics.java | 59 ++ .../audit/AuditReliabilityProperties.java | 26 + .../audit/AuditReliabilitySnapshot.java | 19 + .../AuditReliabilitySnapshotProvider.java | 78 ++ .../system/audit/query/AuditEventView.java | 33 + .../audit/query/AuditQueryAuthorization.java | 58 ++ .../audit/query/AuditQueryRepository.java | 31 + .../system/audit/query/AuditQueryScope.java | 11 + .../system/audit/query/AuditQueryService.java | 78 ++ .../system/audit/query/CursorPage.java | 16 + .../AuthorizationAdminService.java | 470 ++++++++++ .../AuthorizationAssignmentSource.java | 9 + .../AuthorizationAuditSchemaContributor.java | 40 + .../AuthorizationBindingDto.java | 22 + .../AuthorizationBindingPageDto.java | 16 + .../AuthorizationBindingQueryRequest.java | 23 + .../AuthorizationCapabilitiesDto.java | 52 + .../AuthorizationCatalogVersionEntity.java | 23 + ...AuthorizationCatalogVersionRepository.java | 15 + .../AuthorizationController.java | 159 ++++ .../authorization/AuthorizationDecision.java | 26 + .../AuthorizationDenialAuditService.java | 73 ++ .../AuthorizationFieldRuleEntity.java | 21 + .../AuthorizationFieldRuleRepository.java | 12 + .../authorization/AuthorizationMode.java | 6 + ...uthorizationPermissionPolicyMapEntity.java | 42 + ...rizationPermissionPolicyMapRepository.java | 10 + .../authorization/AuthorizationPolicyDto.java | 29 + .../AuthorizationPolicyEntity.java | 54 ++ .../AuthorizationPolicyEvaluator.java | 157 ++++ .../AuthorizationPolicyRepository.java | 9 + .../AuthorizationPolicyRequest.java | 55 ++ .../AuthorizationPolicyVersionEntity.java | 19 + .../AuthorizationPolicyVersionRepository.java | 11 + .../AuthorizationProperties.java | 17 + .../authorization/AuthorizationRequest.java | 13 + .../AuthorizationRolePolicyEntity.java | 41 + .../AuthorizationRolePolicyRepository.java | 30 + ...AuthorizationRoleProfileVersionEntity.java | 21 + ...orizationRoleProfileVersionRepository.java | 21 + .../authorization/AuthorizationService.java | 339 +++++++ .../AuthorizationShadowMetrics.java | 38 + .../AuthorizationSodRuleEntity.java | 29 + .../AuthorizationSodRuleRepository.java | 9 + ...AuthorizationSubjectRoleBindingEntity.java | 41 + ...orizationSubjectRoleBindingRepository.java | 23 + .../AuthorizationSubjectType.java | 6 + .../system/authorization/DataScope.java | 11 + .../system/authorization/EffectivePolicy.java | 20 + .../system/authorization/FieldAccess.java | 24 + .../LegacyPermissionAdapter.java | 61 ++ .../PermissionPolicyMappingType.java | 6 + .../system/authorization/PolicyEffect.java | 6 + .../system/authorization/PolicyRiskLevel.java | 8 + .../system/authorization/ResourceContext.java | 32 + .../RoleAuthorizationProfileDto.java | 16 + .../RoleAuthorizationProfileService.java | 206 ++++ .../RoleAuthorizationSummaryDto.java | 17 + .../authorization/RolePermissionAccess.java | 5 + .../SegregationOfDutiesEvaluator.java | 32 + .../system/authorization/SubjectContext.java | 26 + ...UpdateRoleAuthorizationProfileRequest.java | 23 + .../finance/system/config/AsyncConfig.java | 10 +- .../system/config/FrontendOriginPolicy.java | 114 +++ .../system/config/LocalDataInitializer.java | 25 +- .../finance/system/config/SecurityConfig.java | 22 +- .../com/finance/system/config/WebConfig.java | 28 +- .../controller/AccountsPayableController.java | 12 +- .../controller/ApplicationController.java | 268 ------ .../controller/AuditEventQueryController.java | 41 + .../system/controller/AuthController.java | 13 +- .../controller/BusinessConfigController.java | 88 ++ .../system/controller/CashierController.java | 27 +- .../controller/DashboardController.java | 4 +- .../FeishuApprovalDefinitionController.java | 21 +- .../controller/FeishuAuthController.java | 66 +- .../controller/FeishuDirectoryController.java | 54 +- .../IntegrationConfigController.java | 25 +- .../KingdeeAccountBindingController.java | 43 +- .../KingdeeSyncConfigController.java | 48 +- .../system/controller/LogController.java | 84 +- .../system/controller/MetadataController.java | 73 +- .../controller/PayeeAccountController.java | 137 +++ .../system/controller/PaymentController.java | 202 ---- .../controller/ReimApplicationController.java | 8 +- .../system/controller/RoleController.java | 61 +- .../controller/ScheduledTaskController.java | 29 +- .../TravelApplicationController.java | 35 + .../controller/UserGroupController.java | 20 +- .../finance/system/dto/PayeeAccountDto.java | 28 + .../system/dto/PayeeAccountRequest.java | 31 + .../dto/PayeeInitialAccountRequest.java | 22 + .../finance/system/dto/PayeeSubjectDto.java | 23 + .../system/dto/PayeeSubjectRequest.java | 33 + .../com/finance/system/dto/PayeeUserDto.java | 11 + .../finance/system/dto/PaymentDetailDto.java | 8 +- .../finance/system/dto/PaymentRecordDto.java | 7 + .../system/dto/PaymentReviewRequest.java | 15 + .../finance/system/dto/PaymentTaskDto.java | 8 +- .../system/dto/ReimApplicationDetail.java | 5 + .../system/dto/ReimApplicationSummary.java | 5 +- .../system/dto/TransferApprovalRequest.java | 14 + .../system/dto/TravelApplicationDto.java | 31 + .../com/finance/system/dto/UserProfile.java | 1 + .../entity/FeishuTravelApplication.java | 48 + .../system/entity/FileStorageCleanupTask.java | 79 ++ .../system/entity/IntFeishuApproval.java | 18 - .../system/entity/ReimApplication.java | 9 + .../system/entity/ReimApprovalRecord.java | 3 - .../finance/system/entity/ReimAttachment.java | 8 +- .../finance/system/entity/ReimInvoice.java | 6 - .../finance/system/entity/ReimPayment.java | 22 + .../system/entity/SysApiAccessLog.java | 27 +- .../finance/system/entity/SysBankAccount.java | 26 +- .../com/finance/system/entity/SysBudget.java | 64 -- .../finance/system/entity/SysExpenseType.java | 3 - .../system/entity/SysIntegrationConfig.java | 4 +- .../system/entity/SysKingdeeSyncConfig.java | 8 +- .../system/entity/SysKingdeeSyncRun.java | 2 + .../com/finance/system/entity/SysPayee.java | 70 ++ .../finance/system/entity/SysPermission.java | 16 +- .../com/finance/system/entity/SysRole.java | 8 +- .../com/finance/system/entity/SysUser.java | 16 + .../system/entity/SysUserKingdeeAccount.java | 11 +- .../com/finance/system/enums/UserType.java | 7 - .../exception/GlobalExceptionHandler.java | 11 +- .../finance/audit/FinanceAuditEvents.java | 65 ++ .../audit/FinanceAuditSchemaContributor.java | 79 ++ .../finance/rules/FinancialBusinessRules.java | 58 ++ .../audit/IntegrationAuditEvents.java | 102 ++ .../IntegrationAuditSchemaContributor.java | 50 + .../migration/BankAccountLegacyBackfill.java | 70 ++ .../system/migration/MigrationManifest.java | 151 +++ .../migration/MigrationScriptParser.java | 187 ++++ .../migration/MigrationStateMachine.java | 26 + .../migration/MySqlMigrationRunner.java | 887 ++++++++++++++++++ .../system/migration/TenantBackfillTool.java | 267 ++++++ .../V19BoundRolePermissionRecovery.java | 823 ++++++++++++++++ .../migration/V19RolePermissionRecovery.java | 431 +++++++++ .../finance/system/observability/LogText.java | 252 +++++ .../observability/MdcTaskDecorator.java | 26 + .../OutboundTraceInterceptor.java | 31 + .../system/observability/RequestContext.java | 48 + .../observability/RequestContextFilter.java | 96 ++ ...pplicantDepartmentDirectoryRepository.java | 97 +- ...FeishuDirectoryDepartmentBindingStore.java | 83 ++ .../FeishuTravelApplicationRepository.java | 12 + .../FileStorageCleanupTaskRepository.java | 16 + .../repository/ReimApplicationRepository.java | 92 +- .../repository/ReimAttachmentRepository.java | 3 + .../repository/ReimPaymentRepository.java | 51 +- .../repository/SysApiAccessLogRepository.java | 23 +- .../repository/SysBankAccountRepository.java | 18 +- .../repository/SysBudgetRepository.java | 17 - .../SysIntegrationConfigRepository.java | 5 +- .../SysKingdeeSyncConfigRepository.java | 12 +- .../SysKingdeeSyncRunRepository.java | 5 +- .../system/repository/SysPayeeRepository.java | 27 + .../SysUserKingdeeAccountRepository.java | 7 +- .../system/repository/SysUserRepository.java | 8 + .../system/security/ApiAccessLogFilter.java | 173 ++-- .../security/JwtAuthenticationFilter.java | 3 + .../system/security/PermissionChecker.java | 47 +- .../system/security/UserPrincipal.java | 6 + .../finance/BankAccountProtection.java | 193 ++++ .../finance/FinanceAuthorization.java | 151 +++ .../finance/FinanceFieldProjection.java | 126 +++ .../system/security/finance/FinanceScope.java | 18 + .../integration/IntegrationAccess.java | 25 + .../integration/IntegrationAuthorization.java | 66 ++ .../system/service/ApiAccessLogService.java | 114 ++- .../BankAccountPaymentSecretService.java | 71 ++ .../service/IntegrationConfigCrypto.java | 45 +- .../service/IntegrationConfigReader.java | 81 +- .../service/IntegrationConfigService.java | 148 ++- .../service/KingdeeAccountBindingService.java | 158 ++-- .../service/KingdeeAsyncSyncService.java | 30 +- .../service/KingdeeSyncConfigService.java | 115 ++- .../service/KingdeeSyncRunRecovery.java | 2 +- .../system/service/PayeeAccountService.java | 400 ++++++++ .../system/service/PayeeSubjectService.java | 576 ++++++++++++ .../PrototypeBusinessConfigService.java | 639 +++++++++++++ .../service/ReimApplicationService.java | 4 +- .../system/service/ReimPaymentService.java | 4 + ...imbursementApplicantDepartmentService.java | 118 +++ .../ReimbursementAttachmentService.java | 90 +- .../service/ReimbursementFormService.java | 101 +- .../finance/system/service/RoleService.java | 268 +++++- .../system/service/ScheduledTaskPoller.java | 2 +- .../system/service/ScheduledTaskService.java | 175 ++-- .../service/TravelApplicationService.java | 63 ++ .../service/impl/DashboardServiceImpl.java | 108 +-- .../impl/ReimApplicationServiceImpl.java | 369 +++++--- .../service/impl/ReimApprovalServiceImpl.java | 70 +- .../service/impl/ReimPaymentServiceImpl.java | 298 +++++- .../ReimbursementRoutePreviewService.java | 58 +- .../ReimbursementSubmissionStateService.java | 34 +- .../system/storage/AliyunOssFileStorage.java | 129 +++ .../finance/system/storage/FileStorage.java | 12 + .../storage/FileStorageCleanupService.java | 136 +++ .../system/storage/FileStorageManager.java | 57 ++ .../system/storage/FileStorageProperties.java | 33 + .../system/storage/LocalFileStorage.java | 68 ++ .../storage/StorageObjectKeyPolicy.java | 51 + .../finance/system/storage/StoredObject.java | 9 + src/main/resources/application.yml | 79 +- src/main/resources/logback-spring.xml | 43 - .../feishu/FeishuApprovalFormBuilderTest.java | 77 -- .../FeishuDefinitionNormalizerTest.java | 86 -- .../SecureConfigurationDefaultsTest.java | 49 + .../rules/FinancialBusinessRulesTest.java | 81 ++ .../security/ApiAccessLogFilterTest.java | 88 -- .../finance/BankAccountProtectionTest.java | 77 ++ .../finance/SensitiveFieldMaskingTest.java | 20 + .../ReimbursementAttachmentServiceTest.java | 193 ---- ...ReimbursementFormSchemaValidationTest.java | 68 -- .../RoleServicePermissionSecurityTest.java | 116 --- .../ReimApplicationAttachmentDetailTest.java | 67 -- 267 files changed, 15992 insertions(+), 2593 deletions(-) create mode 100644 src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java create mode 100644 src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java create mode 100644 src/main/java/com/finance/system/audit/AuditDeliveryService.java create mode 100644 src/main/java/com/finance/system/audit/AuditEvent.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventAppender.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventCommand.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventPolicy.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventRepository.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java create mode 100644 src/main/java/com/finance/system/audit/AuditEventService.java create mode 100644 src/main/java/com/finance/system/audit/AuditInstanceIdentity.java create mode 100644 src/main/java/com/finance/system/audit/AuditIntegrityProperties.java create mode 100644 src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java create mode 100644 src/main/java/com/finance/system/audit/AuditIntegrityScanState.java create mode 100644 src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java create mode 100644 src/main/java/com/finance/system/audit/AuditIntegrityService.java create mode 100644 src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java create mode 100644 src/main/java/com/finance/system/audit/AuditOutbox.java create mode 100644 src/main/java/com/finance/system/audit/AuditOutboxClaimService.java create mode 100644 src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java create mode 100644 src/main/java/com/finance/system/audit/AuditOutboxRepository.java create mode 100644 src/main/java/com/finance/system/audit/AuditPort.java create mode 100644 src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java create mode 100644 src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java create mode 100644 src/main/java/com/finance/system/audit/AuditReliabilityProperties.java create mode 100644 src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java create mode 100644 src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java create mode 100644 src/main/java/com/finance/system/audit/query/AuditEventView.java create mode 100644 src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java create mode 100644 src/main/java/com/finance/system/audit/query/AuditQueryRepository.java create mode 100644 src/main/java/com/finance/system/audit/query/AuditQueryScope.java create mode 100644 src/main/java/com/finance/system/audit/query/AuditQueryService.java create mode 100644 src/main/java/com/finance/system/audit/query/CursorPage.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationAdminService.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationAssignmentSource.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationAuditSchemaContributor.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationController.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationDecision.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationDenialAuditService.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationFieldRuleEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationFieldRuleRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationMode.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyDto.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyEvaluator.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyRequest.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationProperties.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationRequest.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationRolePolicyEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationRolePolicyRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationService.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationShadowMetrics.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationSodRuleEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationSodRuleRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingEntity.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingRepository.java create mode 100644 src/main/java/com/finance/system/authorization/AuthorizationSubjectType.java create mode 100644 src/main/java/com/finance/system/authorization/DataScope.java create mode 100644 src/main/java/com/finance/system/authorization/EffectivePolicy.java create mode 100644 src/main/java/com/finance/system/authorization/FieldAccess.java create mode 100644 src/main/java/com/finance/system/authorization/LegacyPermissionAdapter.java create mode 100644 src/main/java/com/finance/system/authorization/PermissionPolicyMappingType.java create mode 100644 src/main/java/com/finance/system/authorization/PolicyEffect.java create mode 100644 src/main/java/com/finance/system/authorization/PolicyRiskLevel.java create mode 100644 src/main/java/com/finance/system/authorization/ResourceContext.java create mode 100644 src/main/java/com/finance/system/authorization/RoleAuthorizationProfileDto.java create mode 100644 src/main/java/com/finance/system/authorization/RoleAuthorizationProfileService.java create mode 100644 src/main/java/com/finance/system/authorization/RoleAuthorizationSummaryDto.java create mode 100644 src/main/java/com/finance/system/authorization/RolePermissionAccess.java create mode 100644 src/main/java/com/finance/system/authorization/SegregationOfDutiesEvaluator.java create mode 100644 src/main/java/com/finance/system/authorization/SubjectContext.java create mode 100644 src/main/java/com/finance/system/authorization/UpdateRoleAuthorizationProfileRequest.java create mode 100644 src/main/java/com/finance/system/config/FrontendOriginPolicy.java delete mode 100644 src/main/java/com/finance/system/controller/ApplicationController.java create mode 100644 src/main/java/com/finance/system/controller/AuditEventQueryController.java create mode 100644 src/main/java/com/finance/system/controller/BusinessConfigController.java create mode 100644 src/main/java/com/finance/system/controller/PayeeAccountController.java delete mode 100644 src/main/java/com/finance/system/controller/PaymentController.java create mode 100644 src/main/java/com/finance/system/controller/TravelApplicationController.java create mode 100644 src/main/java/com/finance/system/dto/PayeeAccountDto.java create mode 100644 src/main/java/com/finance/system/dto/PayeeAccountRequest.java create mode 100644 src/main/java/com/finance/system/dto/PayeeInitialAccountRequest.java create mode 100644 src/main/java/com/finance/system/dto/PayeeSubjectDto.java create mode 100644 src/main/java/com/finance/system/dto/PayeeSubjectRequest.java create mode 100644 src/main/java/com/finance/system/dto/PayeeUserDto.java create mode 100644 src/main/java/com/finance/system/dto/PaymentReviewRequest.java create mode 100644 src/main/java/com/finance/system/dto/TransferApprovalRequest.java create mode 100644 src/main/java/com/finance/system/dto/TravelApplicationDto.java create mode 100644 src/main/java/com/finance/system/entity/FeishuTravelApplication.java create mode 100644 src/main/java/com/finance/system/entity/FileStorageCleanupTask.java delete mode 100644 src/main/java/com/finance/system/entity/SysBudget.java create mode 100644 src/main/java/com/finance/system/entity/SysPayee.java delete mode 100644 src/main/java/com/finance/system/enums/UserType.java create mode 100644 src/main/java/com/finance/system/finance/audit/FinanceAuditEvents.java create mode 100644 src/main/java/com/finance/system/finance/audit/FinanceAuditSchemaContributor.java create mode 100644 src/main/java/com/finance/system/finance/rules/FinancialBusinessRules.java create mode 100644 src/main/java/com/finance/system/integration/audit/IntegrationAuditEvents.java create mode 100644 src/main/java/com/finance/system/integration/audit/IntegrationAuditSchemaContributor.java create mode 100644 src/main/java/com/finance/system/migration/BankAccountLegacyBackfill.java create mode 100644 src/main/java/com/finance/system/migration/MigrationManifest.java create mode 100644 src/main/java/com/finance/system/migration/MigrationScriptParser.java create mode 100644 src/main/java/com/finance/system/migration/MigrationStateMachine.java create mode 100644 src/main/java/com/finance/system/migration/MySqlMigrationRunner.java create mode 100644 src/main/java/com/finance/system/migration/TenantBackfillTool.java create mode 100644 src/main/java/com/finance/system/migration/V19BoundRolePermissionRecovery.java create mode 100644 src/main/java/com/finance/system/migration/V19RolePermissionRecovery.java create mode 100644 src/main/java/com/finance/system/observability/LogText.java create mode 100644 src/main/java/com/finance/system/observability/MdcTaskDecorator.java create mode 100644 src/main/java/com/finance/system/observability/OutboundTraceInterceptor.java create mode 100644 src/main/java/com/finance/system/observability/RequestContext.java create mode 100644 src/main/java/com/finance/system/observability/RequestContextFilter.java create mode 100644 src/main/java/com/finance/system/repository/FeishuDirectoryDepartmentBindingStore.java create mode 100644 src/main/java/com/finance/system/repository/FeishuTravelApplicationRepository.java create mode 100644 src/main/java/com/finance/system/repository/FileStorageCleanupTaskRepository.java delete mode 100644 src/main/java/com/finance/system/repository/SysBudgetRepository.java create mode 100644 src/main/java/com/finance/system/repository/SysPayeeRepository.java create mode 100644 src/main/java/com/finance/system/security/finance/BankAccountProtection.java create mode 100644 src/main/java/com/finance/system/security/finance/FinanceAuthorization.java create mode 100644 src/main/java/com/finance/system/security/finance/FinanceFieldProjection.java create mode 100644 src/main/java/com/finance/system/security/finance/FinanceScope.java create mode 100644 src/main/java/com/finance/system/security/integration/IntegrationAccess.java create mode 100644 src/main/java/com/finance/system/security/integration/IntegrationAuthorization.java create mode 100644 src/main/java/com/finance/system/service/BankAccountPaymentSecretService.java create mode 100644 src/main/java/com/finance/system/service/PayeeAccountService.java create mode 100644 src/main/java/com/finance/system/service/PayeeSubjectService.java create mode 100644 src/main/java/com/finance/system/service/PrototypeBusinessConfigService.java create mode 100644 src/main/java/com/finance/system/service/ReimbursementApplicantDepartmentService.java create mode 100644 src/main/java/com/finance/system/service/TravelApplicationService.java create mode 100644 src/main/java/com/finance/system/storage/AliyunOssFileStorage.java create mode 100644 src/main/java/com/finance/system/storage/FileStorage.java create mode 100644 src/main/java/com/finance/system/storage/FileStorageCleanupService.java create mode 100644 src/main/java/com/finance/system/storage/FileStorageManager.java create mode 100644 src/main/java/com/finance/system/storage/FileStorageProperties.java create mode 100644 src/main/java/com/finance/system/storage/LocalFileStorage.java create mode 100644 src/main/java/com/finance/system/storage/StorageObjectKeyPolicy.java create mode 100644 src/main/java/com/finance/system/storage/StoredObject.java delete mode 100644 src/main/resources/logback-spring.xml delete mode 100644 src/test/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilderTest.java delete mode 100644 src/test/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizerTest.java create mode 100644 src/test/java/com/finance/system/config/SecureConfigurationDefaultsTest.java create mode 100644 src/test/java/com/finance/system/finance/rules/FinancialBusinessRulesTest.java delete mode 100644 src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java create mode 100644 src/test/java/com/finance/system/security/finance/BankAccountProtectionTest.java create mode 100644 src/test/java/com/finance/system/security/finance/SensitiveFieldMaskingTest.java delete mode 100644 src/test/java/com/finance/system/service/ReimbursementAttachmentServiceTest.java delete mode 100644 src/test/java/com/finance/system/service/ReimbursementFormSchemaValidationTest.java delete mode 100644 src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java delete mode 100644 src/test/java/com/finance/system/service/impl/ReimApplicationAttachmentDetailTest.java diff --git a/.gitignore b/.gitignore index d70cda5..4ae261a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,34 @@ +# Maven/Java generated output. target/ - -.idea/ -*.iml out/ - *.class -*.log +*.hprof +# Runtime-only data. +logs/ +uploads/ +tmp/ +*.log +*.pid + +# Local configuration; commit application.yml and safe example templates. .env +.env.* +!.env.example application-local.yml application-local.yaml application-local.properties -logs/ -uploads/ -tmp/ - +# IDE, temporary and OS files. +.idea/ +.vscode/ +*.iml +*.tmp +*.temp +*.swp +*.swo +*.bak +*~ .DS_Store Thumbs.db +Desktop.ini diff --git a/README.md b/README.md index 59a71ad..a0a7920 100644 --- a/README.md +++ b/README.md @@ -5,28 +5,57 @@ Before saving any `secret=true` value in `sys_integration_config`, configure longer secret) in the backend runtime environment. Do not commit the key or place a real value in `src/main/resources/application.yml`. +## Payee bank-account protection + +Before creating or changing a payee bank account, provide these runtime secrets: + +- `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. + +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 +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, +explicit data-cleanup authorization, restore evidence, and post-change checks. + For rollout and operations of asynchronous Feishu directory synchronization, -see [`../docs/feishu-directory-sync.md`](../docs/feishu-directory-sync.md). +see [`../financial_system_docs/feishu-directory-sync.md`](../financial_system_docs/feishu-directory-sync.md). ## Database contract -[`../database/init_schema.sql`](../database/init_schema.sql) is the only schema -and bootstrap source. Run it with a MySQL 5.7 client only when +[`../financial_system_database/init_schema.sql`](../financial_system_database/init_schema.sql) is the clean-install +schema/bootstrap snapshot. Run it with a MySQL 8.4 LTS client only when `finance_system` does not yet exist. It intentionally fails against an existing or partial installation. The application keeps Hibernate `ddl-auto: validate` and never changes the application-owned schema during startup. The optional, explicitly authorized Kingdee table-preparation feature can create or alter only its configured target tables; use a narrowly scoped DDL account for that action or have a DBA pre-create those tables and keep the runtime account DML-only. -Existing installations require a separately reviewed DBA release script and -procedure for every in-place upgrade; never run the clean-install script against -them. +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 +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. -The sole script intentionally seeds exactly one environment-specific Feishu -identity and binds it to the built-in `SUPER_ADMIN_GROUP`. Treat the script as an -access-controlled deployment asset, verify that the identity is the intended -operator, and edit it before installing another tenant. The seed has no local -password, mobile, email, or avatar URL; it receives `SUPER_ADMIN` only through -group membership, while `DEFAULT_EMPLOYEE` has no materialized member. Default -passwords, local-profile bootstrap, and first-user auto-promotion remain -prohibited. +The clean-install snapshot creates built-in roles, groups, and group-role links, +but no person, default administrator, or personal group membership. Bootstrap the +first `SUPER_ADMIN` exactly once: the candidate first completes normal Feishu +login, two independent reviewers verify the immutable user ID and tenant against +the corporate directory, and a DBA runs an external, hashed, parameterized +transaction that adds only that `ACTIVE` user to `SUPER_ADMIN_GROUP`, checks the +affected row and unique membership, and records the evidence in the change ticket. +The candidate verifies `/api/auth/me`, the second reviewer closes the one-time +channel, and all later grants use normal IAM administration. Never store the +identity, script parameters, or secrets in the repository and never auto-promote +the first user. `LocalDataInitializer` is loaded only by the `local` profile, and +`finance.local-bootstrap.super-admin.enabled` defaults to `false`; neither the +profile nor the switch is permitted in production. diff --git a/pom.xml b/pom.xml index 1755489..1eb0160 100644 --- a/pom.xml +++ b/pom.xml @@ -12,9 +12,9 @@ com.finance.system - finance-system + financial_system_backend 1.0.0 - finance-system + financial_system_backend 统一费用支付平台 - 员工报销管理系统 @@ -22,7 +22,9 @@ 0.11.5 1.5.5.Final 1.6.15 + 3.18.4 1.18.30 + 6.6 @@ -47,6 +49,15 @@ org.springframework.boot spring-boot-starter-actuator + + io.micrometer + micrometer-registry-prometheus + + + net.logstash.logback + logstash-logback-encoder + ${logstash.logback.encoder.version} + @@ -112,6 +123,13 @@ jackson-datatype-jsr310 + + + com.aliyun.oss + aliyun-sdk-oss + ${aliyun-oss.version} + + org.springframework.boot spring-boot-starter-test diff --git a/run.bat b/run.bat index 3c6ef09..4f69bf2 100644 --- a/run.bat +++ b/run.bat @@ -1,7 +1,7 @@ @echo off set JAVA_HOME=C:\PROGRA~1\Java\OPENJD~1 set MAVEN_HOME=C:\Users\it\.m2 -set PROJECT_DIR=D:\code\Java\financial_system\finance-system\backend +set PROJECT_DIR=D:\code\Java\financial_system\financial_system_backend cd /d "%PROJECT_DIR%" diff --git a/src/main/java/com/finance/system/FinanceSystemApplication.java b/src/main/java/com/finance/system/FinanceSystemApplication.java index 116db1f..0f35d9e 100644 --- a/src/main/java/com/finance/system/FinanceSystemApplication.java +++ b/src/main/java/com/finance/system/FinanceSystemApplication.java @@ -27,7 +27,7 @@ public class FinanceSystemApplication { @EventListener(ApplicationReadyEvent.class) public void logApplicationReady() { - String application = environment.getProperty("spring.application.name", "finance-system"); + String application = environment.getProperty("spring.application.name", "financial_system_backend"); String port = environment.getProperty("local.server.port", environment.getProperty("server.port", "8080")); String[] profiles = environment.getActiveProfiles(); diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java index 780e2d5..9ff71fb 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java @@ -53,10 +53,10 @@ public class FeishuApprovalFileClient { return code.asText(); } catch (BusinessException e) { throw e; } catch (RestClientResponseException e) { - log.warn("Feishu attachment upload rejected: httpStatus={}", e.getRawStatusCode()); + log.warn("飞书附件上传被拒绝: httpStatus={}", e.getRawStatusCode()); throw new BusinessException("飞书附件上传失败,结果可能未知,请勿自动重试", 502); } catch (Exception e) { - log.warn("Feishu attachment upload outcome unknown", e); + log.warn("飞书附件上传结果未知", e); throw new BusinessException("飞书附件上传结果未知,请勿自动重试", 502); } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java index 0850e1a..ef58a13 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java @@ -1,5 +1,7 @@ package com.finance.system.adapter.feishu; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.finance.system.entity.SysUser; import com.finance.system.entity.SysOauthState; import com.finance.system.exception.BusinessException; @@ -14,13 +16,21 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import java.math.BigInteger; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Map; import java.util.Base64; +import java.util.Locale; +import java.util.Objects; @Slf4j @Service @@ -31,6 +41,7 @@ public class FeishuAuthService { private final SysUserRepository sysUserRepository; private final SysOauthStateRepository sysOauthStateRepository; private final RestTemplate restTemplate; + private final FeishuUserProvisioningService userProvisioning; private IntegrationConfigReader integrationConfigReader; @Autowired private FeishuTenantTokenService tenantTokens; @@ -44,6 +55,12 @@ public class FeishuAuthService { private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis"; private static final String FEISHU_AUTH_URL = "https://open.feishu.cn/open-apis/authen/v1/authorize"; + private static final int FEISHU_RATE_LIMIT_CODE = 99991400; + private static final int FEISHU_AUTH_LOGIN_INVALID_CODE = 99991501; + private static final int FEISHU_USER_ACCESS_TOKEN_INVALID_CODE = 99991668; + private static final int FEISHU_ACCESS_TOKEN_BAD_FORMAT_CODE = 99991671; + private static final BigInteger MAX_PROVIDER_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); + private static final ObjectMapper OAUTH_ERROR_MAPPER = new ObjectMapper(); private static final long OAUTH_STATE_TTL_MILLIS = 5 * 60 * 1000L; private final SecureRandom secureRandom = new SecureRandom(); @@ -52,6 +69,22 @@ public class FeishuAuthService { */ @Transactional public AuthUrl buildAuthUrlWithState() { + return buildAuthUrlWithState(redirectUri()); + } + + /** + * Builds an OAuth URL for a trusted frontend origin. Local development + * commonly configures the callback with localhost; that host is unusable + * when another workstation starts the login. In that case only, replace + * the loopback host with the already allowlisted frontend host while + * retaining the configured callback scheme, port and path. + */ + @Transactional + public AuthUrl buildAuthUrlForFrontendOrigin(String trustedFrontendOrigin) { + return buildAuthUrlWithState(resolveRedirectUri(trustedFrontendOrigin)); + } + + private AuthUrl buildAuthUrlWithState(String oauthRedirectUri) { requireConfigured(); long now = System.currentTimeMillis(); // Cleanup is deliberately limited to expired rows. There is no fixed @@ -67,12 +100,45 @@ public class FeishuAuthService { String authUrl = FEISHU_AUTH_URL + "?app_id=" + encode(appId()) - + "&redirect_uri=" + encode(redirectUri()) + + "&redirect_uri=" + encode(oauthRedirectUri) + "&response_type=code" + "&state=" + state; return new AuthUrl(authUrl, state); } + private String resolveRedirectUri(String trustedFrontendOrigin) { + String configuredRedirectUri = redirectUri(); + try { + URI configuredUri = URI.create(configuredRedirectUri); + URI frontendUri = URI.create(trustedFrontendOrigin); + if (!isLoopbackHost(configuredUri.getHost()) || isLoopbackHost(frontendUri.getHost())) { + return configuredRedirectUri; + } + if (frontendUri.getHost() == null || configuredUri.getScheme() == null + || configuredUri.getRawPath() == null || configuredUri.getRawPath().isEmpty()) { + throw new IllegalArgumentException("Incomplete OAuth redirect URI"); + } + return new URI( + configuredUri.getScheme(), + null, + frontendUri.getHost(), + configuredUri.getPort(), + configuredUri.getPath(), + configuredUri.getQuery(), + null).toASCIIString(); + } catch (IllegalArgumentException | URISyntaxException invalid) { + throw new BusinessException("飞书回调地址配置无效", 500); + } + } + + private boolean isLoopbackHost(String host) { + if (!StringUtils.hasText(host)) return false; + String normalized = host.toLowerCase(Locale.ROOT); + return "localhost".equals(normalized) + || "::1".equals(normalized) + || normalized.startsWith("127."); + } + /** Builds the URL while retaining the original service method contract. */ @Transactional public String buildAuthUrl() { @@ -95,9 +161,12 @@ public class FeishuAuthService { || !state.matches("[A-Za-z0-9_-]{43}")) { throw new BusinessException("飞书登录状态缺失,请重新发起授权", 400); } - if (consume && (!StringUtils.hasText(browserState) - || !java.security.MessageDigest.isEqual( - state.getBytes(StandardCharsets.UTF_8), browserState.getBytes(StandardCharsets.UTF_8)))) { + if (StringUtils.hasText(browserState) + && !java.security.MessageDigest.isEqual( + state.getBytes(StandardCharsets.UTF_8), browserState.getBytes(StandardCharsets.UTF_8))) { + throw new BusinessException("飞书登录状态与当前浏览器不匹配,请重新发起授权", 400); + } + if (consume && !StringUtils.hasText(browserState)) { throw new BusinessException("飞书登录状态与当前浏览器不匹配,请重新发起授权", 400); } long now = System.currentTimeMillis(); @@ -112,10 +181,10 @@ public class FeishuAuthService { private void requireConfigured() { if (integrationConfigReader != null && !integrationConfigReader.isEnabled("FEISHU")) { - throw new BusinessException("飞书集成未启用,请先完成配置"); + throw new BusinessException("飞书集成未启用,请先完成配置", 503); } if (!StringUtils.hasText(appId()) || !StringUtils.hasText(appSecret())) { - throw new BusinessException("飞书登录未配置,请在后端运行配置中设置 FEISHU_APP_ID 和 FEISHU_APP_SECRET"); + throw new BusinessException("飞书登录未配置,请联系管理员", 503); } } @@ -155,32 +224,108 @@ public class FeishuAuthService { * 通过授权码获取access_token */ public FeishuTokenResponse getAccessToken(String code) { + if (!StringUtils.hasText(code)) throw invalidAuthorizationCode(); requireConfigured(); String url = FEISHU_OPEN_API + "/authen/v1/access_token"; + String appAccessToken; + try { + appAccessToken = tenantTokens.getAppAccessToken(); + } catch (FeishuTenantTokenService.DiagnosticFailure failure) { + log.warn("飞书应用令牌获取失败 event=feishu.oauth.app_token outcome=failed diagnostic={}", + failure.getDiagnosticCode()); + throw new BusinessException("飞书登录服务暂时不可用,请稍后重试", failure.getStatusCode()); + } catch (BusinessException failure) { + log.warn("飞书应用令牌获取失败 event=feishu.oauth.app_token outcome=failed diagnostic=BUSINESS_FAILURE"); + throw new BusinessException("飞书登录服务暂时不可用,请稍后重试", failure.getStatusCode()); + } catch (RuntimeException failure) { + log.warn("飞书应用令牌请求失败 event=feishu.oauth.app_token outcome=failed diagnostic=TOKEN_REQUEST_FAILED"); + throw oauthUnavailable(); + } + if (!StringUtils.hasText(appAccessToken)) { + log.warn("飞书应用令牌响应无效 event=feishu.oauth.app_token outcome=invalid_response diagnostic=TOKEN_RESPONSE_INVALID"); + throw oauthUpstreamInvalid(); + } + HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); + headers.setBearerAuth(appAccessToken.trim()); - Map requestBody = new java.util.HashMap<>(); - requestBody.put("grant_type", "authorization_code"); - requestBody.put("code", code); - requestBody.put("app_id", appId()); - requestBody.put("app_secret", appSecret()); + Map requestBody = new java.util.HashMap<>(); + requestBody.put("grant_type", "authorization_code"); + requestBody.put("code", code); HttpEntity> request = new HttpEntity<>(requestBody, headers); try { - ResponseEntity response = restTemplate.postForEntity( - url, request, FeishuTokenResponse.class); + ResponseEntity response = restTemplate.exchange( + url, HttpMethod.POST, request, FeishuTokenResponse.class); FeishuTokenResponse tokenResponse = response.getBody(); - if (tokenResponse == null) throw new BusinessException("飞书授权未返回令牌"); - if (tokenResponse.getCode() != 0) throw new BusinessException("飞书授权失败,请稍后重试"); - if (tokenResponse.getData() == null || !StringUtils.hasText(tokenResponse.getData().getAccessToken())) - throw new BusinessException("飞书授权未返回有效令牌"); + if (tokenResponse == null) { + log.warn("飞书授权令牌交换响应为空 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=EMPTY_BODY", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + Integer responseCode = tokenResponse.getCode(); + if (responseCode == null) { + log.warn("飞书授权令牌交换响应缺少服务商状态码 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=PROVIDER_CODE_MISSING", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + if (responseCode != 0) { + Integer providerCode = safeProviderCode(responseCode); + if (providerCode == null) { + log.warn("飞书授权令牌交换响应的服务商状态码无效 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=INVALID_PROVIDER_CODE", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + if (isRateLimited(providerCode)) { + log.warn("飞书授权令牌交换服务不可用 event=feishu.oauth.token_exchange outcome=unavailable httpStatus={} providerCode={}", + response.getStatusCodeValue(), providerCode); + throw oauthUnavailable(); + } + if (isAuthorizationCodeRejected(providerCode)) { + log.warn("飞书授权令牌交换被服务商拒绝 event=feishu.oauth.token_exchange outcome=provider_rejected httpStatus={} providerCode={}", + response.getStatusCodeValue(), providerCode); + throw invalidAuthorizationCode(); + } + log.warn("飞书授权令牌交换上游服务失败 event=feishu.oauth.token_exchange outcome=upstream_failure httpStatus={} providerCode={}", + response.getStatusCodeValue(), providerCode); + throw oauthUpstreamInvalid(); + } + if (tokenResponse.getData() == null + || !StringUtils.hasText(tokenResponse.getData().getAccessToken())) { + log.warn("飞书授权令牌交换响应缺少令牌 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=TOKEN_MISSING", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + log.info("飞书授权令牌交换成功 event=feishu.oauth.token_exchange outcome=success httpStatus={}", + response.getStatusCodeValue()); return tokenResponse; - } catch (Exception e) { - log.warn("Feishu OAuth token exchange failed"); - throw new BusinessException("飞书授权失败,请稍后重试"); + } catch (BusinessException failure) { + throw failure; + } catch (HttpStatusCodeException failure) { + int status = failure.getStatusCode().value(); + Integer providerCode = safeProviderCode(failure.getResponseBodyAsString()); + if (status == 429 || isRateLimited(providerCode)) { + logProviderHttpFailure("feishu.oauth.token_exchange", "unavailable", status, providerCode); + throw oauthUnavailable(); + } + if (isAuthorizationCodeRejected(providerCode)) { + logProviderHttpFailure("feishu.oauth.token_exchange", "provider_rejected", status, providerCode); + throw invalidAuthorizationCode(); + } + logProviderHttpFailure("feishu.oauth.token_exchange", "upstream_failure", status, providerCode); + throw oauthUpstreamInvalid(); + } catch (ResourceAccessException failure) { + log.warn("飞书授权令牌交换网络请求失败 event=feishu.oauth.token_exchange outcome=unavailable diagnostic=NETWORK_FAILURE"); + throw oauthUnavailable(); + } catch (RestClientException failure) { + log.warn("飞书授权令牌交换客户端请求失败 event=feishu.oauth.token_exchange outcome=invalid_response diagnostic=HTTP_CLIENT_FAILURE"); + throw oauthUpstreamInvalid(); + } catch (RuntimeException failure) { + log.warn("飞书授权令牌交换发生未预期的错误 event=feishu.oauth.token_exchange outcome=failed diagnostic=UNEXPECTED_FAILURE"); + throw oauthUnavailable(); } } @@ -188,6 +333,7 @@ public class FeishuAuthService { * 获取用户信息 */ public FeishuUserInfo getUserInfo(String accessToken) { + if (!StringUtils.hasText(accessToken)) throw invalidUserCredential(); String url = FEISHU_OPEN_API + "/authen/v1/user_info"; HttpHeaders headers = new HttpHeaders(); @@ -199,8 +345,43 @@ public class FeishuAuthService { ResponseEntity response = restTemplate.exchange( url, HttpMethod.GET, request, FeishuUserResponse.class); FeishuUserResponse userResponse = response.getBody(); - if (userResponse == null || userResponse.getCode() != 0 || userResponse.getData() == null) - throw new BusinessException("获取用户信息失败"); + if (userResponse == null) { + log.warn("飞书用户信息响应为空 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=EMPTY_BODY", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + Integer responseCode = userResponse.getCode(); + if (responseCode == null) { + log.warn("飞书用户信息响应缺少服务商状态码 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=PROVIDER_CODE_MISSING", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + if (responseCode != 0) { + Integer providerCode = safeProviderCode(responseCode); + if (providerCode == null) { + log.warn("飞书用户信息响应的服务商状态码无效 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=INVALID_PROVIDER_CODE", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } + if (isRateLimited(providerCode)) { + log.warn("飞书用户信息服务不可用 event=feishu.oauth.user_info outcome=unavailable httpStatus={} providerCode={}", + response.getStatusCodeValue(), providerCode); + throw oauthUnavailable(); + } + if (isUserCredentialRejected(providerCode)) { + log.warn("飞书用户信息请求被服务商拒绝 event=feishu.oauth.user_info outcome=provider_rejected httpStatus={} providerCode={}", + response.getStatusCodeValue(), providerCode); + throw invalidUserCredential(); + } + log.warn("飞书用户信息上游服务失败 event=feishu.oauth.user_info outcome=upstream_failure httpStatus={} providerCode={}", + response.getStatusCodeValue(), providerCode); + throw oauthUpstreamInvalid(); + } + if (userResponse.getData() == null) { + log.warn("飞书用户信息响应缺少用户数据 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=USER_DATA_MISSING", + response.getStatusCodeValue()); + throw oauthUpstreamInvalid(); + } FeishuUserInfo userInfo = new FeishuUserInfo(); userInfo.setOpenId(userResponse.getData().getOpenId()); @@ -209,13 +390,95 @@ public class FeishuAuthService { userInfo.setAvatarUrl(userResponse.getData().getAvatarUrl()); userInfo.setEmail(userResponse.getData().getEmail()); userInfo.setMobile(userResponse.getData().getMobile()); + log.info("飞书用户信息获取成功 event=feishu.oauth.user_info outcome=success httpStatus={}", + response.getStatusCodeValue()); return userInfo; - } catch (Exception e) { - log.warn("Feishu OAuth user-info request failed"); - throw new BusinessException("获取用户信息失败"); + } catch (BusinessException failure) { + throw failure; + } catch (HttpStatusCodeException failure) { + int status = failure.getStatusCode().value(); + Integer providerCode = safeProviderCode(failure.getResponseBodyAsString()); + if (status == 429 || isRateLimited(providerCode)) { + logProviderHttpFailure("feishu.oauth.user_info", "unavailable", status, providerCode); + throw oauthUnavailable(); + } + if (isUserCredentialRejected(providerCode)) { + logProviderHttpFailure("feishu.oauth.user_info", "provider_rejected", status, providerCode); + throw invalidUserCredential(); + } + logProviderHttpFailure("feishu.oauth.user_info", "upstream_failure", status, providerCode); + throw oauthUpstreamInvalid(); + } catch (ResourceAccessException failure) { + log.warn("飞书用户信息网络请求失败 event=feishu.oauth.user_info outcome=unavailable diagnostic=NETWORK_FAILURE"); + throw oauthUnavailable(); + } catch (RestClientException failure) { + log.warn("飞书用户信息客户端请求失败 event=feishu.oauth.user_info outcome=invalid_response diagnostic=HTTP_CLIENT_FAILURE"); + throw oauthUpstreamInvalid(); + } catch (RuntimeException failure) { + log.warn("飞书用户信息获取发生未预期的错误 event=feishu.oauth.user_info outcome=failed diagnostic=UNEXPECTED_FAILURE"); + throw oauthUnavailable(); } } + private static void logProviderHttpFailure(String event, String outcome, + int httpStatus, Integer providerCode) { + if (providerCode == null) { + log.warn("飞书服务商 HTTP 请求失败 event={} outcome={} httpStatus={} diagnostic=PROVIDER_HTTP_FAILURE", + event, outcome, httpStatus); + } else { + log.warn("飞书服务商 HTTP 请求失败 event={} outcome={} httpStatus={} providerCode={}", + event, outcome, httpStatus, providerCode); + } + } + + private static Integer safeProviderCode(int code) { + return code > 0 && BigInteger.valueOf(code).compareTo(MAX_PROVIDER_DIAGNOSTIC_CODE) <= 0 + ? code : null; + } + + private static Integer safeProviderCode(String responseBody) { + if (responseBody == null || responseBody.length() > 16384) return null; + try { + JsonNode value = OAUTH_ERROR_MAPPER.readTree(responseBody).path("code"); + if (!value.isIntegralNumber()) return null; + BigInteger code = value.bigIntegerValue(); + if (code.signum() <= 0 || code.compareTo(MAX_PROVIDER_DIAGNOSTIC_CODE) > 0) return null; + return code.intValueExact(); + } catch (Exception ignored) { + return null; + } + } + + private static boolean isRateLimited(Integer providerCode) { + return providerCode != null && providerCode == FEISHU_RATE_LIMIT_CODE; + } + + private static boolean isAuthorizationCodeRejected(Integer providerCode) { + return providerCode != null && providerCode == FEISHU_AUTH_LOGIN_INVALID_CODE; + } + + private static boolean isUserCredentialRejected(Integer providerCode) { + return providerCode != null + && (providerCode == FEISHU_USER_ACCESS_TOKEN_INVALID_CODE + || providerCode == FEISHU_ACCESS_TOKEN_BAD_FORMAT_CODE); + } + + private static BusinessException invalidAuthorizationCode() { + return new BusinessException("飞书授权码无效或已过期,请重新登录", 400); + } + + private static BusinessException invalidUserCredential() { + return new BusinessException("飞书登录凭证无效或已过期,请重新登录", 400); + } + + private static BusinessException oauthUpstreamInvalid() { + return new BusinessException("飞书登录服务响应异常,请稍后重试", 502); + } + + private static BusinessException oauthUnavailable() { + return new BusinessException("飞书登录服务暂时不可用,请稍后重试", 503); + } + /** * 获取tenant_access_token */ @@ -245,59 +508,90 @@ public class FeishuAuthService { // Check ownership before provisioning. user_id is only a duplicate- // ownership guard; it is never used to discover or adopt an account. SysUser otherOwner = userId == null ? null : sysUserRepository.findByFeishuUserId(userId); - if (otherOwner != null && (user == null || !java.util.Objects.equals(user.getId(), otherOwner.getId()))) { - throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403); - } + requireCompatibleBinding(user, otherOwner, userId); if (user == null) { try { - user = provisionEmployee(feishuUserInfo); + user = userProvisioning.provisionEmployee(feishuUserInfo); } catch (DataIntegrityViolationException race) { - // A concurrent first login may have won the unique open_id - // insert. Reuse that committed account instead of exposing - // a database 500 to the OAuth callback. - user = sysUserRepository.findByFeishuOpenId(openId); - if (user == null) throw new BusinessException("飞书账号绑定冲突,请联系管理员", 403); + // The REQUIRES_NEW provisioning transaction has already rolled + // back here. Recovery lookups therefore never run in the failed + // transaction and can observe a committed concurrent winner. + user = recoverProvisioningConflict(openId, userId, race); } } - // Reject dual ownership even when both identifiers on the selected record are populated. - if (otherOwner != null && !java.util.Objects.equals(user.getId(), otherOwner.getId())) - throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403); + // Re-read user_id ownership after provisioning so a concurrent binding + // cannot pass the optimistic checks above. + otherOwner = userId == null ? null : sysUserRepository.findByFeishuUserId(userId); + requireCompatibleBinding(user, otherOwner, userId); // The finalizer rechecks the exact open_id and current ACTIVE status // under a row lock, then performs only the safe profile/binding update. - return loginPersistence.completeOAuth(user.getId(), feishuUserInfo); + try { + return loginPersistence.completeOAuth(user.getId(), feishuUserInfo); + } catch (DataIntegrityViolationException conflict) { + return recoverFinalizationConflict(user, userId, conflict); + } } - /** Provision an ordinary employee; OAuth can never create a privileged account. */ - @Transactional - protected SysUser provisionEmployee(FeishuUserInfo feishuUserInfo) { - String openId = feishuUserInfo.getOpenId().trim(); - SysUser existing = sysUserRepository.findByFeishuOpenId(openId); - if (existing != null) return existing; + private SysUser recoverProvisioningConflict(String openId, String userId, + DataIntegrityViolationException conflict) { + SysUser byOpenId = sysUserRepository.findByFeishuOpenId(openId); + SysUser byUserId = userId == null ? null : sysUserRepository.findByFeishuUserId(userId); + if (byUserId != null && (byOpenId == null || !Objects.equals(byOpenId.getId(), byUserId.getId()))) { + log.warn("飞书账号配置被拒绝:用户编号冲突 event=feishu.oauth.provision outcome=denied conflictType=USER_ID_UNIQUE"); + throw bindingConflict(); + } + if (byOpenId != null) { + requireCompatibleBinding(byOpenId, byUserId, userId); + log.info("飞书账号配置已恢复:已存在相同开放平台用户标识 event=feishu.oauth.provision outcome=recovered conflictType=OPEN_ID_UNIQUE"); + return byOpenId; + } + String category = constraintCategory(conflict); + log.warn("飞书账号配置失败 event=feishu.oauth.provision outcome=failed conflictType={}", category); + throw new BusinessException("飞书账号创建冲突,请稍后重试", 409); + } - String userId = feishuUserInfo.getUserId() == null ? null : feishuUserInfo.getUserId().trim(); - String number = uniqueEmployeeNo(); + private SysUser recoverFinalizationConflict(SysUser selected, String userId, + DataIntegrityViolationException conflict) { + SysUser byUserId = userId == null ? null : sysUserRepository.findByFeishuUserId(userId); + if (byUserId != null && !Objects.equals(selected.getId(), byUserId.getId())) { + log.warn("飞书登录完成操作被拒绝:用户编号冲突 event=feishu.oauth.finalize outcome=denied conflictType=USER_ID_UNIQUE"); + throw bindingConflict(); + } + log.warn("飞书登录完成操作失败 event=feishu.oauth.finalize outcome=failed conflictType={}", constraintCategory(conflict)); + throw new BusinessException("飞书账号绑定冲突,请稍后重试", 409); + } - SysUser user = SysUser.builder() - .feishuOpenId(openId) - .feishuUserId(StringUtils.hasText(userId) ? userId : null) - .employeeNo(number) - .realName(StringUtils.hasText(feishuUserInfo.getName()) ? feishuUserInfo.getName() : "Feishu User") - .avatarUrl(feishuUserInfo.getAvatarUrl()) - .email(feishuUserInfo.getEmail()) - .mobile(feishuUserInfo.getMobile()) - .userType("EMPLOYEE") - .status("ACTIVE") - .directoryStatus("UNKNOWN") - .build(); - SysUser saved = sysUserRepository.save(user); - if (saved != null) user = saved; - log.info("Feishu OAuth provisioned an employee account"); - // Flush so the subsequent lookup sees the new record - sysUserRepository.flush(); - return user; + private void requireCompatibleBinding(SysUser selected, SysUser userIdOwner, String requestedUserId) { + if (userIdOwner != null && (selected == null || !Objects.equals(selected.getId(), userIdOwner.getId()))) { + throw bindingConflict(); + } + if (selected == null || requestedUserId == null) return; + String boundUserId = StringUtils.hasText(selected.getFeishuUserId()) + ? selected.getFeishuUserId().trim() : null; + if (boundUserId != null && !boundUserId.equals(requestedUserId)) throw bindingConflict(); + } + + static String constraintCategory(DataIntegrityViolationException conflict) { + Throwable current = conflict; + while (current != null) { + String message = current.getMessage(); + String normalized = message == null ? "" : message.toLowerCase(Locale.ROOT); + if (normalized.contains("ux_user_feishu_open_id") + || normalized.contains("feishu_oauth_open_id_unique")) return "OPEN_ID_UNIQUE"; + if (normalized.contains("ux_user_feishu_user_id") + || normalized.contains("feishu_oauth_user_id_unique")) return "USER_ID_UNIQUE"; + if (normalized.contains("ux_user_employee_no") + || normalized.contains("feishu_oauth_employee_no_unique")) return "EMPLOYEE_NO_UNIQUE"; + current = current.getCause(); + } + return "UNKNOWN_CONSTRAINT"; + } + + private BusinessException bindingConflict() { + return new BusinessException("飞书账号已绑定其他账户,请联系管理员", 403); } private void validateOAuthProfile(String openId, String userId, FeishuUserInfo info) { @@ -315,14 +609,6 @@ public class FeishuAuthService { } } - private String uniqueEmployeeNo() { - for (int attempt = 0; attempt < 5; attempt++) { - String number = "FS-" + java.util.UUID.randomUUID(); - if (sysUserRepository.findByEmployeeNo(number) == null) return number; - } - throw new BusinessException("员工编号生成失败,请稍后重试", 503); - } - private BusinessException invalidFeishuIdentity() { return new BusinessException("飞书身份无效,请重新授权", 403); } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java index e289bc9..ae10625 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java @@ -9,12 +9,12 @@ import org.springframework.stereotype.Component; @ConfigurationProperties(prefix = "feishu") public class FeishuConfig { /** Master switch for Feishu OAuth / approval / directory token use. */ - private boolean enabled = true; + private boolean enabled = false; private String appId; private String appSecret; private String redirectUri; - /** Independent switch for Feishu directory sync (defaults on when credentials exist). */ - private boolean syncOrgEnabled = true; + /** Independent switch for Feishu directory sync; must be explicitly enabled. */ + private boolean syncOrgEnabled = false; /** * Legacy setting retained for configuration compatibility. OAuth no * longer has a local bootstrap exception and always provisions an diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java index 897cce7..0ecda9a 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java @@ -51,7 +51,7 @@ public class FeishuDefinitionSyncService { ? "已验证审批定义并完成事件订阅;飞书审批状态变更将实时同步到本系统" : "已验证审批定义;事件订阅已存在,飞书审批状态变更将实时同步到本系统"); } catch (Exception e) { - log.warn("飞书审批定义已同步,但事件订阅失败: {}", e.toString()); + log.warn("飞书审批事件订阅失败 feishu_approval_subscription_failed code=SUBSCRIBE_FAILED"); result.setEventSubscribed(false); result.setMessage("已验证并同步审批定义(发起申请可用);事件订阅暂未成功,请检查飞书事件权限后再次同步"); } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java index 09eb601..0eba949 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java @@ -161,9 +161,9 @@ public class FeishuDirectoryAccessService { String generation = publication.getRevision(); String context = publication.getSuccessfulContext(); - // Directory-first: every valid row in the immutable published - // generation is a candidate, independent of employment policy - // and independent of whether a local account already exists. + // Directory-first, but business membership is explicitly limited + // to ACTIVE/eligible rows because the current directory also + // retains resigned employees for organizational visibility. StringBuilder sql = new StringBuilder("SELECT gu.open_id,gu.user_id,gu.name,gu.employee_no,gu.eligible,") .append("open_owner.id AS open_owner_id,open_owner.status AS local_status,") .append("open_owner.feishu_user_id AS local_user_id,") @@ -171,7 +171,7 @@ public class FeishuDirectoryAccessService { .append("FROM feishu_directory_user gu ") .append("LEFT JOIN sys_user open_owner ON open_owner.feishu_open_id=gu.open_id ") .append("LEFT JOIN sys_user_group_member gm ON gm.user_id=open_owner.id ") - .append("WHERE gu.context=? "); + .append("WHERE gu.context=? AND gu.eligible=TRUE AND gu.employment_status='ACTIVE' "); List args = new ArrayList<>(); args.add(context); if (!blank(query)) { diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java index 030da4c..445e20d 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java @@ -4,6 +4,7 @@ import com.finance.system.dto.DirectoryIdentityDto; import com.finance.system.exception.BusinessException; import com.finance.system.service.FeishuDirectoryLock; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; @@ -25,6 +26,10 @@ import java.util.*; public class FeishuDirectoryBindingProvisioner { private final JdbcTemplate jdbc; private final FeishuDirectoryTime time; + @Value("${observability.tenant-id:default}") + private String deploymentTenant = "default"; + @Value("${observability.organization-id:1}") + private Long deploymentOrganizationId = 1L; public FeishuDirectoryBindingProvisioner(JdbcTemplate jdbc, FeishuDirectoryTime time) { this.jdbc = jdbc; this.time = time; @@ -58,13 +63,13 @@ public class FeishuDirectoryBindingProvisioner { List> directoryRows = jdbc.queryForList( "SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible " + "FROM feishu_directory_user WHERE context=? AND snapshot_run_id=? " - + "AND open_id=? FOR UPDATE", + + "AND open_id=? AND eligible=TRUE AND employment_status='ACTIVE' FOR UPDATE", context, generation, identity.getOpenId()); if (directoryRows.size() != 1) throw conflict(); Map directory = directoryRows.get(0); List> accountRows = jdbc.queryForList( - "SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user " + "SELECT id,feishu_open_id,feishu_user_id,status,tenant_id,organization_id FROM sys_user " + "WHERE feishu_open_id=? FOR UPDATE", identity.getOpenId()); Map openOwner = null; for (Map row : accountRows) { @@ -81,7 +86,7 @@ public class FeishuDirectoryBindingProvisioner { if(!blank(legacyRequest))legacyIds.add(legacyRequest); for(String legacyId:legacyIds){ List> owners=jdbc.queryForList( - "SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user WHERE feishu_user_id=? FOR UPDATE", + "SELECT id,feishu_open_id,feishu_user_id,status,tenant_id,organization_id FROM sys_user WHERE feishu_user_id=? FOR UPDATE", legacyId); for(Map owner:owners){ if(openOwner==null||!Objects.equals(number(openOwner.get("id")),number(owner.get("id"))))throw conflict(); @@ -89,6 +94,10 @@ public class FeishuDirectoryBindingProvisioner { } if (openOwner != null) { + if (!deploymentTenant().equals(value(openOwner.get("tenant_id"))) + || !Objects.equals(deploymentOrganizationId(), number(openOwner.get("organization_id")))) { + throw conflict(); + } String counterpart = value(openOwner.get("feishu_user_id")); if (!blank(counterpart)&&!blank(legacyRow)&&!legacyRow.equals(counterpart)) throw conflict(); if (!blank(counterpart)&&!blank(legacyRequest)&&!legacyRequest.equals(counterpart)) throw conflict(); @@ -117,8 +126,8 @@ public class FeishuDirectoryBindingProvisioner { PreparedStatementCreator insert = connection -> { PreparedStatement statement = connection.prepareStatement( "INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,avatar_url,email,mobile,position," - + "user_type,password_hash,status,directory_status,directory_context,directory_verified_at," - + "directory_last_seen_run_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,'EMPLOYEE',NULL,'ACTIVE',?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", + + "tenant_id,organization_id,user_type,password_hash,status,directory_status,directory_context,directory_verified_at," + + "directory_last_seen_run_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'EMPLOYEE',NULL,'ACTIVE',?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", Statement.RETURN_GENERATED_KEYS); int index = 1; statement.setString(index++, openId); statement.setString(index++, null); @@ -127,6 +136,8 @@ public class FeishuDirectoryBindingProvisioner { statement.setString(index++, boundedNullable(value(row.get("email")), 200)); statement.setString(index++, boundedNullable(value(row.get("mobile")), 20)); statement.setString(index++, boundedNullable(value(row.get("job_title")), 200)); + statement.setString(index++, deploymentTenant()); + statement.setLong(index++, deploymentOrganizationId()); statement.setString(index++, directoryStatus); statement.setString(index++, context); statement.setTimestamp(index++, observed); statement.setString(index, generation); return statement; @@ -182,6 +193,14 @@ public class FeishuDirectoryBindingProvisioner { if (result == null) result = boundedNullable(fallback, max); return result; } + private String deploymentTenant() { + if (blank(deploymentTenant)) throw conflict(); + return deploymentTenant.trim(); + } + private long deploymentOrganizationId() { + if (deploymentOrganizationId == null || deploymentOrganizationId <= 0) throw conflict(); + return deploymentOrganizationId; + } private static BusinessException conflict() { return new BusinessException("目录身份或成员状态已变更,请刷新后重试", 409); } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java index f6ac463..d85a9cc 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java @@ -16,6 +16,6 @@ public class FeishuDirectoryBootstrap { public void start() { if (!settings.isBootstrapSyncOnStartup()) return; try { directory.sync("STARTUP"); } - catch (Exception e) { log.warn("Startup directory sync unavailable; employee access remains fail-closed"); } + catch (Exception e) { log.warn("启动时通讯录同步不可用;为保障安全,继续拒绝员工访问"); } } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java index 841322f..2f296d8 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java @@ -29,10 +29,11 @@ public class FeishuDirectoryClient { "department_id", "name", "parent_department_id", "order_weight", "department_count")); static final List EMPLOYEE_FIELDS = Collections.unmodifiableList(Arrays.asList( "base_info.employee_id", "base_info.name", "base_info.mobile", "base_info.email", - "base_info.departments.department_id", "base_info.avatar", + "base_info.departments.department_id", "base_info.avatar", "base_info.is_resigned", "work_info.job_number", "work_info.job_title.job_title_name")); private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L); private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); + private static final BigInteger DIRECTORY_FIELD_UNAVAILABLE_CODE = BigInteger.valueOf(1000L); private static final ObjectMapper JSON = new ObjectMapper(); private enum Kind { @@ -184,7 +185,35 @@ public class FeishuDirectoryClient { private static void validateAbnormals(JsonNode data,Kind kind) { JsonNode abnormal=data.get("abnormals"); if(abnormal==null) return; - if(!abnormal.isArray()||abnormal.size()!=0) fail(kind.diagnostic+"_ABNORMAL"); + if(!abnormal.isArray()) fail(kind.diagnostic+"_ABNORMAL"); + if(abnormal.size()==0)return; + // Directory-v1 can report a selectively requested unavailable field as + // field error 1000. Classify only the exact, homogeneous + // base_info.is_resigned case; mixed row/field errors must retain the + // generic fail-closed diagnostic so another provider defect is not hidden. + if(kind==Kind.EMPLOYEE&&onlyResignationPermissionErrors(abnormal)) + fail("DIRECTORY_USER_RESIGNATION_FIELD_UNAVAILABLE"); + fail(kind.diagnostic+"_ABNORMAL"); + } + private static boolean onlyResignationPermissionErrors(JsonNode abnormals) { + boolean seen=false; + for(JsonNode abnormal:abnormals) { + if(abnormal==null||!abnormal.isObject())return false; + JsonNode rowError=abnormal.get("row_error"); + if(rowError!=null&&!rowError.isNull() + &&(!rowError.isIntegralNumber()||!BigInteger.ZERO.equals(rowError.bigIntegerValue())))return false; + JsonNode fieldErrors=abnormal.get("field_errors"); + if(fieldErrors==null||!fieldErrors.isObject()||fieldErrors.size()==0)return false; + Iterator> fields=fieldErrors.fields(); + while(fields.hasNext()) { + Map.Entry field=fields.next(); + if(!"base_info.is_resigned".equals(field.getKey()) + ||!field.getValue().isIntegralNumber() + ||!DIRECTORY_FIELD_UNAVAILABLE_CODE.equals(field.getValue().bigIntegerValue()))return false; + seen=true; + } + } + return seen; } private String mergeDepartment(Snapshot snapshot,JsonNode node) { @@ -275,9 +304,17 @@ public class FeishuDirectoryClient { fail("DIRECTORY_USER_ITEM_INVALID"); u.jobTitle=i18n(title.get("job_title_name"),200,"DIRECTORY_USER_ITEM_INVALID"); } - // Exhaustive traversal defines the current employee population. The status - // partition used by transport is deliberately neither projected nor parsed. - u.eligible=true; + JsonNode resigned=base.get("is_resigned"); + // Directory-v1 may omit a selectively projected field because of field + // authorization, response-contract or app/tenant mismatch. Absence must + // remain fail-closed and must never be interpreted as an active employee. + // A present value must still follow the documented boolean contract; no + // string/number coercion is allowed. + if(resigned==null||resigned.isNull())fail("DIRECTORY_USER_RESIGNATION_FIELD_UNAVAILABLE"); + if(!resigned.isBoolean())fail("DIRECTORY_USER_RESIGNATION_FIELD_INVALID"); + // staff_status only partitions the exhaustive transport. Directory-v1's + // explicitly projected boolean is the sole employment eligibility source. + u.eligible=!resigned.booleanValue(); return u; } private static String avatar(JsonNode avatar) { diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java index 8cb396c..729b999 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java @@ -12,6 +12,8 @@ import java.util.*; @Component public class FeishuDirectoryCurrentStore { static final int MAX_DIRECT_MEMBERSHIPS=500_000, MAX_EXPANDED_MEMBERSHIPS=1_000_000, WRITE_BATCH_SIZE=1_000; + static final String EMPLOYMENT_STATUS_ACTIVE="ACTIVE",EMPLOYMENT_STATUS_RESIGNED="RESIGNED"; + static final String EMPLOYMENT_STATUS_SOURCE="FEISHU_DIRECTORY_V1_IS_RESIGNED"; private final JdbcTemplate jdbc; private final int maxDirect,maxExpanded,batchSize; @Autowired public FeishuDirectoryCurrentStore(JdbcTemplate jdbc){this(jdbc,MAX_DIRECT_MEMBERSHIPS,MAX_EXPANDED_MEMBERSHIPS,WRITE_BATCH_SIZE);} FeishuDirectoryCurrentStore(JdbcTemplate jdbc,int maxDirect,int maxExpanded,int batchSize){ @@ -20,12 +22,14 @@ public class FeishuDirectoryCurrentStore { } public void publish(String revision,String context,FeishuDirectoryClient.Snapshot snapshot,Timestamp now){ - Map> relations=relations(snapshot);Map counts=memberCounts(snapshot,relations); + Map> relations=relations(snapshot,false);Map counts=memberCounts(snapshot,relations); Map oldDepartments=hashes("SELECT open_department_id,content_hash FROM feishu_directory_department"); Map oldUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_user"); + Map oldObservedUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_employee_observation"); Set wantedDepartments=new LinkedHashSet<>(),wantedUsers=new LinkedHashSet<>(); - List departmentRows=new ArrayList<>(),userRows=new ArrayList<>(); - List retainedDepartmentRows=new ArrayList<>(),retainedUserRows=new ArrayList<>(); + Set wantedObservedUsers=new LinkedHashSet<>(); + List departmentRows=new ArrayList<>(),userRows=new ArrayList<>(),observedUserRows=new ArrayList<>(); + List retainedDepartmentRows=new ArrayList<>(),retainedUserRows=new ArrayList<>(),retainedObservedUserRows=new ArrayList<>(); for(String id:snapshot.departments){ FeishuDirectoryClient.Department d=snapshot.departmentDetails.get(id);if(d==null)d=fallbackDepartment(id); String open=bounded(d.openDepartmentId,64,id),name=bounded(d.name,200,""),parent=bounded(d.parentOpenDepartmentId,64,"0"),status=bounded(d.status,30,"ACTIVE"); @@ -34,24 +38,53 @@ public class FeishuDirectoryCurrentStore { else retainedDepartmentRows.add(new Object[]{revision,context,now,open}); } for(Map.Entry e:snapshot.userSummaries.entrySet()){ - FeishuDirectoryClient.UserSummary u=e.getValue();String open=bounded(u.openId,100,""); + FeishuDirectoryClient.UserSummary u=e.getValue(); + if(u==null)throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT"); + String observedOpen=bounded(u.openId,100,""); + if(!observedOpen.equals(e.getKey()))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT"); + String observedUserId=nullableBounded(u.userId,100),observedName=bounded(u.name,100,observedOpen); + String observedEmployee=nullableBounded(u.employeeNo,50),observedEmail=bounded(u.email,320,""); + String observedMobile=bounded(u.mobile,50,""),observedJob=bounded(u.jobTitle,200,""),observedAvatar=bounded(u.avatarUrl,500,""); + String employmentStatus=u.eligible?EMPLOYMENT_STATUS_ACTIVE:EMPLOYMENT_STATUS_RESIGNED; + String observedHash=hash(observedOpen,observedUserId,observedName,observedEmployee,observedEmail,observedMobile, + observedJob,observedAvatar,employmentStatus,String.valueOf(!u.eligible),EMPLOYMENT_STATUS_SOURCE,context); + wantedObservedUsers.add(observedOpen); + if(!observedHash.equals(oldObservedUsers.get(observedOpen)))observedUserRows.add(new Object[]{observedOpen,observedUserId, + observedName,observedEmployee,employmentStatus,!u.eligible,EMPLOYMENT_STATUS_SOURCE,now,revision,context, + observedEmail,observedMobile,observedJob,observedAvatar,observedHash,now}); + else retainedObservedUserRows.add(new Object[]{revision,context,now,observedOpen}); + String open=bounded(u.openId,100,""); if(!open.equals(e.getKey()))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT"); String name=bounded(u.name,100,open);String employee=nullableBounded(u.employeeNo,50); - String email=bounded(u.email,320,""),mobile=bounded(u.mobile,50,""),job=bounded(u.jobTitle,200,""),avatar=bounded(u.avatarUrl,500,"");boolean eligible=u.eligible; - String hash=hash(open,"",name,employee,email,mobile,job,avatar,String.valueOf(eligible),context);wantedUsers.add(open); - if(!hash.equals(oldUsers.get(open)))userRows.add(new Object[]{open,null,name,employee,eligible,revision,context,now,email,mobile,job,avatar,hash,now}); + String email=bounded(u.email,320,""),mobile=bounded(u.mobile,50,""),job=bounded(u.jobTitle,200,""),avatar=bounded(u.avatarUrl,500,""); + String hash=hash(open,observedUserId,name,employee,email,mobile,job,avatar, + String.valueOf(u.eligible),employmentStatus,context);wantedUsers.add(open); + if(!hash.equals(oldUsers.get(open)))userRows.add(new Object[]{open,observedUserId,name,employee,u.eligible, + employmentStatus,revision,context,now,email,mobile,job,avatar,hash,now}); else retainedUserRows.add(new Object[]{revision,context,now,open}); } Set oldMemberships=new LinkedHashSet<>();for(Map row:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department"))oldMemberships.add(key(row.get("open_id"),row.get("open_department_id"))); SetwantedMemberships=new LinkedHashSet<>();ListmembershipRows=new ArrayList<>(),retainedMembershipRows=new ArrayList<>(); for(Map.Entry> e:relations.entrySet()){String open=e.getKey();for(String department:e.getValue()){String key=key(open,department);wantedMemberships.add(key);if(!oldMemberships.contains(key))membershipRows.add(new Object[]{open,department,revision,now});else retainedMembershipRows.add(new Object[]{revision,open,department});}} - batchDeleteMemberships(oldMemberships,wantedMemberships);batchDelete("feishu_directory_user","open_id",oldUsers.keySet(),wantedUsers);batchDelete("feishu_directory_department","open_department_id",oldDepartments.keySet(),wantedDepartments); + Set oldObservedMemberships=new LinkedHashSet<>();for(Map row:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_employee_observation_department"))oldObservedMemberships.add(key(row.get("open_id"),row.get("open_department_id"))); + SetwantedObservedMemberships=new LinkedHashSet<>();ListobservedMembershipRows=new ArrayList<>(),retainedObservedMembershipRows=new ArrayList<>(); + for(Map.Entry> e:relations.entrySet()){String open=e.getKey();for(String department:e.getValue()){String key=key(open,department);wantedObservedMemberships.add(key);if(!oldObservedMemberships.contains(key))observedMembershipRows.add(new Object[]{open,department,revision,now});else retainedObservedMembershipRows.add(new Object[]{revision,open,department});}} + batchDeleteMemberships("feishu_directory_user_department",oldMemberships,wantedMemberships); + batchDeleteMemberships("feishu_directory_employee_observation_department",oldObservedMemberships,wantedObservedMemberships); + batchDelete("feishu_directory_user","open_id",oldUsers.keySet(),wantedUsers); + batchDelete("feishu_directory_employee_observation","open_id",oldObservedUsers.keySet(),wantedObservedUsers); + batchDelete("feishu_directory_department","open_department_id",oldDepartments.keySet(),wantedDepartments); batch("INSERT INTO feishu_directory_department(open_department_id,name,parent_open_department_id,sort_order,status,member_count,snapshot_run_id,context,observed_at,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),parent_open_department_id=VALUES(parent_open_department_id),sort_order=VALUES(sort_order),status=VALUES(status),member_count=VALUES(member_count),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",departmentRows); - batch("INSERT INTO feishu_directory_user(open_id,user_id,name,employee_no,eligible,snapshot_run_id,context,observed_at,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),employee_no=VALUES(employee_no),eligible=VALUES(eligible),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",userRows); + batch("INSERT INTO feishu_directory_user(open_id,user_id,name,employee_no,eligible,employment_status,snapshot_run_id,context,observed_at,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE user_id=VALUES(user_id),name=VALUES(name),employee_no=VALUES(employee_no),eligible=VALUES(eligible),employment_status=VALUES(employment_status),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",userRows); batch("INSERT INTO feishu_directory_user_department(open_id,open_department_id,revision_run_id,changed_at) VALUES (?,?,?,?)",membershipRows); + batch("INSERT INTO feishu_directory_employee_observation(open_id,user_id,name,employee_no,employment_status,is_resigned,status_source,status_observed_at,snapshot_run_id,context,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE user_id=VALUES(user_id),name=VALUES(name),employee_no=VALUES(employee_no),employment_status=VALUES(employment_status),is_resigned=VALUES(is_resigned),status_source=VALUES(status_source),status_observed_at=VALUES(status_observed_at),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",observedUserRows); + batch("INSERT INTO feishu_directory_employee_observation_department(open_id,open_department_id,revision_run_id,changed_at) VALUES (?,?,?,?)",observedMembershipRows); batch("UPDATE feishu_directory_department SET snapshot_run_id=?,context=?,observed_at=? WHERE open_department_id=?",retainedDepartmentRows); batch("UPDATE feishu_directory_user SET snapshot_run_id=?,context=?,observed_at=? WHERE open_id=?",retainedUserRows); batch("UPDATE feishu_directory_user_department SET revision_run_id=? WHERE open_id=? AND open_department_id=?",retainedMembershipRows); + batch("UPDATE feishu_directory_employee_observation SET snapshot_run_id=?,context=?,status_observed_at=?,changed_at=changed_at WHERE open_id=?",retainedObservedUserRows); + batch("UPDATE feishu_directory_employee_observation_department SET revision_run_id=? WHERE open_id=? AND open_department_id=?",retainedObservedMembershipRows); + assertCurrentAndObservationConsistent(); } public Map read(){ @@ -63,12 +96,24 @@ public class FeishuDirectoryCurrentStore { /** Departments only — used by the organization shell so the page can paint before members load. */ public List> readDepartments(){ + List> rows=jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id"); + Map parents=new LinkedHashMap<>(); + for(Map row:rows)parents.put(string(row.get("open_department_id")),string(row.get("parent_open_department_id"))); + Map> observedMembers=new HashMap<>(); + for(Map membership:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department ORDER BY open_id,open_department_id")){ + String open=string(membership.get("open_id")),current=string(membership.get("open_department_id")); + Set visited=new HashSet<>(); + while(!current.isEmpty()&&parents.containsKey(current)&&visited.add(current)){ + observedMembers.computeIfAbsent(current,key->new HashSet<>()).add(open); + String parent=parents.get(current);if(parent==null||parent.equals(current))break;current=parent; + } + } List> departments=new ArrayList<>(); - for(Mapr:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){ + for(Mapr:rows){ Mapd=new LinkedHashMap<>(); d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name"))); d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order")))); - d.put("memberCount",intValue(r.get("member_count")));departments.add(d); + d.put("memberCount",observedMembers.getOrDefault(string(r.get("open_department_id")),Collections.emptySet()).size());departments.add(d); } return departments; } @@ -109,8 +154,8 @@ public class FeishuDirectoryCurrentStore { for(Mapr:allForUsers)memberships.computeIfAbsent(string(r.get("open_id")),k->new ArrayList<>()).add(string(r.get("open_department_id"))); } String userSql=scope==null - ?"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id" - :"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user WHERE open_id IN (" + ?"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible,employment_status,observed_at FROM feishu_directory_user ORDER BY open_id" + :"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible,employment_status,observed_at FROM feishu_directory_user WHERE open_id IN (" +placeholders(openIds.size())+") ORDER BY open_id"; List> userRows=scope==null?jdbc.queryForList(userSql):jdbc.queryForList(userSql,openIds.toArray()); List>users=new ArrayList<>(); @@ -120,22 +165,43 @@ public class FeishuDirectoryCurrentStore { u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no")); u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile"))); u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url"))); + String employmentStatus=string(r.get("employment_status")); + u.put("employmentStatus",employmentStatus);u.put("resigned",EMPLOYMENT_STATUS_RESIGNED.equals(employmentStatus)); + u.put("employmentStatusSource",EMPLOYMENT_STATUS_SOURCE); + Object statusObservedAt=r.get("observed_at");u.put("employmentStatusObservedAt",statusObservedAt==null?null:String.valueOf(statusObservedAt)); u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u); } return users; } + private void assertCurrentAndObservationConsistent(){ + String sql="SELECT COUNT(*) FROM (" + +"SELECT u.open_id FROM feishu_directory_user u LEFT JOIN feishu_directory_employee_observation o ON o.open_id=u.open_id " + +"WHERE o.open_id IS NULL OR NOT(u.user_id<=>o.user_id) OR u.name<>o.name OR NOT(u.employee_no<=>o.employee_no) " + +"OR u.employment_status<>o.employment_status OR u.eligible<>(o.employment_status='ACTIVE') " + +"OR o.is_resigned<>(u.employment_status='RESIGNED') OR u.snapshot_run_id<>o.snapshot_run_id " + +"OR NOT(u.context<=>o.context) OR NOT(u.email<=>o.email) OR NOT(u.mobile<=>o.mobile) " + +"OR NOT(u.job_title<=>o.job_title) OR NOT(u.avatar_url<=>o.avatar_url) " + +"UNION ALL SELECT o.open_id FROM feishu_directory_employee_observation o LEFT JOIN feishu_directory_user u ON u.open_id=o.open_id WHERE u.open_id IS NULL " + +"UNION ALL SELECT ud.open_id FROM feishu_directory_user_department ud LEFT JOIN feishu_directory_employee_observation_department od " + +"ON od.open_id=ud.open_id AND od.open_department_id=ud.open_department_id WHERE od.open_id IS NULL " + +"UNION ALL SELECT od.open_id FROM feishu_directory_employee_observation_department od LEFT JOIN feishu_directory_user_department ud " + +"ON ud.open_id=od.open_id AND ud.open_department_id=od.open_department_id WHERE ud.open_id IS NULL) drift"; + Integer drift=jdbc.queryForObject(sql,Integer.class); + if(drift==null||drift.intValue()!=0)throw FeishuTenantTokenService.diagnostic("DIRECTORY_STORAGE_INCONSISTENT"); + } + private static String placeholders(int count){ if(count<1)throw new IllegalArgumentException("placeholder count"); StringBuilder b=new StringBuilder("?"); for(int i=1;iold,Setwanted){Listrows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM feishu_directory_user_department WHERE open_id=? AND open_department_id=?",rows);} + private void batchDeleteMemberships(String table,Setold,Setwanted){Listrows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM "+table+" WHERE open_id=? AND open_department_id=?",rows);} private void batchDelete(String table,String column,Setold,Setwanted){Listrows=new ArrayList<>();for(String value:old)if(!wanted.contains(value))rows.add(new Object[]{value});batch("DELETE FROM "+table+" WHERE "+column+"=?",rows);} private void batch(String sql,Listrows){for(int i=0;ihashes(String sql){Mapr=new LinkedHashMap<>();for(Maprow:jdbc.queryForList(sql)){Iteratori=row.values().iterator();r.put(string(i.next()),string(i.next()));}return r;} - private Map>relations(FeishuDirectoryClient.Snapshot s){Map>r=new LinkedHashMap<>();int total=0;for(Map.Entrye:s.userSummaries.entrySet()){LinkedHashSetids=new LinkedHashSet<>();for(String id:e.getValue().departmentIds)if(id!=null&&s.departments.contains(id.trim()))ids.add(id.trim());if(ids.isEmpty()&&s.departments.contains("0"))ids.add("0");if(ids.size()>maxDirect-total)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");total+=ids.size();r.put(e.getKey(),new ArrayList<>(ids));}return r;} + private Map>relations(FeishuDirectoryClient.Snapshot s,boolean eligibleOnly){Map>r=new LinkedHashMap<>();int total=0;for(Map.Entrye:s.userSummaries.entrySet()){FeishuDirectoryClient.UserSummary user=e.getValue();if(user==null)throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");if(eligibleOnly&&!user.eligible)continue;LinkedHashSetids=new LinkedHashSet<>();for(String id:user.departmentIds)if(id!=null&&s.departments.contains(id.trim()))ids.add(id.trim());if(ids.isEmpty()&&s.departments.contains("0"))ids.add("0");if(ids.size()>maxDirect-total)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");total+=ids.size();r.put(e.getKey(),new ArrayList<>(ids));}return r;} private MapmemberCounts(FeishuDirectoryClient.Snapshot s,Map>relations){Mapparents=new HashMap<>();for(String id:s.departments){FeishuDirectoryClient.Department d=s.departmentDetails.get(id);parents.put(id,d==null?"0":d.parentOpenDepartmentId);}Map>members=new HashMap<>();int expanded=0;for(Map.Entry>e:relations.entrySet()){String employee=e.getKey();for(String id:e.getValue()){Setvisited=new HashSet<>();String current=id;while(current!=null&&parents.containsKey(current)&&visited.add(current)){Setset=members.computeIfAbsent(current,k->new HashSet<>());if(set.add(employee)&&++expanded>maxExpanded)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");String parent=parents.get(current);if(parent==null||parent.equals(current))break;current=parent;}}}Mapr=new HashMap<>();for(Map.Entry>e:members.entrySet())r.put(e.getKey(),e.getValue().size());return r;} private static String hash(String...values){StringBuilder b=new StringBuilder();for(String v:values){String x=v==null?"":v;b.append(x.length()).append(':').append(x).append(';');}return Sha256.hex(b.toString());} private static String key(Object a,Object b){return string(a)+'\u0000'+string(b);} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java index 8f43269..66ab315 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java @@ -30,6 +30,10 @@ public class FeishuDirectoryPublisher { private final FeishuTenantTokenService tokens; private final ObjectMapper mapper; private final FeishuDirectoryTime time; + @org.springframework.beans.factory.annotation.Value("${observability.tenant-id:default}") + private String systemTenant = "default"; + @org.springframework.beans.factory.annotation.Value("${observability.organization-id:1}") + private Long systemOrganization = 1L; public FeishuDirectoryPublisher(JdbcTemplate jdbc, PlatformTransactionManager manager, FeishuDirectoryRunStore runs, FeishuDirectoryCurrentStore directory, @@ -55,12 +59,12 @@ public class FeishuDirectoryPublisher { if (!captured.fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged(); run.setState("SUCCEEDED"); run.setComplete(true); run.setApplied(true); run.setFinishedAt(now.toInstant().toString()); int completed=jdbc.update("UPDATE feishu_directory_sync_run SET state='SUCCEEDED',finished_at=?,complete=TRUE,applied=TRUE,"+ - "departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,context=?,lease_until=NULL,error_code=NULL,error_message=NULL WHERE run_id=? AND execution_token=? AND fence_token=?", - now,counts.getDepartments(),counts.getUsersSeen(),counts.getEligible(),counts.getExcluded(),counts.getCreated(),counts.getUpdated(),counts.getIneligible(),counts.getOutOfScope(),captured.fingerprint,claim.getRunId(),claim.getExecutionToken(),claim.getFenceToken()); + "departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,context=?,lease_until=NULL,error_code=NULL,error_message=NULL WHERE tenant_id=? AND run_id=? AND execution_token=? AND fence_token=?", + now,counts.getDepartments(),counts.getUsersSeen(),counts.getEligible(),counts.getExcluded(),counts.getCreated(),counts.getUpdated(),counts.getIneligible(),counts.getOutOfScope(),captured.fingerprint,systemTenant,claim.getRunId(),claim.getExecutionToken(),claim.getFenceToken()); if(completed!=1)throw FeishuTenantTokenService.ownershipLost(); String runJson=encode(run); - int moved=jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=? WHERE id=1 AND owner=? AND fence_token=?", - runJson,claim.getRunId(),now,captured.fingerprint,claim.getRunId(),claim.getFenceToken()); + int moved=jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=? WHERE tenant_id=? AND id=1 AND owner=? AND fence_token=?", + runJson,claim.getRunId(),now,captured.fingerprint,systemTenant,claim.getRunId(),claim.getFenceToken()); if(moved!=1)throw FeishuTenantTokenService.ownershipLost(); return run; }); @@ -161,7 +165,9 @@ public class FeishuDirectoryPublisher { } private void loadEmployeeNumbers(Set values,Set result){Listall=new ArrayList<>(values);for(int start=0;startb=all.subList(start,Math.min(all.size(),start+LOOKUP_BATCH));for(Maprow:jdbc.queryForList("SELECT employee_no FROM sys_user WHERE employee_no IN ("+placeholders(b.size())+")",b.toArray()))result.add(String.valueOf(row.get("employee_no")));}} private boolean employeeExists(String employee){Integer count=jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE employee_no=?",Integer.class,employee);return count!=null&&count>0;} - private long insertAccount(String open,String employee,String name){KeyHolder key=new GeneratedKeyHolder();PreparedStatementCreator creator=connection->{PreparedStatement statement=connection.prepareStatement("INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,status,user_type,directory_status,created_at,updated_at) VALUES (?,NULL,?,?,'ACTIVE','EMPLOYEE','UNKNOWN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",Statement.RETURN_GENERATED_KEYS);statement.setString(1,open);statement.setString(2,employee);statement.setString(3,name);return statement;};jdbc.update(creator,key);if(key.getKey()==null)throw new IllegalStateException("Directory account key unavailable");return key.getKey().longValue();} + private long insertAccount(String open,String employee,String name){ + String tenant=trim(systemTenant);if(tenant.isEmpty()||systemOrganization==null||systemOrganization<=0)throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEPLOYMENT_BOUNDARY_INVALID"); + KeyHolder key=new GeneratedKeyHolder();PreparedStatementCreator creator=connection->{PreparedStatement statement=connection.prepareStatement("INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,tenant_id,organization_id,status,user_type,directory_status,created_at,updated_at) VALUES (?,NULL,?,?,?,?,'ACTIVE','EMPLOYEE','UNKNOWN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",Statement.RETURN_GENERATED_KEYS);statement.setString(1,open);statement.setString(2,employee);statement.setString(3,name);statement.setString(4,tenant);statement.setLong(5,systemOrganization);return statement;};jdbc.update(creator,key);if(key.getKey()==null)throw new IllegalStateException("Directory account key unavailable");return key.getKey().longValue();} Account account(Maprow){return new Account(((Number)row.get("id")).longValue(),value(row.get("feishu_open_id")),value(row.get("feishu_user_id")),value(row.get("directory_status")),value(row.get("directory_context")),time.instant(row.get("directory_verified_at")));} private static String value(Object value){return value==null?null:String.valueOf(value);} private static String placeholders(int n){StringBuilder b=new StringBuilder();for(int i=0;i0)b.append(',');b.append('?');}return b.toString();} private static String trim(String value){return value==null?"":value.trim();} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java index dd56b45..0075f41 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java @@ -23,6 +23,8 @@ public class FeishuDirectoryRunStore { private final TransactionTemplate requiresNew; private final ObjectMapper mapper; private final long leaseSeconds; + @org.springframework.beans.factory.annotation.Value("${observability.tenant-id:default}") + private String systemTenant = "default"; public FeishuDirectoryRunStore(JdbcTemplate jdbc, PlatformTransactionManager manager, ObjectMapper mapper, FeishuDirectorySettings settings) { @@ -36,28 +38,46 @@ public class FeishuDirectoryRunStore { } public FeishuDirectoryService.Run enqueue(String trigger) { - if (!"MANUAL".equals(trigger) && !"STARTUP".equals(trigger) && !"SCHEDULED".equals(trigger)) - throw new IllegalArgumentException("Invalid trigger"); + validateTrigger(trigger); // Normal duplicate POSTs avoid waiting behind a long publication. The // locked recheck below remains the correctness boundary. - Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class); + Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", Integer.class, systemTenant); if (observedActive != null && observedActive > 0) throw new BusinessException("Directory sync already running", 409); - return requiresNew.execute(status -> { - lockState(); - Integer active = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class); - if (active != null && active > 0) throw new BusinessException("Directory sync already running", 409); - Timestamp now = databaseNow(); - FeishuDirectoryService.Run run = new FeishuDirectoryService.Run(); - run.setRunId(UUID.randomUUID().toString()); - run.setTrigger(trigger); - run.setState("RUNNING"); // Public vocabulary deliberately has no QUEUED state. - run.setStartedAt(null); // Execution time begins only when a worker claims this row. - jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger_type,state,queued_at,started_at,complete,applied) VALUES (?,?, 'QUEUED',?,NULL,FALSE,FALSE)", - run.getRunId(), trigger, now); - jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1", encode(run)); - return run; - }); + return requiresNew.execute(status -> enqueueLocked(trigger)); + } + + /** Participates in the caller's transaction so queue insertion and audit outbox are atomic. */ + public FeishuDirectoryService.Run enqueueInCurrentTransaction(String trigger, String trustedTenantId) { + validateTrigger(trigger); + if (trustedTenantId == null || !trustedTenantId.equals(systemTenant)) { + throw new BusinessException("Invalid tenant boundary", 403); + } + Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", Integer.class, systemTenant); + if (observedActive != null && observedActive > 0) + throw new BusinessException("Directory sync already running", 409); + return enqueueLocked(trigger); + } + + private FeishuDirectoryService.Run enqueueLocked(String trigger) { + lockState(); + Integer active = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", Integer.class, systemTenant); + if (active != null && active > 0) throw new BusinessException("Directory sync already running", 409); + Timestamp now = databaseNow(); + FeishuDirectoryService.Run run = new FeishuDirectoryService.Run(); + run.setRunId(UUID.randomUUID().toString()); + run.setTrigger(trigger); + run.setState("RUNNING"); // Public vocabulary deliberately has no QUEUED state. + run.setStartedAt(null); // Execution time begins only when a worker claims this row. + jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,tenant_id,trigger_type,state,queued_at,started_at,complete,applied) VALUES (?,?,?, 'QUEUED',?,NULL,FALSE,FALSE)", + run.getRunId(), systemTenant, trigger, now); + jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE tenant_id=? AND id=1", encode(run), systemTenant); + return run; + } + + private void validateTrigger(String trigger) { + if (!"MANUAL".equals(trigger) && !"STARTUP".equals(trigger) && !"SCHEDULED".equals(trigger)) + throw new IllegalArgumentException("Invalid trigger"); } public Claim claimNext() { @@ -65,8 +85,8 @@ public class FeishuDirectoryRunStore { Map state = lockState(); List> rows = jdbc.queryForList( "SELECT run_id,trigger_type,attempt_count FROM feishu_directory_sync_run " + - "WHERE (state='QUEUED' OR (state='RUNNING' AND lease_untilCURRENT_TIMESTAMP", - now, lease, claim.runId, claim.executionToken, claim.fenceToken); - if (changed == 1) jdbc.update("UPDATE feishu_directory_state SET lease_until=? WHERE id=1 AND owner=? AND fence_token=?", - lease, claim.runId, claim.fenceToken); + "WHERE tenant_id=? AND run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP", + now, lease, systemTenant, claim.runId, claim.executionToken, claim.fenceToken); + if (changed == 1) jdbc.update("UPDATE feishu_directory_state SET lease_until=? WHERE tenant_id=? AND id=1 AND owner=? AND fence_token=?", + lease, systemTenant, claim.runId, claim.fenceToken); return changed == 1; }); return Boolean.TRUE.equals(result); @@ -107,9 +127,9 @@ public class FeishuDirectoryRunStore { /** Must be called in the publication transaction; takes the singleton lock first. */ public Map requireLease(Claim claim) { Map state = lockState(); - List valid = jdbc.query("SELECT 1 FROM feishu_directory_sync_run WHERE run_id=? AND state='RUNNING' " + + List valid = jdbc.query("SELECT 1 FROM feishu_directory_sync_run WHERE tenant_id=? AND run_id=? AND state='RUNNING' " + "AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP", - (rs, row) -> rs.getInt(1), claim.runId, claim.executionToken, claim.fenceToken); + (rs, row) -> rs.getInt(1), systemTenant, claim.runId, claim.executionToken, claim.fenceToken); if (valid.isEmpty() || !claim.runId.equals(state.get("owner")) || ((Number) state.get("fence_token")).longValue() != claim.fenceToken) throw FeishuTenantTokenService.ownershipLost(); @@ -120,22 +140,22 @@ public class FeishuDirectoryRunStore { requiresNew.execute(status -> { Map state = lockState(); List> rows = jdbc.queryForList("SELECT attempt_count FROM feishu_directory_sync_run " + - "WHERE run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? FOR UPDATE", - claim.runId, claim.executionToken, claim.fenceToken); + "WHERE tenant_id=? AND run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? FOR UPDATE", + systemTenant, claim.runId, claim.executionToken, claim.fenceToken); if (rows.isEmpty()) return null; // A newer owner has fenced this attempt. int attempts = ((Number) rows.get(0).get("attempt_count")).intValue(); if (attempts < MAX_ATTEMPTS && retryable(code)) { - jdbc.update("UPDATE feishu_directory_sync_run SET state='QUEUED',execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL,error_code=?,error_message=? WHERE run_id=?", - code, message, claim.runId); + jdbc.update("UPDATE feishu_directory_sync_run SET state='QUEUED',execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL,error_code=?,error_message=? WHERE tenant_id=? AND run_id=?", + code, message, systemTenant, claim.runId); } else { Timestamp now = databaseNow(); - jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=?,complete=FALSE,applied=FALSE,error_code=?,error_message=?,execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE run_id=?", - now, code, message, claim.runId); + jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=?,complete=FALSE,applied=FALSE,error_code=?,error_message=?,execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE tenant_id=? AND run_id=?", + now, code, message, systemTenant, claim.runId); FeishuDirectoryService.Run run = loadPublic(claim.runId); - jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1", encode(run)); + jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE tenant_id=? AND id=1", encode(run), systemTenant); } if (claim.runId.equals(state.get("owner")) && ((Number) state.get("fence_token")).longValue() == claim.fenceToken) - jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE id=1"); + jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE tenant_id=? AND id=1", systemTenant); return null; }); } @@ -148,7 +168,7 @@ public class FeishuDirectoryRunStore { } public FeishuDirectoryService.Run loadPublic(String runId) { - return jdbc.queryForObject("SELECT * FROM feishu_directory_sync_run WHERE run_id=?", (rs, row) -> { + return jdbc.queryForObject("SELECT * FROM feishu_directory_sync_run WHERE tenant_id=? AND run_id=?", (rs, row) -> { FeishuDirectoryService.Run run = new FeishuDirectoryService.Run(); run.setRunId(rs.getString("run_id")); run.setTrigger(rs.getString("trigger_type")); String internal = rs.getString("state"); @@ -164,24 +184,24 @@ public class FeishuDirectoryRunStore { counts.setIneligible(rs.getInt("ineligible")); counts.setOutOfScope(rs.getInt("out_of_scope")); run.setCounts(counts); run.setErrorCode(rs.getString("error_code")); run.setErrorMessage(rs.getString("error_message")); return run; - }, runId); + }, systemTenant, runId); } private void failExhaustedExpiredRuns() { - List expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE state='RUNNING' " + - "AND lease_until=? FOR UPDATE",(rs,row)->rs.getString(1),MAX_ATTEMPTS); + List expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE tenant_id=? AND state='RUNNING' " + + "AND lease_until=? FOR UPDATE",(rs,row)->rs.getString(1),systemTenant,MAX_ATTEMPTS); for(String runId:expired){ jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=CURRENT_TIMESTAMP,complete=FALSE,applied=FALSE," + "error_code='DIRECTORY_WORKER_UNAVAILABLE',error_message='Directory sync failed; current directory retained.'," + - "execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE run_id=?",runId); + "execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE tenant_id=? AND run_id=?",systemTenant,runId); FeishuDirectoryService.Run failed=loadPublic(runId); - jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1",encode(failed)); - jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE id=1 AND owner=?",runId); + jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE tenant_id=? AND id=1",encode(failed),systemTenant); + jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE tenant_id=? AND id=1 AND owner=?",systemTenant,runId); } } private Map lockState() { - return jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1 FOR UPDATE"); + return jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1 FOR UPDATE", systemTenant); } private Timestamp databaseNow() { return jdbc.queryForObject("SELECT CURRENT_TIMESTAMP", Timestamp.class); } private String encode(FeishuDirectoryService.Run run) { diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java index 61ce3ff..57810fa 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; @@ -34,6 +35,8 @@ public class FeishuDirectoryService { private final ObjectMapper mapper; private final FeishuDirectoryClient directClient; private final FeishuDirectoryPublisher directPublisher; + @Value("${observability.tenant-id:default}") + private String systemTenant = "default"; @Autowired public FeishuDirectoryService(JdbcTemplate jdbc, PlatformTransactionManager manager, @@ -75,18 +78,18 @@ public class FeishuDirectoryService { @PostConstruct public void initializeState(){ - try{jdbc.update("INSERT INTO feishu_directory_state(id) SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM feishu_directory_state WHERE id=1)");} + try{jdbc.update("INSERT INTO feishu_directory_state(id,tenant_id) SELECT 1,? WHERE NOT EXISTS (SELECT 1 FROM feishu_directory_state WHERE tenant_id=? AND id=1)",systemTenant,systemTenant);} catch(DuplicateKeyException ignored){ } } public Map status(){ - Map state=null;try{state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");}catch(RuntimeException ignored){} + Map state=null;try{state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant);}catch(RuntimeException ignored){} FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time); String context=currentContext(); Instant success=publication.getSuccessfulAt(); - Integer active=null;try{active=jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')",Integer.class);}catch(RuntimeException ignored){} + Integer active=null;try{active=jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')",Integer.class,systemTenant);}catch(RuntimeException ignored){} Map result=new LinkedHashMap<>();result.put("configured",context!=null);result.put("running",active!=null&&active>0);result.put("snapshotState",publication.getSnapshotState());result.put("availabilityState",publication.getAvailabilityState());result.put("additionsAllowed",publication.isAdditionsAllowed());result.put("contextState",publication.contextState(context).name());result.put("storageMode","CURRENT_STATE");result.put("currentRevision",publication.getRevision());result.put("maxStatusAgeSeconds",0);result.put("lastSuccessfulRunId",publication.getRevision());result.put("lastSuccessfulAt",success==null?null:success.toString());result.put("snapshotExpiresAt",null); - Run last=null;try{List ids=jdbc.query("SELECT run_id FROM feishu_directory_sync_run ORDER BY queued_at DESC,run_id DESC LIMIT 1",(rs,row)->rs.getString(1));if(!ids.isEmpty())last=runs.loadPublic(ids.get(0));}catch(Exception ignored){last=parse(state==null?null:(String)state.get("last_run"));} + Run last=null;try{List ids=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE tenant_id=? ORDER BY queued_at DESC,run_id DESC LIMIT 1",(rs,row)->rs.getString(1),systemTenant);if(!ids.isEmpty())last=runs.loadPublic(ids.get(0));}catch(Exception ignored){last=parse(state==null?null:(String)state.get("last_run"));} result.put("lastRun",last);return result; } @@ -98,7 +101,7 @@ public class FeishuDirectoryService { if(!organizationPermits.tryAcquire())return unavailable; try{ OrganizationSnapshot captured=organizationSnapshot.execute(status->{ - Map state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1"); + Map state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant); FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time); Instant success=publication.getSuccessfulAt(); Map result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN"); @@ -111,7 +114,7 @@ public class FeishuDirectoryService { if(!revalidate(captured.publication))return unavailable; captured.value.put("contextState",captured.publication.contextState(currentContext()).name()); return captured.value; - }catch(Exception ignored){log.warn("Feishu organization snapshot could not be read");return unavailable;} + }catch(Exception ignored){log.warn("无法读取飞书组织快照");return unavailable;} finally{organizationPermits.release();} } @@ -124,7 +127,7 @@ public class FeishuDirectoryService { String target=departmentId.trim(); try{ OrganizationSnapshot captured=organizationSnapshot.execute(status->{ - Map state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1"); + Map state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant); FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time); Instant success=publication.getSuccessfulAt(); Map result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN"); @@ -142,7 +145,7 @@ public class FeishuDirectoryService { if(!revalidate(captured.publication))return unavailable; captured.value.put("contextState",captured.publication.contextState(currentContext()).name()); return captured.value; - }catch(Exception ignored){log.warn("Feishu organization members could not be read");return unavailable;} + }catch(Exception ignored){log.warn("无法读取飞书组织成员");return unavailable;} finally{organizationPermits.release();} } @@ -169,7 +172,7 @@ public class FeishuDirectoryService { /** A separate READ_COMMITTED transaction observes publications committed during materialization. */ private boolean revalidate(FeishuDirectoryPublication captured){ Boolean stable=observation.execute(status->{ - Map current=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1"); + Map current=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant); FeishuDirectoryPublication now=FeishuDirectoryPublication.classify(current,time); return now.isAvailable()&&Objects.equals(captured.getRevision(),now.getRevision()) &&Objects.equals(captured.getSuccessfulContext(),now.getSuccessfulContext()) @@ -213,7 +216,13 @@ public class FeishuDirectoryService { } return"UNEXPECTED"; } - static String failureMessage(String diagnostic){return"Directory sync failed; current directory retained. Check Feishu contact permissions, app visibility and configuration. 目录同步失败,已保留当前通讯录;请检查飞书通讯录权限、应用可见范围和配置。 Diagnostic category: "+diagnostic+".";} + static String failureMessage(String diagnostic){ + if("DIRECTORY_USER_RESIGNATION_FIELD_UNAVAILABLE".equals(diagnostic)) + return"Directory sync failed; current directory retained. Feishu did not return base_info.is_resigned. Verify that either directory:employee.base.is_resigned:read or directory:employee.base.status:read is granted and published; if already authorized, verify the Directory-v1 response field contract and that the application and tenant match. 目录同步失败,已保留当前通讯录;飞书未返回离职状态字段。请检查上述两种权限之一是否已授予并发布;若已授权,请继续检查 Directory-v1 返回字段契约,以及应用与租户是否匹配。 Diagnostic category: "+diagnostic+"."; + if("DIRECTORY_USER_RESIGNATION_FIELD_INVALID".equals(diagnostic)) + return"Directory sync failed; current directory retained. Feishu returned an invalid base_info.is_resigned value; retry after checking the Directory-v1 field contract. 目录同步失败,已保留当前通讯录;飞书返回的离职状态字段不符合布尔契约,请检查 Directory-v1 字段契约后重试。 Diagnostic category: "+diagnostic+"."; + return"Directory sync failed; current directory retained. Check Feishu contact permissions, app visibility and configuration. 目录同步失败,已保留当前通讯录;请检查飞书通讯录权限、应用可见范围和配置。 Diagnostic category: "+diagnostic+"."; + } @Data public static class Run {private String runId,trigger,state="RUNNING",startedAt,finishedAt;private boolean complete,applied;private Counts counts=new Counts();private String errorCode,errorMessage;} @Data public static class Counts {private int departments,usersSeen,excluded,created,updated,outOfScope;@JsonIgnore private int eligible;@JsonIgnore private int ineligible;@JsonIgnore public int getEligible(){return eligible;}@JsonIgnore public int getIneligible(){return ineligible;}} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java index 8dfec05..2af0c3a 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java @@ -35,7 +35,7 @@ public class FeishuDirectorySyncDispatcher implements SmartLifecycle { catch(Throwable ex){ // Context shutdown closes the shared Hibernate session/pool while a tick may still be in flight. if(!running.get()||isShutdownNoise(ex))return; - log.warn("Feishu directory dispatcher iteration failed: {}", ex.toString()); + log.warn("飞书通讯录同步调度轮询失败: {}", ex.toString()); } } private static boolean isShutdownNoise(Throwable ex){ diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java index 6226d0f..03860dd 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java @@ -45,7 +45,7 @@ public class FeishuDirectorySyncWorker { succeeded=true; }catch(Throwable failure){ String code=FeishuDirectoryService.safeDiagnostic(failure,phase); - log.warn("Feishu directory attempt failed: runId={}, attempt={}, phase={}, errorCode={}, failureType={}", + log.warn("飞书通讯录同步尝试失败: runId={}, attempt={}, phase={}, errorCode={}, failureType={}", claim.getRunId(),claim.getAttempt(),phase,code,FeishuDirectoryService.safeFailureType(failure)); runs.recordFailure(claim,code,FeishuDirectoryService.failureMessage(code)); }finally{heartbeat.cancel(false);} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java index a97bca0..ca0cc8e 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java @@ -4,7 +4,9 @@ import com.finance.system.entity.SysUser; import com.finance.system.exception.BusinessException; import com.finance.system.repository.SysUserRepository; import com.finance.system.service.FeishuDirectoryLock; +import lombok.extern.slf4j.Slf4j; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -20,12 +22,17 @@ import java.util.Objects; * columns can be written. Role/status and directory observations are never written here. */ @Service +@Slf4j public class FeishuLoginPersistenceService { private final JdbcTemplate jdbc; private final EntityManager em; private final SysUserRepository users; private final FeishuDirectoryAccessService access; private final TransactionTemplate tx; + @Value("${observability.tenant-id:default}") + private String deploymentTenant = "default"; + @Value("${observability.organization-id:1}") + private Long deploymentOrganizationId = 1L; public FeishuLoginPersistenceService(JdbcTemplate jdbc, EntityManager em, SysUserRepository users, FeishuDirectoryAccessService access, FeishuTenantTokenService tokens, PlatformTransactionManager manager) { this.jdbc = jdbc; this.em = em; this.users = users; this.access = access; @@ -50,14 +57,25 @@ public class FeishuLoginPersistenceService { SysUser fresh = locked(id); // open_id is the only Feishu identity used for account matching. // Never replace it or adopt an account using user_id alone. - if (!Objects.equals(fresh.getFeishuOpenId(), openId)) throw denied(); + if (!Objects.equals(fresh.getFeishuOpenId(), openId)) throw bindingDenied(); + String tenantId = deploymentTenant(); + long organizationId = deploymentOrganizationId(); + if (!tenantId.equals(fresh.getTenantId())) throw bindingDenied(); + if (fresh.getOrganizationId() == null) { + int repaired = jdbc.update("UPDATE sys_user SET organization_id=?,updated_at=CURRENT_TIMESTAMP(6) " + + "WHERE id=? AND tenant_id=? AND organization_id IS NULL", + organizationId, id, tenantId); + if (repaired != 1) throw bindingDenied(); + em.refresh(fresh); + } + if (!Objects.equals(fresh.getOrganizationId(), organizationId)) throw bindingDenied(); String counterpart = info.getUserId() == null ? null : info.getUserId().trim(); if (counterpart != null && counterpart.isEmpty()) counterpart = null; String existingUserId = fresh.getFeishuUserId(); if (counterpart != null && existingUserId != null && !existingUserId.trim().isEmpty() - && !counterpart.equals(existingUserId)) throw denied(); - if (counterpart != null && jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE feishu_user_id=? AND id<>?", Integer.class, counterpart, id) != 0) throw denied(); + && !counterpart.equals(existingUserId)) throw bindingDenied(); + if (counterpart != null && jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE feishu_user_id=? AND id<>?", Integer.class, counterpart, id) != 0) throw bindingDenied(); String name = info.getName() == null || info.getName().trim().isEmpty() ? fresh.getRealName() : info.getName(); validate(name, 100); validate(info.getAvatarUrl(), 500); validate(info.getEmail(), 200); validate(info.getMobile(), 20); validate(counterpart, 100); jdbc.update("UPDATE sys_user SET real_name=?,avatar_url=?,email=?,mobile=?,feishu_user_id=CASE WHEN feishu_user_id IS NULL OR TRIM(feishu_user_id)='' THEN ? ELSE feishu_user_id END,last_login_at=? WHERE id=?", @@ -92,5 +110,20 @@ public class FeishuLoginPersistenceService { private static String keepExisting(String incoming, String existing) { return incoming == null || incoming.trim().isEmpty() ? existing : incoming; } + private String deploymentTenant() { + if (deploymentTenant == null || deploymentTenant.trim().isEmpty()) throw boundaryUnavailable(); + return deploymentTenant.trim(); + } + private long deploymentOrganizationId() { + if (deploymentOrganizationId == null || deploymentOrganizationId <= 0) throw boundaryUnavailable(); + return deploymentOrganizationId; + } + private static BusinessException bindingDenied() { + log.warn("飞书登录身份归属冲突,登录完成操作被拒绝 event=feishu.oauth.finalize outcome=denied conflictType=IDENTITY_OWNERSHIP"); + return new BusinessException("飞书账号已绑定其他账户,请联系管理员", 403); + } + private static BusinessException boundaryUnavailable() { + return new BusinessException("飞书账号部署边界未配置", 503); + } private static BusinessException denied() { return new BusinessException("Active Feishu identity binding required", 403); } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java new file mode 100644 index 0000000..0db1342 --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java @@ -0,0 +1,81 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.exception.BusinessException; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.function.LongSupplier; + +/** Short-lived, bounded server-side binding between OAuth state and a trusted frontend origin. */ +@Component +public class FeishuOAuthStateOriginStore { + static final long DEFAULT_TTL_MILLIS = 5L * 60L * 1000L; + static final int DEFAULT_MAX_ENTRIES = 4096; + + private final Map entries = new HashMap<>(); + private final LongSupplier clock; + private final long ttlMillis; + private final int maxEntries; + + public FeishuOAuthStateOriginStore() { + this(System::currentTimeMillis, DEFAULT_TTL_MILLIS, DEFAULT_MAX_ENTRIES); + } + + FeishuOAuthStateOriginStore(LongSupplier clock, long ttlMillis, int maxEntries) { + this.clock = clock; + this.ttlMillis = ttlMillis; + this.maxEntries = maxEntries; + } + + public synchronized void bind(String state, String trustedOrigin) { + if (state == null || !state.matches("[A-Za-z0-9_-]{43}") || trustedOrigin == null) { + throw new BusinessException("飞书登录状态创建失败", 503); + } + long now = clock.getAsLong(); + cleanup(now); + if (entries.containsKey(state)) { + throw new BusinessException("飞书登录状态创建失败", 503); + } + if (!entries.containsKey(state) && entries.size() >= maxEntries) { + throw new BusinessException("飞书登录请求过多,请稍后重试", 503); + } + entries.put(state, new Entry(trustedOrigin, now + ttlMillis)); + } + + /** Atomically returns the trusted origin once; replays and expiry fail closed. */ + public synchronized String consume(String state) { + long now = clock.getAsLong(); + cleanup(now); + Entry entry = entries.get(state); + if (entry == null || entry.consumed) { + throw new BusinessException("飞书登录状态无效或已过期", 400); + } + entry.consumed = true; + return entry.origin; + } + + synchronized int size() { + cleanup(clock.getAsLong()); + return entries.size(); + } + + private void cleanup(long now) { + Iterator> iterator = entries.entrySet().iterator(); + while (iterator.hasNext()) { + if (iterator.next().getValue().expiresAt <= now) iterator.remove(); + } + } + + private static final class Entry { + private final String origin; + private final long expiresAt; + private boolean consumed; + + private Entry(String origin, long expiresAt) { + this.origin = origin; + this.expiresAt = expiresAt; + } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java index cef5136..8904291 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java @@ -17,6 +17,13 @@ import java.util.concurrent.TimeUnit; @Service public class FeishuTenantTokenService { static final String API = "https://open.feishu.cn/open-apis"; + static final String DIRECTORY_CONTEXT_POLICY = + "api=directory-v1-filter;employee_id_type=open_id;department_id_type=open_department_id" + + ";department_filter=parent_department_id:eq:json-string:bfs-root-0" + + ";employee_transport_partition=work_info.staff_status:eq:1,2,3,4,5:not-projected:not-persisted" + + ";required_field=base_info.is_resigned:boolean" + + ";resignation_policy=is_resigned:false:business-eligible-current-directory-all-statuses" + + ";policy=directory-v1-6"; private static final BigInteger SUCCESS_CODE = BigInteger.ZERO; private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L); private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L); @@ -81,7 +88,7 @@ public class FeishuTenantTokenService { throw diagnostic("CONFIGURATION_UNAVAILABLE"); } if (values == null) throw diagnostic("CONFIGURATION_MISSING"); - String app = values.get("appId"), secret = values.get("appSecret"); + String app = trim(values.get("appId")), secret = trim(values.get("appSecret")); // A disabled integration is deliberately reported as configuration missing, // while the independent directory-sync switch is reported as SYNC_DISABLED. // Neither path exposes the configured values. @@ -89,13 +96,14 @@ public class FeishuTenantTokenService { || !Boolean.parseBoolean(values.get(IntegrationConfigReader.INTERNAL_ENABLED_KEY))) throw diagnostic("CONFIGURATION_MISSING"); return new Context(app, secret, fingerprint(app + "\n" + secret - + "\napi=directory-v1-filter;employee_id_type=open_id;department_id_type=open_department_id" - + ";department_filter=parent_department_id:eq:json-string:bfs-root-0" - + ";employee_transport_partition=work_info.staff_status:eq:1,2,3,4,5:not-projected:not-persisted" - + ";policy=directory-v1-4\n" + + "\n" + DIRECTORY_CONTEXT_POLICY + "\n" + settings.getCredentialRevision())); } + private static String trim(String value) { + return value == null ? null : value.trim(); + } + public boolean syncEnabled() { try { Map values = config.freshFeishu(); @@ -104,16 +112,27 @@ public class FeishuTenantTokenService { catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); } } public String getTenantAccessToken() { return token(capture()); } + public String getAppAccessToken() { return appToken(capture()); } public String token(Context context) { + return token(context, "/auth/v3/tenant_access_token/internal", "tenant_access_token"); + } + + String appToken(Context context) { + return token(context, "/auth/v3/app_access_token/internal", "app_access_token"); + } + + private String token(Context context, String endpoint, String responseField) { if (context == null) throw diagnostic("TOKEN_CONTEXT_MISSING"); Map body = new HashMap<>(); body.put("app_id", context.app); body.put("app_secret", context.secret); long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(settings.elapsed()); int retries=0; while(true){ try { - ResponseEntity exchange=http.exchange(API + "/auth/v3/tenant_access_token/internal", - HttpMethod.POST,new HttpEntity<>(body),JsonNode.class); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + ResponseEntity exchange=http.exchange(API + endpoint, + HttpMethod.POST,new HttpEntity<>(body, headers),JsonNode.class); JsonNode response=exchange.getBody(); BigInteger responseCode = responseCode(response); if (RATE_LIMIT_CODE.equals(responseCode)) { @@ -127,10 +146,10 @@ public class FeishuTenantTokenService { Long code = safeCode(response); throw code == null ? diagnostic("TOKEN_RESPONSE_INVALID") : diagnostic("FEISHU_CODE_" + code); } - if (!response.path("tenant_access_token").isTextual() - || response.path("tenant_access_token").asText().trim().isEmpty()) + if (!response.path(responseField).isTextual() + || response.path(responseField).asText().trim().isEmpty()) throw diagnostic("TOKEN_RESPONSE_INVALID"); - return response.path("tenant_access_token").asText(); + return response.path(responseField).asText(); } catch (DiagnosticFailure ex) { throw ex; } catch (org.springframework.web.client.HttpStatusCodeException ex) { diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java index 5a07f8f..04997dd 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java @@ -9,7 +9,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class FeishuTokenResponse { - private int code; + private Integer code; private String msg; private TokenData data; @@ -29,4 +29,4 @@ public class FeishuTokenResponse { @JsonProperty("refresh_token") private String refreshToken; } -} \ No newline at end of file +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java new file mode 100644 index 0000000..a1e67fc --- /dev/null +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java @@ -0,0 +1,170 @@ +package com.finance.system.adapter.feishu; + +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.service.FeishuDirectoryLock; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.StringUtils; + +import java.sql.Statement; +import java.util.Objects; + +/** + * Owns the independent transaction used by first-time Feishu account creation. + * A uniqueness failure is rolled back before it is returned to the OAuth + * orchestrator, so any recovery lookup runs in a clean transaction context. + */ +@Slf4j +@Service +public class FeishuUserProvisioningService { + private final SysUserRepository users; + private final JdbcTemplate jdbc; + private final TransactionTemplate transaction; + @Value("${observability.tenant-id:default}") + private String deploymentTenant = "default"; + @Value("${observability.organization-id:1}") + private Long deploymentOrganizationId = 1L; + + public FeishuUserProvisioningService(SysUserRepository users, + JdbcTemplate jdbc, + PlatformTransactionManager transactionManager) { + this.users = users; + this.jdbc = jdbc; + this.transaction = new TransactionTemplate(transactionManager); + this.transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.transaction.setTimeout(30); + } + + public SysUser provisionEmployee(FeishuUserInfo info) { + ProvisioningResult result = transaction.execute(status -> createEmployee(info)); + if (result == null || result.user == null || result.user.getId() == null) { + throw new BusinessException("飞书账号创建失败,请稍后重试", 503); + } + log.info("飞书员工账号配置完成 event=feishu.oauth.provision outcome={} accountType=EMPLOYEE", + result.created ? "created" : "recovered"); + return result.user; + } + + private ProvisioningResult createEmployee(FeishuUserInfo info) { + if (info == null || !StringUtils.hasText(info.getOpenId())) { + throw new BusinessException("飞书身份无效,请重新授权", 403); + } + String openId = info.getOpenId().trim(); + String userId = StringUtils.hasText(info.getUserId()) ? info.getUserId().trim() : null; + String tenantId = deploymentTenant(); + long organizationId = deploymentOrganizationId(); + + // Use the same short database mutex as directory publication and OAuth + // finalization. Re-read under that lock to avoid the common in-process + // first-login race without ever discovering/adopting an account by + // user_id alone: only the exact open_id may be returned. + FeishuDirectoryLock.acquire(jdbc); + SysUser existing = users.findByFeishuOpenId(openId); + SysUser userIdOwner = userId == null ? null : users.findByFeishuUserId(userId); + if (existing != null) { + requireCompatibleExactOpen(existing, userIdOwner, userId); + return new ProvisioningResult(existing, false); + } + if (userIdOwner != null) throw bindingConflict(); + + String employeeNo = uniqueEmployeeNo(); + KeyHolder key = new GeneratedKeyHolder(); + PreparedStatementCreator insert = connection -> { + java.sql.PreparedStatement statement = connection.prepareStatement( + "INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,avatar_url,email,mobile," + + "tenant_id,organization_id,user_type,status,directory_status,created_at,updated_at) " + + "VALUES (?,?,?,?,?,?,?,?,?,'EMPLOYEE','ACTIVE','UNKNOWN',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", + Statement.RETURN_GENERATED_KEYS); + statement.setString(1, openId); + statement.setString(2, userId); + statement.setString(3, employeeNo); + statement.setString(4, StringUtils.hasText(info.getName()) ? info.getName() : "Feishu User"); + statement.setString(5, info.getAvatarUrl()); + statement.setString(6, info.getEmail()); + statement.setString(7, info.getMobile()); + statement.setString(8, tenantId); + statement.setLong(9, organizationId); + return statement; + }; + try { + jdbc.update(insert, key); + } catch (DataIntegrityViolationException conflict) { + // Do not let a vendor SQLException (which may contain identifier + // values) reach TransactionTemplate's diagnostic logging. The + // orchestrator still receives a DataIntegrityViolationException, + // but its message contains only a whitelisted constraint category. + throw sanitizedConflict(conflict); + } + Number generated = key.getKey(); + if (generated == null) throw new BusinessException("飞书账号创建失败,请稍后重试", 503); + SysUser inserted = users.findById(generated.longValue()) + .orElseThrow(() -> new BusinessException("飞书账号创建失败,请稍后重试", 503)); + return new ProvisioningResult(inserted, true); + } + + private void requireCompatibleExactOpen(SysUser existing, SysUser userIdOwner, String requestedUserId) { + if (!deploymentTenant().equals(existing.getTenantId())) throw bindingConflict(); + if (userIdOwner != null && !Objects.equals(existing.getId(), userIdOwner.getId())) { + throw bindingConflict(); + } + String boundUserId = StringUtils.hasText(existing.getFeishuUserId()) + ? existing.getFeishuUserId().trim() : null; + if (boundUserId != null && requestedUserId != null && !boundUserId.equals(requestedUserId)) { + throw bindingConflict(); + } + } + + private DataIntegrityViolationException sanitizedConflict(DataIntegrityViolationException conflict) { + String category = FeishuAuthService.constraintCategory(conflict); + return new DataIntegrityViolationException("FEISHU_OAUTH_" + category); + } + + private BusinessException bindingConflict() { + log.warn("飞书员工账号身份归属冲突,账号配置被拒绝 event=feishu.oauth.provision outcome=denied conflictType=IDENTITY_OWNERSHIP"); + return new BusinessException("飞书账号已绑定其他账户,请联系管理员", 403); + } + + private String uniqueEmployeeNo() { + for (int attempt = 0; attempt < 5; attempt++) { + String number = "FS-" + java.util.UUID.randomUUID(); + if (users.findByEmployeeNo(number) == null) return number; + } + throw new BusinessException("员工编号生成失败,请稍后重试", 503); + } + + private String deploymentTenant() { + if (!StringUtils.hasText(deploymentTenant)) { + throw new BusinessException("飞书账号部署边界未配置", 503); + } + return deploymentTenant.trim(); + } + + private long deploymentOrganizationId() { + if (deploymentOrganizationId == null || deploymentOrganizationId <= 0) { + throw new BusinessException("飞书账号部署边界未配置", 503); + } + return deploymentOrganizationId; + } + + private static final class ProvisioningResult { + private final SysUser user; + private final boolean created; + + private ProvisioningResult(SysUser user, boolean created) { + this.user = user; + this.created = created; + } + } +} diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java index 9e210d9..47d7115 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java @@ -9,7 +9,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class FeishuUserResponse { - private int code; + private Integer code; private String msg; private UserData data; @@ -30,4 +30,4 @@ public class FeishuUserResponse { @JsonProperty("avatar_url") private String avatarUrl; } -} \ No newline at end of file +} diff --git a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java index e609d29..100c9df 100644 --- a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java +++ b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java @@ -36,9 +36,10 @@ public final class ReimbursementCanonicalizer { field(out, "feishuFormDisplayValues", app.getFeishuFormDisplayValues()); field(out, "bankName", bank == null ? null : bank.getBankName()); field(out, "branchName", bank == null ? null : bank.getBranchName()); - field(out, "accountName", bank == null ? null : bank.getAccountName()); - field(out, "accountNo", bank == null ? null : bank.getAccountNo()); field(out, "accountNoMask", bank == null ? null : bank.getAccountNoMask()); + // Metadata detects an account change without placing plaintext, ciphertext, + // or the equality fingerprint in the Feishu canonical representation. + field(out, "bankAccountUpdatedAt", bank == null ? null : bank.getUpdatedAt()); for (ReimExpenseItem item : orderedItems(sourceItems)) { field(out, "item.seq", item.getSeqNo()); field(out, "item.date", item.getExpenseDate()); diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java index b3592a4..18e70e7 100644 --- a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java +++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java @@ -7,6 +7,7 @@ import com.finance.system.service.IntegrationConfigReader; import com.finance.system.service.IntegrationConfigService; import com.finance.system.service.KingdeeAccountBindingService; import com.finance.system.util.AuditUtil; +import com.finance.system.security.UserPrincipal; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -89,9 +90,12 @@ public class KingdeeClient { if (kingdeeAccountBindingService == null) { throw new BusinessException("金蝶员工账号绑定服务未配置"); } - Long userId = AuditUtil.getCurrentUserId(); + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null || principal.getId() == null || principal.getTenantId() == null) { + throw new BusinessException("缺少可信的金蝶操作员租户边界", 403); + } KingdeeAccountBindingService.KingdeeCredentials credentials = - kingdeeAccountBindingService.requireCredentials(userId); + kingdeeAccountBindingService.requireCredentials(principal.getId(), principal.getTenantId()); String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc"; String userSession = authenticate(credentials.getUsername(), credentials.getPassword()); return executeKingdeeApi(url, formId, data, userSession); diff --git a/src/main/java/com/finance/system/audit/AuditDeliveryService.java b/src/main/java/com/finance/system/audit/AuditDeliveryService.java new file mode 100644 index 0000000..d085351 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditDeliveryService.java @@ -0,0 +1,128 @@ +package com.finance.system.audit; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class AuditDeliveryService { + private final AuditOutboxRepository outboxRepository; + private final AuditEventRepository eventRepository; + private final AuditEventAppender eventAppender; + private final AuditEventPolicy policy; + private final ObjectMapper objectMapper; + private final AuditIntegrityService integrityService; + + @Value("${observability.audit.max-attempts:10}") + private int maxAttempts; + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public boolean deliver(Long outboxId, String owner) { + Optional optional = outboxRepository.findOwnedByIdForUpdate(outboxId, owner); + if (!optional.isPresent()) return false; + AuditOutbox outbox = optional.get(); + LocalDateTime now = AuditEventService.utcNow(); + if (!"PENDING".equals(outbox.getStatus()) || outbox.getLeaseUntil() == null + || !outbox.getLeaseUntil().isAfter(now)) return false; + if (outbox.getAvailableAt().isAfter(now)) return false; + + AuditEventCommand command; + try { + command = objectMapper.readValue(outbox.getEventPayload(), AuditEventCommand.class); + } catch (JsonProcessingException e) { + throw new IllegalStateException("AUDIT_PAYLOAD_INVALID", e); + } + policy.validate(command); + if (!eventRepository.existsByEventUid(command.getEventId())) { + eventAppender.append(toEntity(command)); + } + outbox.setStatus("PUBLISHED"); + outbox.setPublishedAt(now); + outbox.setLastErrorCode(null); + clearLease(outbox); + return true; + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public boolean markFailure(Long outboxId, String owner, String errorCode) { + Optional optional = outboxRepository.findOwnedByIdForUpdate(outboxId, owner); + if (!optional.isPresent()) return false; + AuditOutbox outbox = optional.get(); + LocalDateTime now = AuditEventService.utcNow(); + if (!"PENDING".equals(outbox.getStatus()) || outbox.getLeaseUntil() == null + || !outbox.getLeaseUntil().isAfter(now)) return false; + int attempts = outbox.getAttemptCount() == null ? 1 : outbox.getAttemptCount() + 1; + outbox.setAttemptCount(attempts); + outbox.setLastErrorCode(safeErrorCode(errorCode)); + if (attempts >= Math.max(1, maxAttempts)) { + outbox.setStatus("DEAD"); + } else { + outbox.setStatus("PENDING"); + long delaySeconds = Math.min(300L, 1L << Math.min(8, attempts)); + outbox.setAvailableAt(now.plusSeconds(delaySeconds)); + } + clearLease(outbox); + return true; + } + + private static void clearLease(AuditOutbox outbox) { + outbox.setLeaseOwner(null); + outbox.setLeaseUntil(null); + } + + private AuditEvent toEntity(AuditEventCommand command) { + LocalDateTime occurred = LocalDateTime.ofInstant( + command.getEventTime() == null ? Instant.now() : command.getEventTime(), ZoneOffset.UTC); + AuditEvent event = AuditEvent.builder() + .eventUid(command.getEventId()) + .schemaVersion(command.getSchemaVersion() == null ? 1 : command.getSchemaVersion()) + .occurredAt(occurred) + .recordedAt(AuditEventService.utcNow()) + .tenantId(command.getTenantId()) + .organizationId(command.getOrganizationId()) + .category(command.getCategory()) + .actionCode(command.getAction()) + .outcome(command.getOutcome()) + .reasonCode(command.getReasonCode()) + .actorType(command.getActorType()) + .actorId(command.getActorId()) + .targetType(command.getTargetType()) + .targetId(command.getTargetId()) + .resourceType(command.getResourceType()) + .resourceId(command.getResourceId()) + .requestId(command.getRequestId()) + .traceId(command.getTraceId()) + .spanId(command.getSpanId()) + .sourceChannel(command.getSource()) + .clientIpHash(command.getClientIpHash()) + .changedFields(writeJson(command.getChanges())) + .attributes(writeJson(command.getAttributes())) + .build(); + event.setIntegrityHash(integrityService.sign(event)); + return event; + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new IllegalStateException("AUDIT_PAYLOAD_INVALID", e); + } + } + + private static String safeErrorCode(String value) { + if (value != null && value.matches("[A-Z0-9_]{1,80}")) return value; + return "AUDIT_DELIVERY_FAILED"; + } +} + diff --git a/src/main/java/com/finance/system/audit/AuditEvent.java b/src/main/java/com/finance/system/audit/AuditEvent.java new file mode 100644 index 0000000..89af49b --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEvent.java @@ -0,0 +1,83 @@ +package com.finance.system.audit; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.Immutable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Immutable +@Table(name = "sys_audit_event") +public class AuditEvent { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "event_uid", nullable = false, unique = true, length = 32) + private String eventUid; + @Column(name = "schema_version", nullable = false) + private Integer schemaVersion; + @Column(name = "occurred_at", nullable = false) + private LocalDateTime occurredAt; + @Column(name = "recorded_at", nullable = false) + private LocalDateTime recordedAt; + @Column(name = "tenant_id", nullable = false, length = 64) + private String tenantId; + @Column(name = "organization_id", nullable = false) + private Long organizationId; + @Column(nullable = false, length = 24) + private String category; + @Column(name = "action_code", nullable = false, length = 120) + private String actionCode; + @Column(nullable = false, length = 16) + private String outcome; + @Column(name = "reason_code", length = 80) + private String reasonCode; + @Column(name = "actor_type", nullable = false, length = 16) + private String actorType; + @Column(name = "actor_id") + private Long actorId; + @Column(name = "target_type", length = 64) + private String targetType; + @Column(name = "target_id", length = 128) + private String targetId; + @Column(name = "resource_type", nullable = false, length = 64) + private String resourceType; + @Column(name = "resource_id", nullable = false, length = 128) + private String resourceId; + @Column(name = "request_id", length = 64) + private String requestId; + @Column(name = "trace_id", length = 32) + private String traceId; + @Column(name = "span_id", length = 16) + private String spanId; + @Column(name = "source_channel", nullable = false, length = 24) + private String sourceChannel; + @Column(name = "client_ip_hash", length = 64) + private String clientIpHash; + @Lob + @Column(name = "changed_fields", columnDefinition = "MEDIUMTEXT") + private String changedFields; + @Lob + @Column(columnDefinition = "MEDIUMTEXT") + private String attributes; + @Column(name = "integrity_algorithm", nullable = false, length = 32) + private String integrityAlgorithm; + @Column(name = "integrity_key_id", nullable = false, length = 64) + private String integrityKeyId; + @Column(name = "integrity_hash", nullable = false, length = 64) + private String integrityHash; +} diff --git a/src/main/java/com/finance/system/audit/AuditEventAppender.java b/src/main/java/com/finance/system/audit/AuditEventAppender.java new file mode 100644 index 0000000..6baeaf0 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventAppender.java @@ -0,0 +1,19 @@ +package com.finance.system.audit; + +import org.springframework.stereotype.Component; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +/** The sole application write path for the immutable audit event table. */ +@Component +public class AuditEventAppender { + @PersistenceContext + private EntityManager entityManager; + + public void append(AuditEvent event) { + if (event == null || event.getId() != null) throw new IllegalArgumentException("AUDIT_APPEND_INVALID"); + entityManager.persist(event); + entityManager.flush(); + } +} diff --git a/src/main/java/com/finance/system/audit/AuditEventCommand.java b/src/main/java/com/finance/system/audit/AuditEventCommand.java new file mode 100644 index 0000000..b083126 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventCommand.java @@ -0,0 +1,39 @@ +package com.finance.system.audit; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.Instant; +import java.util.Map; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AuditEventCommand { + private String eventId; + private Integer schemaVersion; + private Instant eventTime; + private String tenantId; + private Long organizationId; + private String category; + private String action; + private String outcome; + private String reasonCode; + private String actorType; + private Long actorId; + private String targetType; + private String targetId; + private String resourceType; + private String resourceId; + private String requestId; + private String traceId; + private String spanId; + private String source; + private String clientIpHash; + private Map changes; + private Map attributes; +} + diff --git a/src/main/java/com/finance/system/audit/AuditEventPolicy.java b/src/main/java/com/finance/system/audit/AuditEventPolicy.java new file mode 100644 index 0000000..ed09feb --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventPolicy.java @@ -0,0 +1,154 @@ +package com.finance.system.audit; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +@Component +public class AuditEventPolicy { + // Versioned deny-by-default audit schemas are enforced below. + static final int MAX_DEPTH = 5; + static final int MAX_NODES = 256; + static final int MAX_SERIALIZED_BYTES = 16 * 1024; + static final int MAX_STRING_LENGTH = 512; + private static final Pattern CODE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,119}"); + private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Set CATEGORIES = new HashSet<>(Arrays.asList( + "SECURITY", "ADMIN", "BUSINESS", "INTEGRATION")); + private static final Set OUTCOMES = new HashSet<>(Arrays.asList( + "SUCCESS", "FAILURE", "DENIED", "UNKNOWN")); + private static final Set ACTOR_TYPES = new HashSet<>(Arrays.asList( + "USER", "SYSTEM", "SERVICE", "ANONYMOUS")); + private static final Set SOURCES = new HashSet<>(Arrays.asList( + "WEB", "JOB", "WEBHOOK", "OAUTH", "INTERNAL")); + private final ObjectMapper objectMapper; + private final AuditEventSchemaRegistry schemaRegistry; + + public AuditEventPolicy() { + this(new ObjectMapper().findAndRegisterModules(), + Collections.emptyList()); + } + + @Autowired + public AuditEventPolicy(ObjectMapper objectMapper, List contributors) { + this.objectMapper = objectMapper; + this.schemaRegistry = new AuditEventSchemaRegistry(contributors); + } + + public void validate(AuditEventCommand event) { + if (event == null) throw new IllegalArgumentException("audit event is required"); + if (!StringUtils.hasText(event.getEventId()) || event.getEventId().length() > 32 + || !SAFE_ID.matcher(event.getEventId()).matches()) { + throw new IllegalArgumentException("invalid audit eventId"); + } + if (!StringUtils.hasText(event.getTenantId()) || event.getTenantId().length() > 64 + || !SAFE_ID.matcher(event.getTenantId()).matches()) { + throw new IllegalArgumentException("invalid audit tenantId"); + } + if (event.getOrganizationId() == null || event.getOrganizationId() <= 0) { + throw new IllegalArgumentException("invalid audit organizationId"); + } + requireCode(event.getCategory(), "category"); + requireCode(event.getAction(), "action"); + requireCode(event.getOutcome(), "outcome"); + requireCode(event.getActorType(), "actorType"); + requireCode(event.getResourceType(), "resourceType"); + requireId(event.getResourceId(), "resourceId"); + requireCode(event.getSource(), "source"); + optionalCode(event.getReasonCode(), "reasonCode"); + optionalCode(event.getTargetType(), "targetType"); + if (StringUtils.hasText(event.getTargetId())) requireId(event.getTargetId(), "targetId"); + optionalId(event.getRequestId(), 64, "requestId"); + optionalHex(event.getTraceId(), 32, "traceId"); + optionalHex(event.getSpanId(), 16, "spanId"); + optionalHex(event.getClientIpHash(), 64, "clientIpHash"); + if (!CATEGORIES.contains(event.getCategory())) throw new IllegalArgumentException("invalid audit category"); + if (!OUTCOMES.contains(event.getOutcome())) throw new IllegalArgumentException("invalid audit outcome"); + if (!ACTOR_TYPES.contains(event.getActorType())) throw new IllegalArgumentException("invalid actor type"); + if (!SOURCES.contains(event.getSource())) throw new IllegalArgumentException("invalid audit source"); + validateComplexityAndSize(event); + schemaRegistry.validate(event); + } + + private void validateComplexityAndSize(AuditEventCommand event) { + int[] nodes = {0}; + validateValue(event.getChanges(), 0, nodes); + validateValue(event.getAttributes(), 0, nodes); + try { + if (objectMapper.writeValueAsBytes(event).length > MAX_SERIALIZED_BYTES) + throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_BYTES"); + } catch (IllegalArgumentException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_SERIALIZATION", e); + } + } + + private void validateValue(Object value, int depth, int[] nodes) { + if (depth > MAX_DEPTH) throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_DEPTH"); + if (++nodes[0] > MAX_NODES) throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_NODES"); + if (value == null || value instanceof Number || value instanceof Boolean) return; + if (value instanceof String) { + requireText((String) value, MAX_STRING_LENGTH, "attribute value"); + return; + } + if (value instanceof Map) { + for (Map.Entry entry : ((Map) value).entrySet()) { + requireCode(String.valueOf(entry.getKey()), "attribute key"); + validateValue(entry.getValue(), depth + 1, nodes); + } + return; + } + if (value instanceof Collection) { + Collection collection = (Collection) value; + for (Object element : collection) validateValue(element, depth + 1, nodes); + return; + } + throw new IllegalArgumentException("unsupported audit attribute type"); + } + + private static void requireCode(String value, String field) { + if (!StringUtils.hasText(value) || !CODE.matcher(value).matches()) { + throw new IllegalArgumentException("invalid audit " + field); + } + } + + private static void requireText(String value, int max, String field) { + if (!StringUtils.hasText(value) || value.length() > max || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("invalid audit " + field); + } + } + + private static void requireId(String value, String field) { + if (!StringUtils.hasText(value) || !SAFE_ID.matcher(value).matches()) { + throw new IllegalArgumentException("invalid audit " + field); + } + } + + private static void optionalCode(String value, String field) { + if (StringUtils.hasText(value)) requireCode(value, field); + } + + private static void optionalId(String value, int max, String field) { + if (StringUtils.hasText(value) && (value.length() > max || !SAFE_ID.matcher(value).matches())) { + throw new IllegalArgumentException("invalid audit " + field); + } + } + + private static void optionalHex(String value, int length, String field) { + if (StringUtils.hasText(value) && !value.matches("[0-9a-fA-F]{" + length + "}")) { + throw new IllegalArgumentException("invalid audit " + field); + } + } +} + diff --git a/src/main/java/com/finance/system/audit/AuditEventRepository.java b/src/main/java/com/finance/system/audit/AuditEventRepository.java new file mode 100644 index 0000000..e90092c --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventRepository.java @@ -0,0 +1,14 @@ +package com.finance.system.audit; + +import org.springframework.data.repository.Repository; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +/** Read-only repository surface; append is only available through AuditEventAppender. */ +public interface AuditEventRepository extends Repository { + boolean existsByEventUid(String eventUid); + + List findByIdGreaterThanOrderByIdAsc(Long id, Pageable pageable); +} + diff --git a/src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java b/src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java new file mode 100644 index 0000000..e8db179 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java @@ -0,0 +1,8 @@ +package com.finance.system.audit; + +import java.util.Collection; + +/** Domain extension point. Duplicate schemas fail startup; unknown schemas fail validation. */ +public interface AuditEventSchemaContributor { + Collection schemas(); +} diff --git a/src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java b/src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java new file mode 100644 index 0000000..c9b76e5 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java @@ -0,0 +1,158 @@ +package com.finance.system.audit; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** Explicit category/action/version and field schemas. There is no wildcard schema. */ +public final class AuditEventSchemaRegistry { + private static final Pattern CODE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,119}"); + private final Map schemas = new LinkedHashMap<>(); + + public AuditEventSchemaRegistry(Collection contributors) { + builtIns(); + if (contributors != null) for (AuditEventSchemaContributor contributor : contributors) { + if (contributor != null && contributor.schemas() != null) + for (Schema schema : contributor.schemas()) register(schema); + } + } + + public void validate(AuditEventCommand event) { + int version = event.getSchemaVersion() == null ? 1 : event.getSchemaVersion(); + Schema schema = schemas.get(key(event.getCategory(), event.getAction(), version)); + if (schema == null) throw new IllegalArgumentException("AUDIT_POLICY_SCHEMA_NOT_REGISTERED"); + validateFields(event.getChanges(), schema.changes, "CHANGES"); + validateFields(event.getAttributes(), schema.attributes, "ATTRIBUTES"); + } + + private void validateFields(Map values, Map rules, String location) { + Map actual = values == null ? Collections.emptyMap() : values; + for (Map.Entry entry : actual.entrySet()) { + Rule rule = rules.get(entry.getKey()); + if (rule == null) throw new IllegalArgumentException("AUDIT_POLICY_UNKNOWN_" + location + "_FIELD"); + rule.validate(entry.getValue()); + } + for (Map.Entry entry : rules.entrySet()) { + if (entry.getValue().required && !actual.containsKey(entry.getKey())) + throw new IllegalArgumentException("AUDIT_POLICY_MISSING_" + location + "_FIELD"); + } + } + + private void builtIns() { + register(schema("ADMIN", "iam.role.create", 1, none(), fields("roleCode", code(80)))); + register(schema("ADMIN", "iam.role.update", 1, none(), fields("roleCode", code(80)))); + register(schema("ADMIN", "iam.role.delete", 1, none(), fields("roleCode", code(80)))); + register(schema("ADMIN", "iam.role.permission.update", 1, none(), + fields("roleCode", code(80), "policyCount", integer(0, 10000)))); + register(schema("ADMIN", "iam.group.create", 1, none(), fields("groupCode", code(80)))); + register(schema("ADMIN", "iam.group.update", 1, none(), fields("groupCode", code(80)))); + register(schema("ADMIN", "iam.group.delete", 1, none(), fields("groupCode", code(80)))); + register(schema("ADMIN", "iam.group.role.update", 1, none(), fields("roleCount", integer(0, 10000)))); + register(schema("ADMIN", "iam.group.member.update", 1, none(), fields("memberCount", integer(0, 5000)))); + register(schema("ADMIN", "iam.user.status.update", 1, none(), + fields("statusCode", enumeration("ACTIVE", "INACTIVE")))); + register(schema("ADMIN", "rbac.role.permissions.changed", 1, + fields("permissionCodes", codeList(1000, 120)), none())); + } + + private void register(Schema schema) { + String key = key(schema.category, schema.action, schema.version); + if (schemas.putIfAbsent(key, schema) != null) + throw new IllegalStateException("AUDIT_SCHEMA_DUPLICATE:" + schema.action); + } + + private static String key(String category, String action, int version) { + return category + "\u0000" + action + "\u0000" + version; + } + + public static Schema schema(String category, String action, int version, + Map changes, Map attributes) { + return new Schema(category, action, version, changes, attributes); + } + + public static Map none() { return Collections.emptyMap(); } + + public static Map fields(Object... pairs) { + if (pairs.length % 2 != 0) throw new IllegalArgumentException("AUDIT_SCHEMA_FIELD_PAIRS"); + Map result = new LinkedHashMap<>(); + for (int i = 0; i < pairs.length; i += 2) result.put(String.valueOf(pairs[i]), (Rule) pairs[i + 1]); + return Collections.unmodifiableMap(result); + } + + public static Rule code(int maxLength) { + return new Rule(false, value -> { + if (!(value instanceof String) || ((String) value).length() > maxLength + || !CODE.matcher((String) value).matches()) invalid("FIELD_CODE"); + }); + } + + public static Rule integer(long min, long max) { + return new Rule(false, value -> { + if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long)) + invalid("FIELD_INTEGER"); + long number = ((Number) value).longValue(); + if (number < min || number > max) invalid("FIELD_INTEGER_RANGE"); + }); + } + + public static Rule enumeration(String... allowed) { + List values = Arrays.asList(allowed); + return new Rule(false, value -> { + if (!(value instanceof String) || !values.contains(value)) invalid("FIELD_ENUM"); + }); + } + + public static Rule flag() { + return new Rule(false, value -> { + if (!(value instanceof Boolean)) invalid("FIELD_BOOLEAN"); + }); + } + + public static Rule codeList(int maxItems, int maxLength) { + return new Rule(false, value -> { + if (!(value instanceof Collection)) invalid("FIELD_CODE_LIST"); + Collection list = (Collection) value; + if (list.size() > maxItems) invalid("FIELD_CODE_LIST_SIZE"); + for (Object item : list) if (!(item instanceof String) || ((String) item).length() > maxLength + || !CODE.matcher((String) item).matches()) invalid("FIELD_CODE_LIST_ITEM"); + }); + } + + private static void invalid(String code) { throw new IllegalArgumentException("AUDIT_POLICY_" + code); } + + public static final class Schema { + private final String category; + private final String action; + private final int version; + private final Map changes; + private final Map attributes; + + private Schema(String category, String action, int version, + Map changes, Map attributes) { + this.category = category; + this.action = action; + this.version = version; + this.changes = changes == null ? none() : changes; + this.attributes = attributes == null ? none() : attributes; + } + } + + public static final class Rule { + private final boolean required; + private final Validator validator; + + private Rule(boolean required, Validator validator) { + this.required = required; + this.validator = validator; + } + + public Rule required() { return new Rule(true, validator); } + private void validate(Object value) { validator.validate(value); } + } + + private interface Validator { void validate(Object value); } +} diff --git a/src/main/java/com/finance/system/audit/AuditEventService.java b/src/main/java/com/finance/system/audit/AuditEventService.java new file mode 100644 index 0000000..a534b3e --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditEventService.java @@ -0,0 +1,118 @@ +package com.finance.system.audit; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import lombok.RequiredArgsConstructor; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Collections; +import java.util.UUID; + +@Service +public class AuditEventService implements AuditPort { + private final AuditOutboxRepository outboxRepository; + private final AuditEventPolicy policy; + private final ObjectMapper objectMapper; + private final String systemTenantId; + private final Long systemOrganizationId; + + @Autowired + public AuditEventService(AuditOutboxRepository outboxRepository, AuditEventPolicy policy, + ObjectMapper objectMapper, + @Value("${observability.tenant-id:default}") String systemTenantId, + @Value("${observability.organization-id:1}") Long systemOrganizationId) { + this.outboxRepository = outboxRepository; + this.policy = policy; + this.objectMapper = objectMapper; + this.systemTenantId = systemTenantId; + this.systemOrganizationId = systemOrganizationId; + } + + public AuditEventService(AuditOutboxRepository outboxRepository, AuditEventPolicy policy, + ObjectMapper objectMapper) { + this(outboxRepository, policy, objectMapper, "default", 1L); + } + + @Override + @Transactional + public String emit(AuditEventCommand event) { + normalize(event); + policy.validate(event); + String payload; + try { + payload = objectMapper.writer().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) + .writeValueAsString(event); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("audit event cannot be serialized", e); + } + String payloadHash = sha256(payload); + LocalDateTime now = utcNow(); + // MySQL's unique event_uid and atomic INSERT .. ON DUPLICATE KEY remove + // the exists+save race. This statement participates in the caller's + // transaction; a business rollback also removes the outbox row. + outboxRepository.insertIfAbsent(event.getEventId(), event.getResourceType(), + event.getResourceId(), event.getAction(), payload, payloadHash, now); + AuditOutbox stored = outboxRepository.findByEventUidForUpdate(event.getEventId()) + .orElseThrow(() -> new IllegalStateException("AUDIT_OUTBOX_WRITE_LOST")); + if (!payloadHash.equals(stored.getPayloadHash()) || !payload.equals(stored.getEventPayload())) { + throw new IllegalStateException("AUDIT_EVENT_ID_COLLISION"); + } + return event.getEventId(); + } + + private void normalize(AuditEventCommand event) { + if (event == null) return; + if (!StringUtils.hasText(event.getEventId())) { + event.setEventId(UUID.randomUUID().toString().replace("-", "")); + } + if (event.getSchemaVersion() == null) event.setSchemaVersion(1); + if (event.getEventTime() == null) event.setEventTime(Instant.now()); + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal != null) { + if (!StringUtils.hasText(principal.getTenantId()) || principal.getOrganizationId() == null + || principal.getOrganizationId() <= 0) { + throw new IllegalArgumentException("AUDIT_TRUSTED_CONTEXT_REQUIRED"); + } + event.setTenantId(principal.getTenantId()); + event.setOrganizationId(principal.getOrganizationId()); + } else { + if (!StringUtils.hasText(systemTenantId) || systemOrganizationId == null + || systemOrganizationId <= 0) { + throw new IllegalArgumentException("AUDIT_SYSTEM_CONTEXT_REQUIRED"); + } + event.setTenantId(systemTenantId); + event.setOrganizationId(systemOrganizationId); + } + if (event.getChanges() == null) event.setChanges(Collections.emptyMap()); + if (event.getAttributes() == null) event.setAttributes(Collections.emptyMap()); + } + + static LocalDateTime utcNow() { + return LocalDateTime.now(ZoneOffset.UTC); + } + + static String sha256(String value) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(64); + for (byte current : digest) result.append(String.format("%02x", current & 0xff)); + return result.toString(); + } catch (Exception e) { + throw new IllegalStateException("AUDIT_HASH_UNAVAILABLE", e); + } + } +} + diff --git a/src/main/java/com/finance/system/audit/AuditInstanceIdentity.java b/src/main/java/com/finance/system/audit/AuditInstanceIdentity.java new file mode 100644 index 0000000..8db74ca --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditInstanceIdentity.java @@ -0,0 +1,27 @@ +package com.finance.system.audit; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.UUID; + +@Component +public class AuditInstanceIdentity { + private final String instanceId; + + public AuditInstanceIdentity(@Value("${observability.audit.instance-id:}") String configuredId) { + String prefix = StringUtils.hasText(configuredId) + ? configuredId.replaceAll("[^A-Za-z0-9._-]", "_") : "audit"; + if (prefix.length() > 24) prefix = prefix.substring(0, 24); + this.instanceId = prefix + "-" + UUID.randomUUID().toString().replace("-", ""); + } + + public String getInstanceId() { + return instanceId; + } + + public String newClaimOwner() { + return instanceId + "-" + UUID.randomUUID().toString().replace("-", "").substring(0, 6); + } +} diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityProperties.java b/src/main/java/com/finance/system/audit/AuditIntegrityProperties.java new file mode 100644 index 0000000..90de82c --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditIntegrityProperties.java @@ -0,0 +1,200 @@ +package com.finance.system.audit; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +@Component +@ConfigurationProperties(prefix = "observability.audit.integrity") +public class AuditIntegrityProperties { + static final String LOCAL_DEVELOPMENT_KEY_ID = "local-development"; + private static final String LOCAL_DEVELOPMENT_KEY = + "finance-system-local-audit-integrity-key-v1"; + + private String currentKeyId; + private String currentKey; + private Map historicalKeys = new LinkedHashMap<>(); + private String historicalKeysSpec; + private boolean verificationEnabled = true; + private long verificationDelayMs = 300000L; + private long verificationInitialDelayMs = 60000L; + private int verificationBatchSize = 200; + private Environment environment; + + @Autowired + void setEnvironment(Environment environment) { + this.environment = environment; + } + + public Map resolvedKeys() { + return resolvedKeySet().keys; + } + + ResolvedKeySet resolvedKeySet() { + CurrentKey resolvedCurrent = resolvedCurrentKey(); + Map result = new LinkedHashMap<>(); + if (historicalKeys != null) result.putAll(historicalKeys); + if (StringUtils.hasText(historicalKeysSpec)) { + for (String entry : historicalKeysSpec.split(";")) { + if (!StringUtils.hasText(entry)) continue; + int split = entry.indexOf('='); + if (split <= 0 || split == entry.length() - 1) { + throw new IllegalStateException("AUDIT_HISTORICAL_KEY_SPEC_INVALID"); + } + putUnique(result, entry.substring(0, split).trim(), entry.substring(split + 1)); + } + } + for (Map.Entry entry : result.entrySet()) { + validateKeyId(entry.getKey()); + validateKey(entry.getValue()); + } + putUnique(result, resolvedCurrent.keyId, resolvedCurrent.key); + if (verificationBatchSize < 1 || verificationBatchSize > 10000) { + throw new IllegalStateException("AUDIT_VERIFICATION_BATCH_SIZE_INVALID"); + } + return new ResolvedKeySet(resolvedCurrent.keyId, resolvedCurrent.key, + Collections.unmodifiableMap(result)); + } + + private CurrentKey resolvedCurrentKey() { + boolean hasKeyId = StringUtils.hasText(currentKeyId); + boolean hasKey = StringUtils.hasText(currentKey); + if (!hasKeyId && !hasKey) { + if (hasLocalProfile()) { + return new CurrentKey(LOCAL_DEVELOPMENT_KEY_ID, LOCAL_DEVELOPMENT_KEY); + } + throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_PAIR_REQUIRED"); + } + if (!hasKeyId) { + throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_ID_REQUIRED"); + } + if (!hasKey) { + throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_REQUIRED"); + } + validateKeyId(currentKeyId); + validateKey(currentKey); + return new CurrentKey(currentKeyId, currentKey); + } + + private boolean hasLocalProfile() { + if (environment == null) return false; + String[] activeProfiles = environment.getActiveProfiles(); + if (activeProfiles.length == 0) return false; + for (String profile : activeProfiles) { + if (!"local".equalsIgnoreCase(profile)) return false; + } + return true; + } + + private static void putUnique(Map keys, String keyId, String key) { + String existing = keys.putIfAbsent(keyId, key); + if (existing != null && !existing.equals(key)) { + throw new IllegalStateException("AUDIT_KEY_ID_COLLISION:" + keyId); + } + } + + private static void validateKeyId(String keyId) { + if (!StringUtils.hasText(keyId) || !keyId.matches("[A-Za-z0-9._-]{1,64}")) { + throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_ID_INVALID"); + } + } + + private static void validateKey(String key) { + if (!StringUtils.hasText(key) || key.getBytes(StandardCharsets.UTF_8).length < 32) { + throw new IllegalStateException("AUDIT_INTEGRITY_KEY_MUST_HAVE_32_BYTES"); + } + } + + private static final class CurrentKey { + private final String keyId; + private final String key; + + private CurrentKey(String keyId, String key) { + this.keyId = keyId; + this.key = key; + } + } + + static final class ResolvedKeySet { + final String currentKeyId; + final String currentKey; + final Map keys; + + private ResolvedKeySet(String currentKeyId, String currentKey, Map keys) { + this.currentKeyId = currentKeyId; + this.currentKey = currentKey; + this.keys = keys; + } + } + + public String getCurrentKeyId() { + return currentKeyId; + } + + public void setCurrentKeyId(String currentKeyId) { + this.currentKeyId = currentKeyId; + } + + public String getCurrentKey() { + return currentKey; + } + + public void setCurrentKey(String currentKey) { + this.currentKey = currentKey; + } + + public Map getHistoricalKeys() { + return historicalKeys; + } + + public void setHistoricalKeys(Map historicalKeys) { + this.historicalKeys = historicalKeys; + } + + public String getHistoricalKeysSpec() { + return historicalKeysSpec; + } + + public void setHistoricalKeysSpec(String historicalKeysSpec) { + this.historicalKeysSpec = historicalKeysSpec; + } + + public boolean isVerificationEnabled() { + return verificationEnabled; + } + + public void setVerificationEnabled(boolean verificationEnabled) { + this.verificationEnabled = verificationEnabled; + } + + public long getVerificationDelayMs() { + return verificationDelayMs; + } + + public void setVerificationDelayMs(long verificationDelayMs) { + this.verificationDelayMs = verificationDelayMs; + } + + public long getVerificationInitialDelayMs() { + return verificationInitialDelayMs; + } + + public void setVerificationInitialDelayMs(long verificationInitialDelayMs) { + this.verificationInitialDelayMs = verificationInitialDelayMs; + } + + public int getVerificationBatchSize() { + return verificationBatchSize; + } + + public void setVerificationBatchSize(int verificationBatchSize) { + this.verificationBatchSize = verificationBatchSize; + } +} diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java b/src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java new file mode 100644 index 0000000..f72aed9 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java @@ -0,0 +1,19 @@ +package com.finance.system.audit; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class AuditIntegrityScanLeaseService { + private final AuditIntegrityScanStateRepository repository; + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public boolean claim(String owner, LocalDateTime now, LocalDateTime leaseUntil) { + return repository.claimLease(AuditIntegrityVerifier.SCAN_NAME, owner, now, leaseUntil) == 1; + } +} diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityScanState.java b/src/main/java/com/finance/system/audit/AuditIntegrityScanState.java new file mode 100644 index 0000000..1191b27 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditIntegrityScanState.java @@ -0,0 +1,38 @@ +package com.finance.system.audit; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.time.LocalDateTime; + +@Data +@Entity +@Table(name = "sys_audit_integrity_scan_state") +public class AuditIntegrityScanState { + @Id + @Column(name = "scan_name", length = 64) + private String scanName; + @Column(name = "cursor_id", nullable = false) + private Long cursorId; + @Column(name = "lease_owner", length = 64) + private String leaseOwner; + @Column(name = "lease_until") + private LocalDateTime leaseUntil; + @Column(name = "current_cycle_failures", nullable = false) + private Long currentCycleFailures; + @Column(name = "last_cycle_failures", nullable = false) + private Long lastCycleFailures; + @Column(name = "last_scan_at") + private LocalDateTime lastScanAt; + @Column(name = "last_completed_at") + private LocalDateTime lastCompletedAt; + @Column(name = "last_failure_at") + private LocalDateTime lastFailureAt; + @Column(name = "last_failure_event_id") + private Long lastFailureEventId; + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java b/src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java new file mode 100644 index 0000000..ef7a56f --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java @@ -0,0 +1,23 @@ +package com.finance.system.audit; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import javax.persistence.LockModeType; +import java.time.LocalDateTime; +import java.util.Optional; + +public interface AuditIntegrityScanStateRepository extends JpaRepository { + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = "update sys_audit_integrity_scan_state set lease_owner=:owner,lease_until=:leaseUntil,updated_at=:now " + + "where scan_name=:scanName and (lease_until is null or lease_until<:now or lease_owner=:owner)", nativeQuery = true) + int claimLease(@Param("scanName") String scanName, @Param("owner") String owner, + @Param("now") LocalDateTime now, @Param("leaseUntil") LocalDateTime leaseUntil); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select s from AuditIntegrityScanState s where s.scanName=:scanName") + Optional findByScanNameForUpdate(@Param("scanName") String scanName); +} diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityService.java b/src/main/java/com/finance/system/audit/AuditIntegrityService.java new file mode 100644 index 0000000..bfbb803 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditIntegrityService.java @@ -0,0 +1,147 @@ +package com.finance.system.audit; + +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** Keyed integrity tag over every immutable event column except the tag itself. */ +@Component +public class AuditIntegrityService { + public static final String PERSISTED_ALGORITHM = "HMAC-SHA256"; + public static final String LEGACY_UNVERIFIABLE_ALGORITHM = "LEGACY-HMAC-SHA256"; + public static final String LEGACY_UNVERIFIABLE_KEY_ID = "legacy-unverifiable"; + private static final String JCA_ALGORITHM = "HmacSHA256"; + private static final DateTimeFormatter MICROSECOND_TIME = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS"); + private final AuditIntegrityProperties properties; + private volatile ResolvedIntegrityKeys resolved; + + public AuditIntegrityService(AuditIntegrityProperties properties) { + this.properties = properties; + } + + @PostConstruct + synchronized void validateKey() { + if (resolved != null) return; + AuditIntegrityProperties.ResolvedKeySet resolvedProperties = properties.resolvedKeySet(); + resolved = new ResolvedIntegrityKeys(resolvedProperties.currentKeyId, + resolvedProperties.currentKey, resolvedProperties.keys); + } + + public String sign(AuditEvent event) { + ResolvedIntegrityKeys activeKeys = activeKeys(); + event.setOccurredAt(normalizeToMicros(event.getOccurredAt())); + event.setRecordedAt(normalizeToMicros(event.getRecordedAt())); + event.setIntegrityAlgorithm(PERSISTED_ALGORITHM); + event.setIntegrityKeyId(activeKeys.currentKeyId); + return calculate(event, activeKeys.currentKey); + } + + /** Constant-time tag verification; unknown key ids and algorithms fail closed. */ + public boolean verify(AuditEvent event) { + if (event == null || !PERSISTED_ALGORITHM.equals(event.getIntegrityAlgorithm())) return false; + String key = activeKeys().keys.get(event.getIntegrityKeyId()); + if (key == null) return false; + try { + byte[] actual = decodeHex(event.getIntegrityHash()); + byte[] expected = decodeHex(calculate(event, key)); + return actual != null && MessageDigest.isEqual(expected, actual); + } catch (RuntimeException e) { + return false; + } + } + + public static LocalDateTime normalizeToMicros(LocalDateTime value) { + if (value == null) return null; + return value.withNano((value.getNano() / 1000) * 1000); + } + + private String calculate(AuditEvent event, String key) { + try { + Mac mac = Mac.getInstance(JCA_ALGORITHM); + mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), JCA_ALGORITHM)); + append(mac, event.getIntegrityAlgorithm()); + append(mac, event.getIntegrityKeyId()); + append(mac, event.getEventUid()); + append(mac, event.getSchemaVersion()); + append(mac, event.getOccurredAt()); + append(mac, event.getRecordedAt()); + append(mac, event.getTenantId()); + // Pre-organization legacy rows remain verifiable with their original + // tag. New rows always have an organization and bind it into the HMAC. + if (event.getOrganizationId() != null) append(mac, event.getOrganizationId()); + append(mac, event.getCategory()); + append(mac, event.getActionCode()); + append(mac, event.getOutcome()); + append(mac, event.getReasonCode()); + append(mac, event.getActorType()); + append(mac, event.getActorId()); + append(mac, event.getTargetType()); + append(mac, event.getTargetId()); + append(mac, event.getResourceType()); + append(mac, event.getResourceId()); + append(mac, event.getRequestId()); + append(mac, event.getTraceId()); + append(mac, event.getSpanId()); + append(mac, event.getSourceChannel()); + append(mac, event.getClientIpHash()); + append(mac, event.getChangedFields()); + append(mac, event.getAttributes()); + byte[] digest = mac.doFinal(); + StringBuilder result = new StringBuilder(64); + for (byte current : digest) result.append(String.format("%02x", current & 0xff)); + return result.toString(); + } catch (Exception e) { + throw new IllegalStateException("AUDIT_HMAC_UNAVAILABLE", e); + } + } + + private static void append(Mac mac, Object value) { + String text = value == null ? "" : value instanceof LocalDateTime + ? MICROSECOND_TIME.format(normalizeToMicros((LocalDateTime) value)) : String.valueOf(value); + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + mac.update((byte) ((bytes.length >>> 24) & 0xff)); + mac.update((byte) ((bytes.length >>> 16) & 0xff)); + mac.update((byte) ((bytes.length >>> 8) & 0xff)); + mac.update((byte) (bytes.length & 0xff)); + mac.update(bytes); + } + + private static byte[] decodeHex(String value) { + if (value == null || value.length() != 64) return null; + byte[] result = new byte[32]; + for (int i = 0; i < result.length; i++) { + int high = Character.digit(value.charAt(i * 2), 16); + int low = Character.digit(value.charAt(i * 2 + 1), 16); + if (high < 0 || low < 0) return null; + result[i] = (byte) ((high << 4) | low); + } + return result; + } + + private ResolvedIntegrityKeys activeKeys() { + ResolvedIntegrityKeys activeKeys = resolved; + if (activeKeys == null) throw new IllegalStateException("AUDIT_INTEGRITY_NOT_INITIALIZED"); + return activeKeys; + } + + private static final class ResolvedIntegrityKeys { + private final String currentKeyId; + private final String currentKey; + private final Map keys; + + private ResolvedIntegrityKeys(String currentKeyId, String currentKey, + Map keys) { + this.currentKeyId = currentKeyId; + this.currentKey = currentKey; + this.keys = keys; + } + } +} diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java b/src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java new file mode 100644 index 0000000..a2b339a --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java @@ -0,0 +1,131 @@ +package com.finance.system.audit; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.PageRequest; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +/** Incremental scheduled integrity verification with bounded batches. */ +@Component +@Slf4j +public class AuditIntegrityVerifier { + static final String SCAN_NAME = "PRIMARY"; + private final AuditEventRepository repository; + private final AuditIntegrityScanStateRepository scanStates; + private final AuditIntegrityScanLeaseService scanLease; + private final AuditIntegrityService integrityService; + private final AuditIntegrityProperties properties; + private final AuditReliabilityProperties reliabilityProperties; + private final AuditInstanceIdentity identity; + private final Counter verifiedCounter; + private final Counter failureCounter; + private final Counter legacyCounter; + private final Counter cycleCounter; + private final Counter contentionCounter; + + public AuditIntegrityVerifier(AuditEventRepository repository, + AuditIntegrityScanStateRepository scanStates, + AuditIntegrityScanLeaseService scanLease, + AuditIntegrityService integrityService, + AuditIntegrityProperties properties, + AuditReliabilityProperties reliabilityProperties, + AuditInstanceIdentity identity, + MeterRegistry meterRegistry) { + this.repository = repository; + this.scanStates = scanStates; + this.scanLease = scanLease; + this.integrityService = integrityService; + this.properties = properties; + this.reliabilityProperties = reliabilityProperties; + this.identity = identity; + this.verifiedCounter = Counter.builder("audit.integrity.verified") + .description("Audit events with a valid HMAC tag").register(meterRegistry); + this.failureCounter = Counter.builder("audit.integrity.failures") + .description("Audit events failing integrity verification").register(meterRegistry); + this.legacyCounter = Counter.builder("audit.integrity.legacy_unverifiable") + .description("Pre-remediation audit events that cannot be cryptographically reverified") + .register(meterRegistry); + this.cycleCounter = Counter.builder("audit.integrity.scan.cycles") + .description("Completed full audit-integrity scan cycles").register(meterRegistry); + this.contentionCounter = Counter.builder("audit.integrity.scan.lease.contention") + .description("Integrity scan attempts blocked by another instance lease").register(meterRegistry); + } + + @Scheduled(fixedDelayString = "${observability.audit.integrity.verification-delay-ms:300000}", + initialDelayString = "${observability.audit.integrity.verification-initial-delay-ms:60000}") + @Transactional + public void verifyBatch() { + if (!properties.isVerificationEnabled()) return; + LocalDateTime now = AuditEventService.utcNow(); + String owner = identity.getInstanceId(); + if (!scanLease.claim(owner, now, now.plusSeconds(reliabilityProperties.boundedIntegrityScanLeaseSeconds()))) { + contentionCounter.increment(); + return; + } + AuditIntegrityScanState state = scanStates.findByScanNameForUpdate(SCAN_NAME) + .orElseThrow(() -> new IllegalStateException("AUDIT_INTEGRITY_SCAN_STATE_MISSING")); + if (!owner.equals(state.getLeaseOwner()) || state.getLeaseUntil() == null || !state.getLeaseUntil().isAfter(now)) { + contentionCounter.increment(); + return; + } + long cursor = state.getCursorId() == null ? 0L : state.getCursorId(); + List events = repository.findByIdGreaterThanOrderByIdAsc(cursor, + PageRequest.of(0, properties.getVerificationBatchSize())); + state.setLastScanAt(now); + if (events.isEmpty()) { + completeCycle(state, now); + return; + } + for (AuditEvent event : events) { + state.setCursorId(event.getId()); + if (isLegacyUnverifiable(event)) { + legacyCounter.increment(); + log.warn("历史审计记录无法验证完整性 AUDIT_INTEGRITY_LEGACY_UNVERIFIABLE eventId={}", event.getId()); + } else if (integrityService.verify(event)) { + verifiedCounter.increment(); + } else { + failureCounter.increment(); + state.setCurrentCycleFailures(value(state.getCurrentCycleFailures()) + 1L); + state.setLastFailureAt(now); + state.setLastFailureEventId(event.getId()); + log.error("审计完整性验证失败 AUDIT_INTEGRITY_VERIFICATION_FAILED eventId={} algorithm={} keyId={}", + event.getId(), event.getIntegrityAlgorithm(), event.getIntegrityKeyId()); + } + } + if (events.size() < properties.getVerificationBatchSize()) { + completeCycle(state, now); + } else { + release(state, now); + } + } + + private void completeCycle(AuditIntegrityScanState state, LocalDateTime now) { + state.setCursorId(0L); + state.setLastCycleFailures(value(state.getCurrentCycleFailures())); + state.setCurrentCycleFailures(0L); + state.setLastCompletedAt(now); + release(state, now); + cycleCounter.increment(); + } + + private void release(AuditIntegrityScanState state, LocalDateTime now) { + state.setLeaseOwner(null); + state.setLeaseUntil(null); + state.setUpdatedAt(now); + } + + private static long value(Long value) { + return value == null ? 0L : value; + } + + private boolean isLegacyUnverifiable(AuditEvent event) { + return AuditIntegrityService.LEGACY_UNVERIFIABLE_ALGORITHM.equals(event.getIntegrityAlgorithm()) + && AuditIntegrityService.LEGACY_UNVERIFIABLE_KEY_ID.equals(event.getIntegrityKeyId()); + } +} diff --git a/src/main/java/com/finance/system/audit/AuditOutbox.java b/src/main/java/com/finance/system/audit/AuditOutbox.java new file mode 100644 index 0000000..392a0e4 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditOutbox.java @@ -0,0 +1,71 @@ +package com.finance.system.audit; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "sys_audit_outbox") +public class AuditOutbox { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "event_uid", nullable = false, unique = true, length = 32) + private String eventUid; + + @Column(name = "aggregate_type", nullable = false, length = 64) + private String aggregateType; + + @Column(name = "aggregate_id", nullable = false, length = 128) + private String aggregateId; + + @Column(name = "action_code", nullable = false, length = 120) + private String actionCode; + + @Lob + @Column(name = "event_payload", nullable = false, columnDefinition = "MEDIUMTEXT") + private String eventPayload; + + @Column(name = "payload_hash", nullable = false, length = 64) + private String payloadHash; + + @Column(nullable = false, length = 16) + private String status; + + @Column(name = "available_at", nullable = false) + private LocalDateTime availableAt; + + @Column(name = "attempt_count", nullable = false) + private Integer attemptCount; + + @Column(name = "lease_owner", length = 64) + private String leaseOwner; + + @Column(name = "lease_until") + private LocalDateTime leaseUntil; + + @Column(name = "last_error_code", length = 80) + private String lastErrorCode; + + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @Column(name = "published_at") + private LocalDateTime publishedAt; +} + diff --git a/src/main/java/com/finance/system/audit/AuditOutboxClaimService.java b/src/main/java/com/finance/system/audit/AuditOutboxClaimService.java new file mode 100644 index 0000000..403829f --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditOutboxClaimService.java @@ -0,0 +1,23 @@ +package com.finance.system.audit; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class AuditOutboxClaimService { + private final AuditOutboxRepository repository; + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public List claim(String owner, LocalDateTime now, LocalDateTime leaseUntil, int limit) { + int boundedLimit = Math.max(1, Math.min(limit, 200)); + repository.claimReady(owner, now, leaseUntil, boundedLimit); + return repository.findClaimedIds(owner, now, PageRequest.of(0, boundedLimit)); + } +} diff --git a/src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java b/src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java new file mode 100644 index 0000000..6c47d39 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java @@ -0,0 +1,47 @@ +package com.finance.system.audit; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +@ConditionalOnProperty(prefix = "observability.audit", name = "dispatch-enabled", havingValue = "true", matchIfMissing = true) +public class AuditOutboxDispatcher { + private final AuditOutboxRepository outboxRepository; + private final AuditOutboxClaimService claimService; + private final AuditDeliveryService deliveryService; + private final AuditInstanceIdentity instanceIdentity; + private final AuditReliabilityProperties reliabilityProperties; + private final AuditReliabilityMetrics metrics; + + @org.springframework.beans.factory.annotation.Value("${observability.audit.dispatch-batch-size:50}") + private int batchSize; + + @Scheduled(fixedDelayString = "${observability.audit.dispatch-delay-ms:1000}") + public void dispatch() { + LocalDateTime now = AuditEventService.utcNow(); + String owner = instanceIdentity.newClaimOwner(); + List ids = claimService.claim(owner, now, + now.plusSeconds(reliabilityProperties.boundedOutboxLeaseSeconds()), batchSize); + if (ids.isEmpty() && outboxRepository.countReady(now) > 0) metrics.recordClaimContention(); + for (Long id : ids) { + long started = System.nanoTime(); + try { + if (deliveryService.deliver(id, owner)) metrics.recordDeliverySuccess(Duration.ofNanos(System.nanoTime() - started)); + else metrics.recordClaimContention(); + } catch (Exception failure) { + log.warn("审计事件投递失败 event=audit.delivery.failed outboxId={} errorCode=AUDIT_DELIVERY_FAILED", id); + metrics.recordDeliveryFailure(Duration.ofNanos(System.nanoTime() - started)); + if (!deliveryService.markFailure(id, owner, "AUDIT_DELIVERY_FAILED")) metrics.recordClaimContention(); + } + } + } +} diff --git a/src/main/java/com/finance/system/audit/AuditOutboxRepository.java b/src/main/java/com/finance/system/audit/AuditOutboxRepository.java new file mode 100644 index 0000000..87cc87b --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditOutboxRepository.java @@ -0,0 +1,56 @@ +package com.finance.system.audit; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import javax.persistence.LockModeType; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +public interface AuditOutboxRepository extends JpaRepository { + @Modifying + @Query(value = "insert into sys_audit_outbox " + + "(event_uid,aggregate_type,aggregate_id,action_code,event_payload,payload_hash,status," + + "available_at,attempt_count,created_at) values " + + "(:eventUid,:aggregateType,:aggregateId,:actionCode,:payload,:payloadHash,'PENDING',:now,0,:now) " + + "on duplicate key update id=id", nativeQuery = true) + int insertIfAbsent(@Param("eventUid") String eventUid, + @Param("aggregateType") String aggregateType, + @Param("aggregateId") String aggregateId, + @Param("actionCode") String actionCode, + @Param("payload") String payload, + @Param("payloadHash") String payloadHash, + @Param("now") LocalDateTime now); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select o from AuditOutbox o where o.eventUid = :eventUid") + Optional findByEventUidForUpdate(@Param("eventUid") String eventUid); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = "update sys_audit_outbox set lease_owner=:owner, lease_until=:leaseUntil " + + "where status='PENDING' and available_at<=:now " + + "and (lease_until is null or lease_until<:now) order by available_at,id limit :limit", nativeQuery = true) + int claimReady(@Param("owner") String owner, @Param("now") LocalDateTime now, + @Param("leaseUntil") LocalDateTime leaseUntil, @Param("limit") int limit); + + @Query("select o.id from AuditOutbox o where o.status = 'PENDING' and o.leaseOwner = :owner " + + "and o.leaseUntil > :now order by o.availableAt, o.id") + List findClaimedIds(@Param("owner") String owner, @Param("now") LocalDateTime now, Pageable pageable); + + @Query("select count(o) from AuditOutbox o where o.status = 'PENDING' and o.availableAt <= :now") + long countReady(@Param("now") LocalDateTime now); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select o from AuditOutbox o where o.id = :id") + Optional findByIdForUpdate(@Param("id") Long id); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select o from AuditOutbox o where o.id = :id and o.leaseOwner = :owner") + Optional findOwnedByIdForUpdate(@Param("id") Long id, @Param("owner") String owner); +} + diff --git a/src/main/java/com/finance/system/audit/AuditPort.java b/src/main/java/com/finance/system/audit/AuditPort.java new file mode 100644 index 0000000..8382b2c --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditPort.java @@ -0,0 +1,10 @@ +package com.finance.system.audit; + +public interface AuditPort { + /** + * Adds an immutable audit event to the transactional outbox. Supplying the + * same eventId more than once is idempotent. + */ + String emit(AuditEventCommand event); +} + diff --git a/src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java b/src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java new file mode 100644 index 0000000..d552384 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java @@ -0,0 +1,60 @@ +package com.finance.system.audit; + +import lombok.RequiredArgsConstructor; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +@Component("auditReliabilityHealthIndicator") +@RequiredArgsConstructor +public class AuditReliabilityHealthIndicator implements HealthIndicator { + private final AuditReliabilitySnapshotProvider snapshots; + private final AuditReliabilityProperties properties; + + @Override + public Health health() { + try { + AuditReliabilitySnapshot snapshot = snapshots.snapshot(); + String reason = reason(snapshot); + Health.Builder builder = reason == null ? Health.up() : Health.outOfService(); + return builder.withDetail("reasonCode", reason == null ? "AUDIT_RELIABILITY_OK" : reason) + .withDetail("pendingCount", snapshot.getPendingCount()) + .withDetail("deadCount", snapshot.getDeadCount()) + .withDetail("oldestPendingAgeSeconds", snapshot.getOldestPendingAgeSeconds()) + .withDetail("pendingTimestampInvalid", snapshot.isPendingTimestampInvalid()) + .withDetail("integrityScanAgeSeconds", snapshot.getIntegrityScanAgeSeconds()) + .withDetail("integrityScanMissing", snapshot.isIntegrityScanMissing()) + .withDetail("integrityScanTimestampInvalid", snapshot.isIntegrityScanTimestampInvalid()) + .withDetail("integrityFailureCount", snapshot.getIntegrityFailureCount()).build(); + } catch (RuntimeException ex) { + return Health.down().withDetail("reasonCode", "AUDIT_RELIABILITY_PROBE_FAILED").build(); + } + } + + private String reason(AuditReliabilitySnapshot snapshot) { + if (snapshot.getDeadCount() > properties.getMaxDeadCount()) return "AUDIT_OUTBOX_DEAD_THRESHOLD"; + if (snapshot.getPendingCount() > 0 + && (snapshot.isPendingTimestampInvalid() || snapshot.getOldestPendingAgeSeconds() < 0L)) { + return "AUDIT_OUTBOX_PENDING_TIME_INVALID"; + } + if (snapshot.getPendingCount() > 0 + && (snapshot.isPendingAgeThresholdExceeded() + || snapshot.getOldestPendingAgeSeconds() > properties.getMaxPendingAgeSeconds())) { + return "AUDIT_OUTBOX_PENDING_AGE_THRESHOLD"; + } + if (properties.isFailOnIntegrityFailure() && snapshot.getIntegrityFailureCount() > 0) { + return "AUDIT_INTEGRITY_FAILURE"; + } + if (snapshot.isIntegrityScanMissing() || snapshot.getIntegrityScanAgeSeconds() == Long.MAX_VALUE) { + return "AUDIT_INTEGRITY_SCAN_NOT_RECORDED"; + } + if (snapshot.isIntegrityScanTimestampInvalid() || snapshot.getIntegrityScanAgeSeconds() < 0L) { + return "AUDIT_INTEGRITY_SCAN_TIME_INVALID"; + } + if (snapshot.isIntegrityScanStale() + || snapshot.getIntegrityScanAgeSeconds() > properties.getMaxIntegrityScanAgeSeconds()) { + return "AUDIT_INTEGRITY_SCAN_STALE"; + } + return null; + } +} diff --git a/src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java b/src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java new file mode 100644 index 0000000..d9f9e85 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java @@ -0,0 +1,59 @@ +package com.finance.system.audit; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Timer; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.util.concurrent.atomic.AtomicLong; + +@Component +public class AuditReliabilityMetrics { + private final Counter deliverySuccess; + private final Counter deliveryFailure; + private final Counter claimContention; + private final Timer deliveryLatency; + private final AuditReliabilitySnapshotProvider snapshots; + private final AtomicLong pending = new AtomicLong(); + private final AtomicLong dead = new AtomicLong(); + private final AtomicLong oldestPendingAge = new AtomicLong(); + private final AtomicLong scanAge = new AtomicLong(); + + public AuditReliabilityMetrics(MeterRegistry registry, AuditReliabilitySnapshotProvider snapshots) { + this.snapshots = snapshots; + deliverySuccess = Counter.builder("audit.outbox.delivery.success").register(registry); + deliveryFailure = Counter.builder("audit.outbox.delivery.failure").register(registry); + claimContention = Counter.builder("audit.outbox.claim.contention").register(registry); + deliveryLatency = Timer.builder("audit.outbox.delivery.latency").publishPercentileHistogram().register(registry); + Gauge.builder("audit.outbox.pending", pending, AtomicLong::get).register(registry); + Gauge.builder("audit.outbox.dead", dead, AtomicLong::get).register(registry); + Gauge.builder("audit.outbox.oldest.pending.age.seconds", oldestPendingAge, AtomicLong::get).register(registry); + Gauge.builder("audit.integrity.scan.age.seconds", scanAge, AtomicLong::get).register(registry); + } + + public void recordDeliverySuccess(Duration duration) { + deliverySuccess.increment(); + deliveryLatency.record(duration); + } + + public void recordDeliveryFailure(Duration duration) { + deliveryFailure.increment(); + deliveryLatency.record(duration); + } + + public void recordClaimContention() { + claimContention.increment(); + } + + @Scheduled(fixedDelayString = "${observability.audit.reliability.metrics-refresh-ms:30000}") + public void refresh() { + AuditReliabilitySnapshot value = snapshots.snapshot(); + pending.set(value.getPendingCount()); + dead.set(value.getDeadCount()); + oldestPendingAge.set(value.getOldestPendingAgeSeconds()); + scanAge.set(value.getIntegrityScanAgeSeconds()); + } +} diff --git a/src/main/java/com/finance/system/audit/AuditReliabilityProperties.java b/src/main/java/com/finance/system/audit/AuditReliabilityProperties.java new file mode 100644 index 0000000..3cdba7c --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditReliabilityProperties.java @@ -0,0 +1,26 @@ +package com.finance.system.audit; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "observability.audit.reliability") +public class AuditReliabilityProperties { + private int outboxLeaseSeconds = 30; + private int integrityScanLeaseSeconds = 120; + private long maxPendingAgeSeconds = 300L; + private long maxDeadCount = 0L; + private long maxIntegrityScanAgeSeconds = 900L; + private boolean failOnIntegrityFailure = true; + private long metricsRefreshMs = 30000L; + + public int boundedOutboxLeaseSeconds() { + return Math.max(5, Math.min(outboxLeaseSeconds, 3600)); + } + + public int boundedIntegrityScanLeaseSeconds() { + return Math.max(30, Math.min(integrityScanLeaseSeconds, 3600)); + } +} diff --git a/src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java new file mode 100644 index 0000000..77152f1 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java @@ -0,0 +1,19 @@ +package com.finance.system.audit; + +import lombok.Builder; +import lombok.Value; + +@Value +@Builder +public class AuditReliabilitySnapshot { + long pendingCount; + long deadCount; + long oldestPendingAgeSeconds; + boolean pendingTimestampInvalid; + boolean pendingAgeThresholdExceeded; + long integrityScanAgeSeconds; + boolean integrityScanMissing; + boolean integrityScanTimestampInvalid; + boolean integrityScanStale; + long integrityFailureCount; +} diff --git a/src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java new file mode 100644 index 0000000..3892b92 --- /dev/null +++ b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java @@ -0,0 +1,78 @@ +package com.finance.system.audit; + +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RequiredArgsConstructor +public class AuditReliabilitySnapshotProvider { + static final String OUTBOX_SNAPSHOT_SQL = + "select pending_count,dead_count," + + "case when oldest_pending_at is null then 0 " + + "else timestampdiff(second,oldest_pending_at,utc_timestamp(6)) end " + + "oldest_pending_age_seconds," + + "case when invalid_pending_time_count>0 " + + "then 1 else 0 end pending_time_invalid," + + "case when oldest_pending_at is not null " + + "and oldest_pending_atutc_timestamp(6)) then 1 else 0 end),0) " + + "invalid_pending_time_count," + + "min(case when status='PENDING' then created_at end) oldest_pending_at " + + "from sys_audit_outbox) outbox_state"; + + static final String INTEGRITY_SCAN_SNAPSHOT_SQL = + "select case when last_scan_at is null then null " + + "else timestampdiff(second,last_scan_at,utc_timestamp(6)) end " + + "integrity_scan_age_seconds," + + "case when last_scan_at is null then 1 else 0 end scan_missing," + + "case when last_scan_at is not null and last_scan_at>utc_timestamp(6) " + + "then 1 else 0 end scan_time_invalid," + + "case when last_scan_at is not null " + + "and last_scan_at outbox = jdbcTemplate.queryForMap( + OUTBOX_SNAPSHOT_SQL, properties.getMaxPendingAgeSeconds()); + Map scan = jdbcTemplate.queryForMap( + INTEGRITY_SCAN_SNAPSHOT_SQL, properties.getMaxIntegrityScanAgeSeconds()); + long failures = number(scan.get("current_cycle_failures")) + number(scan.get("last_cycle_failures")); + return AuditReliabilitySnapshot.builder() + .pendingCount(number(outbox.get("pending_count"))) + .deadCount(number(outbox.get("dead_count"))) + .oldestPendingAgeSeconds(number(outbox.get("oldest_pending_age_seconds"))) + .pendingTimestampInvalid(flag(outbox.get("pending_time_invalid"))) + .pendingAgeThresholdExceeded(flag(outbox.get("pending_age_exceeded"))) + .integrityScanAgeSeconds(number(scan.get("integrity_scan_age_seconds"), Long.MAX_VALUE)) + .integrityScanMissing(flag(scan.get("scan_missing"))) + .integrityScanTimestampInvalid(flag(scan.get("scan_time_invalid"))) + .integrityScanStale(flag(scan.get("scan_stale"))) + .integrityFailureCount(failures) + .build(); + } + + private static long number(Object value) { + return number(value, 0L); + } + + private static long number(Object value, long missingValue) { + return value instanceof Number ? ((Number) value).longValue() : missingValue; + } + + private static boolean flag(Object value) { + return number(value) != 0L; + } +} diff --git a/src/main/java/com/finance/system/audit/query/AuditEventView.java b/src/main/java/com/finance/system/audit/query/AuditEventView.java new file mode 100644 index 0000000..d00e678 --- /dev/null +++ b/src/main/java/com/finance/system/audit/query/AuditEventView.java @@ -0,0 +1,33 @@ +package com.finance.system.audit.query; + +import lombok.Builder; +import lombok.Value; + +import java.time.LocalDateTime; + +/** Explicit audit-query allowlist. Payload, attributes and integrity metadata are never exposed. */ +@Value +@Builder +public class AuditEventView { + Long id; + LocalDateTime eventTime; + String category; + String categoryLabel; + String action; + String actionLabel; + String outcome; + String outcomeLabel; + String reasonCode; + String reasonLabel; + String actorType; + String actorLabel; + Long actorId; + String targetType; + String targetId; + String resourceType; + String resourceLabel; + String resourceId; + String requestId; + String traceId; + String source; +} diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java b/src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java new file mode 100644 index 0000000..99a4af3 --- /dev/null +++ b/src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java @@ -0,0 +1,58 @@ +package com.finance.system.audit.query; + +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.exception.UnauthorizedException; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.Locale; + +@Component +@RequiredArgsConstructor +public class AuditQueryAuthorization { + private final AuthorizationService authorizationService; + + public AuditQueryScope authorize(String area) { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null || principal.getId() == null) throw new UnauthorizedException("未登录"); + SubjectContext subject = authorizationService.subject(principal); + if (subject == null || !StringUtils.hasText(subject.getTenantId()) + || subject.getOrganizationId() == null) { + throw new AccessDeniedException("缺少审计查询隔离边界"); + } + String resource = resource(area); + ResourceContext context = ResourceContext.builder().resourceType(resource) + .tenantId(subject.getTenantId()).organizationId(subject.getOrganizationId()) + .ownerId(subject.getUserId()).build(); + if (authorizationService.can(request(subject, resource, "read-all", context))) { + return new AuditQueryScope(subject.getTenantId(), subject.getOrganizationId(), subject.getUserId(), true); + } + if (authorizationService.can(request(subject, resource, "read-own", context))) { + return new AuditQueryScope(subject.getTenantId(), subject.getOrganizationId(), subject.getUserId(), false); + } + throw new AccessDeniedException("无权查看该类审计事件"); + } + + private AuthorizationRequest request(SubjectContext subject, String resource, String action, + ResourceContext context) { + return AuthorizationRequest.builder().subject(subject).resource(resource).action(action) + .resourceContext(context).build(); + } + + private String resource(String area) { + String normalized = area == null ? "" : area.trim().toUpperCase(Locale.ROOT); + if ("ACCESS".equals(normalized)) return "audit.access"; + if ("SECURITY".equals(normalized)) return "audit.security"; + if ("BUSINESS".equals(normalized)) return "audit.business"; + if ("ADMIN".equals(normalized)) return "audit.admin"; + if ("INTEGRATION".equals(normalized)) return "audit.integration"; + throw new IllegalArgumentException("不支持的审计类别"); + } +} diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryRepository.java b/src/main/java/com/finance/system/audit/query/AuditQueryRepository.java new file mode 100644 index 0000000..1caa215 --- /dev/null +++ b/src/main/java/com/finance/system/audit/query/AuditQueryRepository.java @@ -0,0 +1,31 @@ +package com.finance.system.audit.query; + +import com.finance.system.audit.AuditEvent; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDateTime; +import java.util.List; + +public interface AuditQueryRepository extends Repository { + @Query("select e from AuditEvent e where e.tenantId = :tenantId and e.organizationId = :organizationId " + + "and (:allActors = true or e.actorId = :actorId) and e.category = :category " + + "and (:action is null or e.actionCode = :action) " + + "and (:outcome is null or e.outcome = :outcome) " + + "and (:filterActorId is null or e.actorId = :filterActorId) " + + "and (:resourceType is null or e.resourceType = :resourceType) " + + "and (:resourceId is null or e.resourceId = :resourceId) " + + "and (:cursorTime is null or e.occurredAt < :cursorTime " + + "or (e.occurredAt = :cursorTime and e.id < :cursorId)) " + + "order by e.occurredAt desc, e.id desc") + List search(@Param("tenantId") String tenantId, + @Param("organizationId") Long organizationId, + @Param("allActors") boolean allActors, @Param("actorId") Long actorId, + @Param("category") String category, @Param("action") String action, + @Param("outcome") String outcome, @Param("filterActorId") Long filterActorId, + @Param("resourceType") String resourceType, @Param("resourceId") String resourceId, + @Param("cursorTime") LocalDateTime cursorTime, @Param("cursorId") Long cursorId, + Pageable pageable); +} diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryScope.java b/src/main/java/com/finance/system/audit/query/AuditQueryScope.java new file mode 100644 index 0000000..cacb19f --- /dev/null +++ b/src/main/java/com/finance/system/audit/query/AuditQueryScope.java @@ -0,0 +1,11 @@ +package com.finance.system.audit.query; + +import lombok.Value; + +@Value +public class AuditQueryScope { + String tenantId; + Long organizationId; + Long actorId; + boolean allActors; +} diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryService.java b/src/main/java/com/finance/system/audit/query/AuditQueryService.java new file mode 100644 index 0000000..f460b99 --- /dev/null +++ b/src/main/java/com/finance/system/audit/query/AuditQueryService.java @@ -0,0 +1,78 @@ +package com.finance.system.audit.query; + +import com.finance.system.audit.AuditEvent; +import com.finance.system.observability.LogText; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +@Service +@RequiredArgsConstructor +public class AuditQueryService { + private static final int DEFAULT_LIMIT = 50; + private static final int MAX_LIMIT = 100; + private final AuditQueryRepository repository; + + @Transactional(readOnly = true) + public CursorPage search(AuditQueryScope scope, String category, String action, + String outcome, Long actorId, String resourceType, String resourceId, + LocalDateTime cursorTime, Long cursorId, Integer requestedLimit) { + if ((cursorTime == null) != (cursorId == null)) + throw new IllegalArgumentException("cursorTime 与 cursorId 必须同时提供"); + if (!scope.isAllActors() && actorId != null && !actorId.equals(scope.getActorId())) { + throw new org.springframework.security.access.AccessDeniedException("仅可查询本人审计事件"); + } + int limit = requestedLimit == null ? DEFAULT_LIMIT : Math.max(1, Math.min(requestedLimit, MAX_LIMIT)); + Long filterActor = scope.isAllActors() ? actorId : scope.getActorId(); + if (scope.getOrganizationId() == null || scope.getOrganizationId() <= 0) + throw new org.springframework.security.access.AccessDeniedException("缺少组织隔离边界"); + List rows = repository.search(scope.getTenantId(), scope.getOrganizationId(), + scope.isAllActors(), scope.getActorId(), + normalizeCategory(category), clean(action), clean(outcome), filterActor, + clean(resourceType), clean(resourceId), cursorTime, cursorId, PageRequest.of(0, limit + 1)); + boolean more = rows.size() > limit; + List items = new ArrayList<>(); + for (int i = 0; i < Math.min(limit, rows.size()); i++) { + AuditEvent row = rows.get(i); + if (!scope.getTenantId().equals(row.getTenantId()) + || !scope.getOrganizationId().equals(row.getOrganizationId())) { + throw new org.springframework.security.access.AccessDeniedException("审计事件组织边界不匹配"); + } + items.add(toView(row)); + } + AuditEvent last = more && !items.isEmpty() ? rows.get(limit - 1) : null; + return CursorPage.builder().items(items).hasMore(more) + .nextEventTime(last == null ? null : last.getOccurredAt()) + .nextId(last == null ? null : last.getId()).build(); + } + + private AuditEventView toView(AuditEvent e) { + return AuditEventView.builder().id(e.getId()).eventTime(e.getOccurredAt()) + .category(e.getCategory()).categoryLabel(LogText.auditCategory(e.getCategory())) + .action(e.getActionCode()).actionLabel(LogText.auditAction(e.getActionCode())) + .outcome(e.getOutcome()).outcomeLabel(LogText.outcome(e.getOutcome())) + .reasonCode(e.getReasonCode()).reasonLabel(LogText.reason(e.getReasonCode())) + .actorType(e.getActorType()) + .actorLabel(LogText.actorType(e.getActorType())).actorId(e.getActorId()) + .targetType(e.getTargetType()).targetId(e.getTargetId()) + .resourceType(e.getResourceType()).resourceLabel(LogText.resourceType(e.getResourceType())) + .resourceId(e.getResourceId()) + .requestId(e.getRequestId()).traceId(e.getTraceId()).source(e.getSourceChannel()).build(); + } + + private String normalizeCategory(String value) { + String result = value == null ? "" : value.trim().toUpperCase(Locale.ROOT); + if (!java.util.Arrays.asList("SECURITY", "BUSINESS", "ADMIN", "INTEGRATION").contains(result)) + throw new IllegalArgumentException("不支持的审计类别"); + return result; + } + + private String clean(String value) { return StringUtils.hasText(value) ? value.trim() : null; } +} diff --git a/src/main/java/com/finance/system/audit/query/CursorPage.java b/src/main/java/com/finance/system/audit/query/CursorPage.java new file mode 100644 index 0000000..278c0b5 --- /dev/null +++ b/src/main/java/com/finance/system/audit/query/CursorPage.java @@ -0,0 +1,16 @@ +package com.finance.system.audit.query; + +import lombok.Builder; +import lombok.Value; + +import java.time.LocalDateTime; +import java.util.List; + +@Value +@Builder +public class CursorPage { + List items; + LocalDateTime nextEventTime; + Long nextId; + boolean hasMore; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationAdminService.java b/src/main/java/com/finance/system/authorization/AuthorizationAdminService.java new file mode 100644 index 0000000..ca107f0 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationAdminService.java @@ -0,0 +1,470 @@ +package com.finance.system.authorization; + +import com.finance.system.audit.AuditEventCommand; +import com.finance.system.audit.AuditPort; +import com.finance.system.entity.SysRole; +import com.finance.system.exception.BadRequestException; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.repository.SysRoleRepository; +import com.finance.system.repository.SysUserGroupRepository; +import com.finance.system.repository.SysUserGroupMemberRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.entity.SysUser; +import com.finance.system.entity.SysUserGroupMember; +import com.finance.system.service.RoleService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.beans.factory.annotation.Autowired; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.*; + +/** Super-admin mutation boundary for canonical policies and subject bindings. */ +@Service +@RequiredArgsConstructor +public class AuthorizationAdminService { + private final AuthorizationPolicyEvaluator evaluator; + private final AuthorizationPolicyRepository policies; + private final AuthorizationRolePolicyRepository rolePolicies; + private final AuthorizationSubjectRoleBindingRepository subjectBindings; + private final AuthorizationFieldRuleRepository fieldRules; + private final AuthorizationPolicyVersionRepository versions; + private final AuthorizationSodRuleRepository sodRules; + private final SysRoleRepository roles; + private final SysUserRepository users; + private final SysUserGroupRepository groups; + private final SysUserGroupMemberRepository groupMembers; + private final RoleService roleService; + private final AuditPort auditPort; + @Autowired + private AuthorizationRoleProfileVersionRepository roleProfileVersions; + + @Transactional(readOnly = true) + public List listPolicies() { + List result = new ArrayList<>(); + for (AuthorizationPolicyEntity policy : policies.findAll()) result.add(policyDto(policy)); + return result; + } + + /** Internal-only gate for raw policy diagnostics and maintenance endpoints. */ + @Transactional(readOnly = true) + public void assertInternalPolicyAdmin(Long actorId) { + requireSuperAdmin(actorId); + } + + @Transactional + public AuthorizationPolicyDto savePolicy(Long id, AuthorizationPolicyRequest request, Long actorId) { + if (request == null) throw new BadRequestException("策略请求不能为空"); + return savePolicy(id, request.toMap(), actorId); + } + + @Transactional + public AuthorizationPolicyDto savePolicy(Long id, Map body, Long actorId) { + requireSuperAdmin(actorId); + String resource = normalizedPart(body, "resource"); + String action = normalizedPart(body, "action"); + String policyCode = text(body, "policyCode", 120); + PolicyEffect effect = enumValue(body, "effect", PolicyEffect.class); + DataScope dataScope = enumValue(body, "dataScope", DataScope.class); + String scopeParameter = optionalText(body, "scopeParameter", 120); + int priority = integer(body, "priority", 0, -10000, 10000); + boolean enabled = bool(body, "enabled", true); + AuthorizationPolicyEntity policy = id == null ? new AuthorizationPolicyEntity() + : policies.findById(id).orElseThrow(() -> new ResourceNotFoundException("授权策略不存在")); + AuthorizationPolicyEntity duplicate = policies.findByPolicyCode(policyCode).orElse(null); + if (duplicate != null && !Objects.equals(duplicate.getId(), id)) throw new BusinessException("策略编码已存在", 409); + boolean delegable = bool(body, "delegable", policy.getDelegable() == null || policy.getDelegable()); + PolicyRiskLevel riskLevel = optionalEnum(body, "riskLevel", PolicyRiskLevel.class); + if (riskLevel == null) riskLevel = policy.getRiskLevel() == null ? PolicyRiskLevel.NORMAL : policy.getRiskLevel(); + boolean protectedPolicy = bool(body, "protected", Boolean.TRUE.equals(policy.getProtectedPolicy())); + validateProtectedPolicyMutation(id, body, policy, policyCode, resource, action, effect, dataScope, + scopeParameter, priority, enabled, delegable, riskLevel, protectedPolicy); + if ((protectedPolicy || riskLevel == PolicyRiskLevel.CRITICAL) && delegable) { + throw new BusinessException("受保护或CRITICAL策略必须显式设为不可委派", 403); + } + if (riskLevel == PolicyRiskLevel.CRITICAL && !protectedPolicy) { + throw new BusinessException("CRITICAL策略必须显式设为受保护", 403); + } + policy.setPolicyCode(policyCode); + policy.setResourceCode(resource); + policy.setActionCode(action); + policy.setEffect(effect); + policy.setDataScope(dataScope); + policy.setScopeParameter(scopeParameter); + policy.setPriority(priority); + policy.setEnabled(enabled); + policy.setDelegable(delegable); + policy.setRiskLevel(riskLevel); + policy.setProtectedPolicy(protectedPolicy); + LocalDateTime now = LocalDateTime.now(); + if (policy.getCreatedAt() == null) policy.setCreatedAt(now); + policy.setUpdatedAt(now); + AuthorizationPolicyEntity saved = policies.save(policy); + replaceFieldRules(saved.getId(), body == null ? null : body.get("fieldAccess")); + bumpVersion(); + audit("iam.policy." + (id == null ? "create" : "update"), actorId, + "IAM_POLICY", saved.getId(), attributes("policyCode", saved.getPolicyCode(), "effectCode", saved.getEffect().name())); + return policyDto(saved); + } + + @Transactional(readOnly = true) + public AuthorizationBindingPageDto listBindings(AuthorizationBindingQueryRequest query, Long actorId, + String actorTenant) { + if (query == null) query = new AuthorizationBindingQueryRequest(); + if (!StringUtils.hasText(actorTenant)) throw new BusinessException("当前主体缺少租户边界", 403); + boolean superAdmin = actorId != null && roleService.isSuperAdmin(actorId); + String requestedTenant = StringUtils.hasText(query.getTenant()) ? query.getTenant().trim() : actorTenant; + boolean global = "*".equals(requestedTenant); + if (global && !superAdmin) throw new BusinessException("只有超级管理员可以查询GLOBAL授权绑定", 403); + if (!global && !actorTenant.equals(requestedTenant) && !superAdmin) { + throw new BusinessException("禁止跨租户查询授权绑定", 403); + } + int page = query.getPage() == null ? 0 : query.getPage(); + int size = query.getSize() == null ? 20 : query.getSize(); + if (page < 0 || size < 1 || size > 100) throw new BadRequestException("分页参数无效"); + List filtered = new ArrayList<>(); + for (AuthorizationSubjectRoleBindingEntity binding : subjectBindings.findAll()) { + if (binding == null || binding.getId() == null) continue; + AuthorizationSubjectType subjectType; + try { subjectType = AuthorizationSubjectType.valueOf(binding.getSubjectType()); } + catch (RuntimeException ex) { continue; } + String bindingTenant = resolveBindingTenant(binding, subjectType); + if (!global && !requestedTenant.equals(bindingTenant)) continue; + if (query.getSubjectType() != null && query.getSubjectType() != subjectType) continue; + if (query.getSubjectId() != null && !query.getSubjectId().equals(binding.getSubjectId())) continue; + if (query.getRoleId() != null && !query.getRoleId().equals(binding.getRoleId())) continue; + if (query.getEnabled() != null && !query.getEnabled().equals(binding.getEnabled())) continue; + filtered.add(bindingDto(binding, subjectType, bindingTenant)); + } + filtered.sort(Comparator.comparing(AuthorizationBindingDto::getId)); + long total = filtered.size(); + long offset = (long) page * size; + int from = offset >= total ? filtered.size() : (int) offset; + int to = Math.min(filtered.size(), from + size); + return AuthorizationBindingPageDto.builder().content(new ArrayList<>(filtered.subList(from, to))) + .page(page).size(size).totalElements(total) + .totalPages(total == 0 ? 0 : (int) ((total + size - 1) / size)).build(); + } + + @Transactional + public void replaceRolePolicies(Long roleId, Collection policyIds, Long actorId) { + replaceRolePoliciesInternal(roleId, policyIds, actorId, true); + } + + @Transactional + public void replaceRolePoliciesFromProfile(Long roleId, Collection policyIds, Long actorId) { + replaceRolePoliciesInternal(roleId, policyIds, actorId, false); + } + + private void replaceRolePoliciesInternal(Long roleId, Collection policyIds, Long actorId, + boolean bumpRoleProfileVersion) { + requireSuperAdmin(actorId); + // Every authorization writer must acquire the role row first. The + // atomic profile writer already does this before locking its version + // row; keeping the legacy policy endpoint on the same leading lock + // serializes same-role writes and prevents downstream lock inversion. + SysRole role = roles.findByIdForUpdate(roleId) + .orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + Set ids = positiveIds(policyIds, "policyIds"); + List selected = policies.findAllById(ids); + if (selected.size() != ids.size()) throw new BadRequestException("policyIds包含不存在的策略"); + boolean protectedTarget = "SUPER_ADMIN".equals(role.getRoleCode()) && Boolean.TRUE.equals(role.getBuiltIn()); + for (AuthorizationPolicyEntity policy : selected) { + if ((!Boolean.TRUE.equals(policy.getDelegable()) || Boolean.TRUE.equals(policy.getProtectedPolicy()) + || policy.getRiskLevel() == PolicyRiskLevel.CRITICAL) + && !protectedTarget) { + throw new BusinessException("不可委派、受保护或CRITICAL策略只能绑定内置超级管理员角色", 403); + } + } + for (AuthorizationRolePolicyEntity existing : rolePolicies.findByIdRoleId(roleId)) { + if (existing == null || existing.getId() == null || ids.contains(existing.getId().getPolicyId())) continue; + AuthorizationPolicyEntity policy = policies.findById(existing.getId().getPolicyId()).orElse(null); + if (policy != null && Boolean.TRUE.equals(policy.getProtectedPolicy())) { + throw new BusinessException("受保护策略不能通过角色策略替换移除", 403); + } + } + rolePolicies.deleteByIdRoleId(roleId); + for (Long policyId : ids) rolePolicies.save(new AuthorizationRolePolicyEntity(roleId, policyId)); + bumpVersion(); + if (bumpRoleProfileVersion && roleProfileVersions != null) roleProfileVersions.bumpRoleVersion(roleId); + audit("iam.role.policy.update", actorId, "IAM_ROLE", roleId, + attributes("roleCode", role.getRoleCode(), "policyCount", ids.size())); + } + + @Transactional(readOnly = true) + public List rolePolicyIds(Long roleId) { + if (!roles.existsById(roleId)) throw new ResourceNotFoundException("角色不存在"); + List result = new ArrayList<>(); + for (AuthorizationRolePolicyEntity link : rolePolicies.findByIdRoleId(roleId)) result.add(link.getId().getPolicyId()); + return result; + } + + @Transactional + public Map createSubjectBinding(Map body, Long actorId) { + requireSuperAdmin(actorId); + String subjectType = text(body, "subjectType", 16).toUpperCase(Locale.ROOT); + if (!("USER".equals(subjectType) || "GROUP".equals(subjectType))) throw new BadRequestException("subjectType必须是USER或GROUP"); + Long subjectId = positiveLong(body, "subjectId"); + Long roleId = positiveLong(body, "roleId"); + if ("USER".equals(subjectType) && subjectId.equals(actorId)) throw new BusinessException("禁止给当前操作者自授权", 403); + if ("USER".equals(subjectType) && !users.existsById(subjectId)) throw new ResourceNotFoundException("用户不存在"); + if ("GROUP".equals(subjectType) && !groups.existsById(subjectId)) throw new ResourceNotFoundException("用户组不存在"); + SysRole role = roles.findById(roleId).orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + DataScope scopeOverride = optionalEnum(body, "scopeOverride", DataScope.class); + Long scopeReferenceId = optionalPositiveLong(body, "scopeReferenceId"); + if (scopeReferenceId != null && scopeOverride != DataScope.DEPARTMENT + && scopeOverride != DataScope.DEPARTMENT_TREE) { + throw new BadRequestException("scopeReferenceId仅适用于部门范围"); + } + if (subjectBindings.existsNormalized(subjectType, subjectId, roleId, scopeOverride, scopeReferenceId)) { + throw new BusinessException("授权绑定已存在", 409); + } + AuthorizationSubjectRoleBindingEntity binding = new AuthorizationSubjectRoleBindingEntity(); + binding.setSubjectType(subjectType); binding.setSubjectId(subjectId); binding.setRoleId(roleId); + binding.setScopeOverride(scopeOverride); + binding.setScopeReferenceId(scopeReferenceId); + binding.setValidFrom(optionalDateTime(body, "validFrom")); + binding.setValidUntil(optionalDateTime(body, "validUntil")); + if (binding.getValidFrom() != null && binding.getValidUntil() != null + && !binding.getValidUntil().isAfter(binding.getValidFrom())) { + throw new BadRequestException("validUntil必须晚于validFrom"); + } + binding.setEnabled(bool(body, "enabled", true)); binding.setCreatedBy(actorId); binding.setRecordVersion(0L); + AuthorizationSubjectRoleBindingEntity saved; + try { + saved = subjectBindings.saveAndFlush(binding); + } catch (DataIntegrityViolationException ex) { + throw new BusinessException("授权绑定已存在", 409); + } + bumpVersion(); + audit("iam.binding.create", actorId, "IAM_BINDING", saved.getId(), + attributes("subjectType", subjectType, "subjectId", subjectId, "roleCode", role.getRoleCode())); + return bindingMap(saved); + } + + @Transactional + public void deleteSubjectBinding(Long bindingId, Long actorId) { + requireSuperAdmin(actorId); + AuthorizationSubjectRoleBindingEntity binding = subjectBindings.findById(bindingId) + .orElseThrow(() -> new ResourceNotFoundException("授权绑定不存在")); + if ("USER".equals(binding.getSubjectType()) && Objects.equals(binding.getSubjectId(), actorId)) { + throw new BusinessException("禁止移除当前操作者自身的授权绑定", 403); + } + subjectBindings.delete(binding); + bumpVersion(); + audit("iam.binding.delete", actorId, "IAM_BINDING", bindingId, + attributes("subjectType", binding.getSubjectType(), "subjectId", binding.getSubjectId(), "roleId", binding.getRoleId())); + } + + @Transactional(readOnly = true) + public List> listSodRules() { + List> result = new ArrayList<>(); + for (AuthorizationSodRuleEntity rule : sodRules.findAll()) { + Map item = new LinkedHashMap<>(); + item.put("id", rule.getId()); item.put("ruleCode", rule.getRuleCode()); + item.put("leftDuty", rule.getLeftDuty()); item.put("rightDuty", rule.getRightDuty()); + item.put("relationType", rule.getRelationType()); item.put("enabled", rule.getEnabled()); + result.add(item); + } + return result; + } + + private void replaceFieldRules(Long policyId, Object raw) { + if (raw == null) return; + if (!(raw instanceof Map)) throw new BadRequestException("fieldAccess必须是对象"); + Map values = (Map) raw; + if (values.size() > 200) throw new BadRequestException("字段规则不能超过200项"); + fieldRules.deleteByPolicyId(policyId); + for (Map.Entry entry : values.entrySet()) { + String field = String.valueOf(entry.getKey()); + if (!field.matches("[A-Za-z][A-Za-z0-9_.-]{0,119}")) throw new BadRequestException("字段编码格式不正确"); + FieldAccess access; + try { access = FieldAccess.valueOf(String.valueOf(entry.getValue()).toUpperCase(Locale.ROOT)); } + catch (Exception ex) { throw new BadRequestException("字段访问级别无效"); } + AuthorizationFieldRuleEntity rule = new AuthorizationFieldRuleEntity(); + rule.setPolicyId(policyId); rule.setFieldCode(field); rule.setFieldAccess(access); fieldRules.save(rule); + } + } + + private void validateProtectedPolicyMutation(Long id, Map body, + AuthorizationPolicyEntity existing, + String policyCode, String resource, String action, + PolicyEffect effect, DataScope dataScope, + String scopeParameter, int priority, boolean enabled, + boolean delegable, PolicyRiskLevel riskLevel, + boolean protectedPolicy) { + if (id == null || existing == null) return; + boolean locked = Boolean.TRUE.equals(existing.getProtectedPolicy()) + || existing.getRiskLevel() == PolicyRiskLevel.CRITICAL; + if (!locked) return; + boolean changed = !Objects.equals(existing.getPolicyCode(), policyCode) + || !Objects.equals(existing.getResourceCode(), resource) + || !Objects.equals(existing.getActionCode(), action) + || existing.getEffect() != effect + || existing.getDataScope() != dataScope + || !Objects.equals(existing.getScopeParameter(), scopeParameter) + || !Objects.equals(existing.getPriority(), priority) + || !Objects.equals(existing.getEnabled(), enabled) + || !Objects.equals(existing.getDelegable(), delegable) + || existing.getRiskLevel() != riskLevel + || !Objects.equals(existing.getProtectedPolicy(), protectedPolicy) + || (body != null && body.containsKey("fieldAccess")); + if (changed) { + throw new BusinessException("受保护或CRITICAL策略不支持普通更新;系统未提供break-glass降级通道", 403); + } + } + + private AuthorizationPolicyDto policyDto(AuthorizationPolicyEntity policy) { + Map fields = new LinkedHashMap<>(); + if (policy.getId() != null) for (AuthorizationFieldRuleEntity rule : fieldRules.findByPolicyId(policy.getId())) fields.put(rule.getFieldCode(), rule.getFieldAccess()); + return AuthorizationPolicyDto.builder().id(policy.getId()).policyCode(policy.getPolicyCode()) + .resource(policy.getResourceCode()).action(policy.getActionCode()).effect(policy.getEffect()) + .dataScope(policy.getDataScope()).scopeParameter(policy.getScopeParameter()) + .priority(policy.getPriority()).enabled(policy.getEnabled()).delegable(policy.getDelegable()) + .riskLevel(policy.getRiskLevel()).protectedPolicy(policy.getProtectedPolicy()) + .validFrom(policy.getValidFrom()).validUntil(policy.getValidUntil()) + .version(policy.getRecordVersion()).fieldAccess(Collections.unmodifiableMap(fields)).build(); + } + + private AuthorizationBindingDto bindingDto(AuthorizationSubjectRoleBindingEntity binding, + AuthorizationSubjectType subjectType, String tenantId) { + return AuthorizationBindingDto.builder().id(binding.getId()).tenantId(tenantId) + .subjectType(subjectType).subjectId(binding.getSubjectId()).roleId(binding.getRoleId()) + .scopeOverride(binding.getScopeOverride()).scopeReferenceId(binding.getScopeReferenceId()) + .enabled(binding.getEnabled()).validFrom(binding.getValidFrom()).validUntil(binding.getValidUntil()) + .version(binding.getRecordVersion()).build(); + } + + private String resolveBindingTenant(AuthorizationSubjectRoleBindingEntity binding, + AuthorizationSubjectType subjectType) { + if (subjectType == AuthorizationSubjectType.USER) { + return users.findById(binding.getSubjectId()).map(SysUser::getTenantId).filter(StringUtils::hasText) + .orElse(null); + } + List memberships = groupMembers.findByIdGroupId(binding.getSubjectId()); + if (memberships == null || memberships.isEmpty()) return null; + Set userIds = new LinkedHashSet<>(); + for (SysUserGroupMember membership : memberships) { + if (membership != null && membership.getId() != null && membership.getId().getUserId() != null) + userIds.add(membership.getId().getUserId()); + } + if (userIds.isEmpty()) return null; + Set tenants = new LinkedHashSet<>(); + int resolvedUsers = 0; + for (SysUser user : users.findAllById(userIds)) { + if (user == null || !StringUtils.hasText(user.getTenantId())) return null; + resolvedUsers++; tenants.add(user.getTenantId()); + } + return resolvedUsers == userIds.size() && tenants.size() == 1 ? tenants.iterator().next() : null; + } + + private Map bindingMap(AuthorizationSubjectRoleBindingEntity binding) { + Map result = new LinkedHashMap<>(); + result.put("id", binding.getId()); result.put("subjectType", binding.getSubjectType()); + result.put("subjectId", binding.getSubjectId()); result.put("roleId", binding.getRoleId()); + result.put("scopeOverride", binding.getScopeOverride()); result.put("scopeReferenceId", binding.getScopeReferenceId()); + result.put("enabled", binding.getEnabled()); result.put("validFrom", binding.getValidFrom()); + result.put("validUntil", binding.getValidUntil()); result.put("version", binding.getRecordVersion()); + return result; + } + + private void requireSuperAdmin(Long actorId) { + if (actorId == null || !roleService.isSuperAdmin(actorId)) throw new BusinessException("只有超级管理员可以变更规范授权策略", 403); + } + + private void bumpVersion() { + if (versions.incrementPolicyVersion() == 0) { + AuthorizationPolicyVersionEntity version = new AuthorizationPolicyVersionEntity(); + version.setId(1); version.setPolicyVersion(1L); version.setUpdatedAt(LocalDateTime.now()); versions.save(version); + } + } + + private void audit(String action, Long actorId, String resourceType, Long resourceId, Map attributes) { + auditPort.emit(AuditEventCommand.builder().eventTime(Instant.now()).tenantId("default") + .category("ADMIN").action(action).outcome("SUCCESS").actorType("USER").actorId(actorId) + .targetType(resourceType).targetId(String.valueOf(resourceId)) + .resourceType(resourceType).resourceId(String.valueOf(resourceId)).source("WEB") + .changes(Collections.emptyMap()).attributes(attributes).build()); + } + + private String normalizedPart(Map body, String key) { + String value = evaluator.normalizePart(text(body, key, 80)); + if (value == null) throw new BadRequestException(key + "格式不正确"); + return value; + } + private String text(Map body, String key, int max) { + String value = optionalText(body, key, max); + if (!StringUtils.hasText(value)) throw new BadRequestException(key + "不能为空"); + return value; + } + private String optionalText(Map body, String key, int max) { + Object raw = body == null ? null : body.get(key); + if (raw == null) return null; + if (!(raw instanceof String)) throw new BadRequestException(key + "必须是字符串"); + String value = ((String)raw).trim(); + if (value.isEmpty()) return null; + if (value.length() > max || value.chars().anyMatch(Character::isISOControl)) throw new BadRequestException(key + "格式不正确"); + return value; + } + private > E enumValue(Map body, String key, Class type) { + E value = optionalEnum(body, key, type); + if (value == null) throw new BadRequestException(key + "不能为空或无效"); + return value; + } + private > E optionalEnum(Map body, String key, Class type) { + String value = optionalText(body, key, 40); + if (value == null) return null; + try { return Enum.valueOf(type, value.toUpperCase(Locale.ROOT)); } + catch (IllegalArgumentException ex) { throw new BadRequestException(key + "无效"); } + } + private int integer(Map body, String key, int fallback, int min, int max) { + Object raw = body == null ? null : body.get(key); + if (raw == null) return fallback; + if (!(raw instanceof Number)) throw new BadRequestException(key + "必须是整数"); + int value = ((Number)raw).intValue(); + if (value < min || value > max) throw new BadRequestException(key + "超出范围"); + return value; + } + private boolean bool(Map body, String key, boolean fallback) { + Object raw = body == null ? null : body.get(key); + if (raw == null) return fallback; + if (!(raw instanceof Boolean)) throw new BadRequestException(key + "必须是布尔值"); + return (Boolean)raw; + } + private Long positiveLong(Map body, String key) { + Long value = optionalPositiveLong(body, key); + if (value == null) throw new BadRequestException(key + "不能为空"); + return value; + } + private Long optionalPositiveLong(Map body, String key) { + Object raw = body == null ? null : body.get(key); + if (raw == null) return null; + if (!(raw instanceof Number) || ((Number)raw).longValue() <= 0) throw new BadRequestException(key + "必须是正整数"); + return ((Number)raw).longValue(); + } + private LocalDateTime optionalDateTime(Map body, String key) { + String value = optionalText(body, key, 40); + if (value == null) return null; + try { return LocalDateTime.parse(value); } + catch (java.time.format.DateTimeParseException ex) { throw new BadRequestException(key + "格式无效"); } + } + private Set positiveIds(Collection raw, String field) { + if (raw == null) throw new BadRequestException(field + "不能为空"); + Set result = new LinkedHashSet<>(); + for (Object value : raw) { + if (!(value instanceof Number) || ((Number)value).longValue() <= 0 || !result.add(((Number)value).longValue())) + throw new BadRequestException(field + "包含无效或重复ID"); + } + return result; + } + private Map attributes(Object... values) { + Map result = new LinkedHashMap<>(); + for (int i=0; i schemas() { + return Arrays.asList( + schema("ADMIN", "iam.policy.create", 1, none(), + fields("policyCode", code(120), "effectCode", enumeration("ALLOW", "DENY"))), + schema("ADMIN", "iam.policy.update", 1, none(), + fields("policyCode", code(120), "effectCode", enumeration("ALLOW", "DENY"))), + schema("ADMIN", "iam.role.policy.update", 1, none(), + fields("roleCode", code(80), "policyCount", integer(0, 10000))), + schema("ADMIN", "iam.binding.create", 1, none(), + fields("subjectType", enumeration("USER", "GROUP"), + "subjectId", integer(1, Long.MAX_VALUE), "roleCode", code(80))), + schema("ADMIN", "iam.binding.delete", 1, none(), + fields("subjectType", enumeration("USER", "GROUP"), + "subjectId", integer(1, Long.MAX_VALUE), "roleId", integer(1, Long.MAX_VALUE))), + schema("SECURITY", "security.authorization.denied", 1, none(), + fields("resource", code(80), "action", code(80), + "reason", code(80), "policyVersion", integer(0, Long.MAX_VALUE), + "matchedPolicyIds", codeList(MAX_MATCHED_POLICY_IDS, 32), + "matchedPolicyCount", integer(0, Integer.MAX_VALUE), + "truncated", flag())) + ); + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java b/src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java new file mode 100644 index 0000000..c38022a --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java @@ -0,0 +1,22 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Value; + +import java.time.LocalDateTime; + +@Value +@Builder +public class AuthorizationBindingDto { + Long id; + String tenantId; + AuthorizationSubjectType subjectType; + Long subjectId; + Long roleId; + DataScope scopeOverride; + Long scopeReferenceId; + Boolean enabled; + LocalDateTime validFrom; + LocalDateTime validUntil; + Long version; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java b/src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java new file mode 100644 index 0000000..2cbd424 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java @@ -0,0 +1,16 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Value; + +import java.util.List; + +@Value +@Builder +public class AuthorizationBindingPageDto { + List content; + int page; + int size; + long totalElements; + int totalPages; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java b/src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java new file mode 100644 index 0000000..0839017 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java @@ -0,0 +1,23 @@ +package com.finance.system.authorization; + +import lombok.Data; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.Pattern; + +@Data +public class AuthorizationBindingQueryRequest { + @Pattern(regexp = "\\*|[A-Za-z0-9][A-Za-z0-9._:-]{0,63}") + private String tenant; + private AuthorizationSubjectType subjectType; + @Min(1) + private Long subjectId; + @Min(1) + private Long roleId; + private Boolean enabled; + @Min(0) + private Integer page = 0; + @Min(1) @Max(100) + private Integer size = 20; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java b/src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java new file mode 100644 index 0000000..bbaed01 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java @@ -0,0 +1,52 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Value; + +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; + +@Value +@Builder +public class AuthorizationCapabilitiesDto { + String source; + Set capabilities; + Set auditAccess; + Set auditSecurity; + Set auditBusiness; + Set auditIntegration; + Set financeActions; + + public static AuthorizationCapabilitiesDto from(Set raw) { + Set canonical = new TreeSet<>(); + if (raw != null) for (String value : raw) { + if (value != null && value.contains(":") + && !value.startsWith("page.") && !value.startsWith("ui.page")) canonical.add(value); + } + return AuthorizationCapabilitiesDto.builder().source("CANONICAL_POLICY") + .capabilities(unmodifiable(canonical)) + .auditAccess(prefix(canonical, "audit.access:")) + .auditSecurity(prefix(canonical, "audit.security:")) + .auditBusiness(prefix(canonical, "audit.business:")) + .auditIntegration(prefix(canonical, "audit.integration:")) + .financeActions(prefixes(canonical, "finance.", "reimbursement.")) + .build(); + } + + private static Set prefix(Set values, String prefix) { + return prefixes(values, prefix); + } + + private static Set prefixes(Set values, String... prefixes) { + Set result = new TreeSet<>(); + for (String value : values) for (String prefix : prefixes) { + if (value.startsWith(prefix)) { result.add(value); break; } + } + return unmodifiable(result); + } + + private static Set unmodifiable(Set values) { + return Collections.unmodifiableSet(new TreeSet<>(values)); + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java new file mode 100644 index 0000000..a4feaf5 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java @@ -0,0 +1,23 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_permission_catalog_version") +public class AuthorizationCatalogVersionEntity { + @Id + private Integer id; + @Column(nullable = false) + private Long version; + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java new file mode 100644 index 0000000..d61ad0a --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java @@ -0,0 +1,15 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import javax.persistence.LockModeType; +import java.util.Optional; + +public interface AuthorizationCatalogVersionRepository extends JpaRepository { + @Lock(LockModeType.PESSIMISTIC_READ) + @Query("select v from AuthorizationCatalogVersionEntity v where v.id = :id") + Optional findByIdForShare(@Param("id") Integer id); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationController.java b/src/main/java/com/finance/system/authorization/AuthorizationController.java new file mode 100644 index 0000000..bc0fb60 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationController.java @@ -0,0 +1,159 @@ +package com.finance.system.authorization; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +@RestController +@RequestMapping("/api/authorization") +@RequiredArgsConstructor +@PreAuthorize("isAuthenticated()") +public class AuthorizationController { + private final AuthorizationService authorizationService; + private final AuthorizationAdminService adminService; + + @GetMapping("/capabilities") + public ResponseEntity> capabilities() { + SubjectContext subject = currentSubject(); + Set capabilities = authorizationService.capabilities(subject); + return ResponseEntity.ok(ApiResponse.success(AuthorizationCapabilitiesDto.from(capabilities))); + } + + /** Self-service explanation endpoint. The result is advisory and never reused as an enforcement token. */ + @PostMapping("/decision") + public ResponseEntity>> decision(@RequestBody Map body) { + SubjectContext subject = currentSubject(); + String resource = text(body, "resource"); + String action = text(body, "action"); + ResourceContext context = resource.startsWith("iam.") ? ResourceContext.global(resource) + : ResourceContext.builder().resourceType(resource) + .resourceId(optionalText(body, "resourceId")) + .tenantId(subject.getTenantId()) + .ownerId(optionalLong(body, "ownerId")) + .currentApproverId(optionalLong(body, "currentApproverId")) + .departmentId(optionalLong(body, "departmentId")) + .organizationId(optionalLong(body, "organizationId")).build(); + AuthorizationDecision decision = authorizationService.evaluate(AuthorizationRequest.builder() + .subject(subject).resource(resource).action(action).resourceContext(context).build()); + Map result = new LinkedHashMap<>(); + result.put("allowed", decision.isAllowed()); + result.put("reasonCode", decision.getReasonCode()); + result.put("matchedPolicyIds", decision.getMatchedPolicyIds()); + result.put("resolvedScope", decision.getResolvedScope()); + result.put("fieldAccess", decision.getFieldAccess()); + result.put("policyVersion", decision.getPolicyVersion()); + return ResponseEntity.ok(ApiResponse.success(result)); + } + + @GetMapping("/policies") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')") + public ResponseEntity>> policies() { + adminService.assertInternalPolicyAdmin(AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success(adminService.listPolicies())); + } + + @PostMapping("/policies") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')") + public ResponseEntity> createPolicy( + @Valid @RequestBody AuthorizationPolicyRequest body) { + throw rawPolicyWritesRetired(); + } + + @PutMapping("/policies/{id}") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')") + public ResponseEntity> updatePolicy(@PathVariable Long id, + @Valid @RequestBody AuthorizationPolicyRequest body) { + throw rawPolicyWritesRetired(); + } + + @GetMapping("/roles/{roleId}/policies") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')") + public ResponseEntity>> rolePolicies(@PathVariable Long roleId) { + adminService.assertInternalPolicyAdmin(AuditUtil.getCurrentUserId()); + Map result = new LinkedHashMap<>(); + result.put("policyIds", adminService.rolePolicyIds(roleId)); + return ResponseEntity.ok(ApiResponse.success(result)); + } + + @PutMapping("/roles/{roleId}/policies") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')") + public ResponseEntity> replaceRolePolicies(@PathVariable Long roleId, + @RequestBody Map body) { + throw rawPolicyWritesRetired(); + } + + @PostMapping("/bindings") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')") + public ResponseEntity>> createBinding(@RequestBody Map body) { + throw rawPolicyWritesRetired(); + } + + @GetMapping("/bindings") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')") + public ResponseEntity> bindings( + @Valid @ModelAttribute AuthorizationBindingQueryRequest query) { + UserPrincipal principal = currentPrincipal(); + return ResponseEntity.ok(ApiResponse.success( + adminService.listBindings(query, principal.getId(), principal.getTenantId()))); + } + + @DeleteMapping("/bindings/{id}") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')") + public ResponseEntity> deleteBinding(@PathVariable Long id) { + adminService.deleteSubjectBinding(id, AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success()); + } + + @GetMapping("/sod-rules") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')") + public ResponseEntity>>> sodRules() { + adminService.assertInternalPolicyAdmin(AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success(adminService.listSodRules())); + } + + private SubjectContext currentSubject() { + return authorizationService.subject(currentPrincipal()); + } + + private UserPrincipal currentPrincipal() { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null) throw new org.springframework.security.access.AccessDeniedException("Authentication required"); + return principal; + } + + private String text(Map body, String key) { + String value = optionalText(body, key); + if (value == null) throw new com.finance.system.exception.BadRequestException(key + "不能为空"); + return value; + } + + private String optionalText(Map body, String key) { + Object value = body == null ? null : body.get(key); + if (!(value instanceof String)) return null; + String text = ((String) value).trim(); + if (text.isEmpty() || text.length() > 120) return null; + return text; + } + + private Long optionalLong(Map body, String key) { + Object value = body == null ? null : body.get(key); + if (value == null) return null; + if (!(value instanceof Number)) throw new com.finance.system.exception.BadRequestException(key + "必须是整数"); + long parsed = ((Number) value).longValue(); + if (parsed <= 0) throw new com.finance.system.exception.BadRequestException(key + "必须是正整数"); + return parsed; + } + + private com.finance.system.exception.BusinessException rawPolicyWritesRetired() { + return new com.finance.system.exception.BusinessException("原始授权策略写入接口已停用,请使用角色授权档案", 410); + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationDecision.java b/src/main/java/com/finance/system/authorization/AuthorizationDecision.java new file mode 100644 index 0000000..716f352 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationDecision.java @@ -0,0 +1,26 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Singular; +import lombok.Value; + +import java.util.List; +import java.util.Map; + +@Value +@Builder +public class AuthorizationDecision { + boolean allowed; + String reasonCode; + DataScope resolvedScope; + @Singular List matchedPolicyIds; + @Singular("fieldAccess") Map fieldAccess; + long policyVersion; + boolean shadow; + Boolean legacyAllowed; + + public FieldAccess accessFor(String fieldCode) { + FieldAccess value = fieldAccess == null ? null : fieldAccess.get(fieldCode); + return value == null ? FieldAccess.HIDDEN : value; + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationDenialAuditService.java b/src/main/java/com/finance/system/authorization/AuthorizationDenialAuditService.java new file mode 100644 index 0000000..9b3d876 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationDenialAuditService.java @@ -0,0 +1,73 @@ +package com.finance.system.authorization; + +import com.finance.system.audit.AuditEventCommand; +import com.finance.system.audit.AuditPort; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.Collections; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; + +/** Persists authorization denials independently from the rejected business transaction. */ +@Service +@RequiredArgsConstructor +public class AuthorizationDenialAuditService { + private final AuditPort auditPort; + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void record(AuthorizationRequest request, AuthorizationDecision decision) { + SubjectContext subject = request == null ? null : request.getSubject(); + String resource = safeCode(request == null ? null : request.getResource(), "unknown"); + String action = safeCode(request == null ? null : request.getAction(), "unknown"); + String reason = safeCode(decision == null ? null : decision.getReasonCode(), "UNKNOWN_DENY"); + String resourceId = resource + ":" + action; + if (resourceId.length() > 128) resourceId = resourceId.substring(0, 128); + LinkedHashSet uniquePolicyIds = new LinkedHashSet<>(); + if (decision != null && decision.getMatchedPolicyIds() != null) { + for (Long id : decision.getMatchedPolicyIds()) { + if (id != null && id > 0) uniquePolicyIds.add(String.valueOf(id)); + } + } + int matchedPolicyCount = uniquePolicyIds.size(); + List policyIds = new ArrayList<>(Math.min(matchedPolicyCount, + AuthorizationAuditSchemaContributor.MAX_MATCHED_POLICY_IDS)); + for (String policyId : uniquePolicyIds) { + if (policyIds.size() >= AuthorizationAuditSchemaContributor.MAX_MATCHED_POLICY_IDS) break; + policyIds.add(policyId); + } + Map attributes = new LinkedHashMap<>(); + attributes.put("resource", resource); + attributes.put("action", action); + attributes.put("reason", reason); + attributes.put("policyVersion", decision == null ? 0L : decision.getPolicyVersion()); + attributes.put("matchedPolicyIds", policyIds); + attributes.put("matchedPolicyCount", matchedPolicyCount); + attributes.put("truncated", matchedPolicyCount > policyIds.size()); + auditPort.emit(AuditEventCommand.builder().eventTime(Instant.now()) + .tenantId(safeTenant(subject == null ? null : subject.getTenantId())) + .category("SECURITY").action("security.authorization.denied").outcome("DENIED") + .reasonCode(reason).actorType(subject == null ? "ANONYMOUS" : "USER") + .actorId(subject == null ? null : subject.getUserId()) + .resourceType("AUTHORIZATION").resourceId(resourceId) + .requestId(MDC.get("request_id")).source("INTERNAL") + .changes(Collections.emptyMap()).attributes(attributes).build()); + } + + private String safeCode(String value, String fallback) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,119}")) return fallback; + return value; + } + + private String safeTenant(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,63}")) return "default"; + return value; + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationFieldRuleEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationFieldRuleEntity.java new file mode 100644 index 0000000..c9133e3 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationFieldRuleEntity.java @@ -0,0 +1,21 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_field_rule") +public class AuthorizationFieldRuleEntity { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "policy_id", nullable = false) + private Long policyId; + @Column(name = "field_code", nullable = false, length = 120) + private String fieldCode; + @Enumerated(EnumType.STRING) @Column(name = "field_access", nullable = false, length = 16) + private FieldAccess fieldAccess; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationFieldRuleRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationFieldRuleRepository.java new file mode 100644 index 0000000..49a1f1f --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationFieldRuleRepository.java @@ -0,0 +1,12 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Collection; +import java.util.List; + +public interface AuthorizationFieldRuleRepository extends JpaRepository { + List findByPolicyIdIn(Collection policyIds); + List findByPolicyId(Long policyId); + void deleteByPolicyId(Long policyId); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationMode.java b/src/main/java/com/finance/system/authorization/AuthorizationMode.java new file mode 100644 index 0000000..b5e7cfa --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationMode.java @@ -0,0 +1,6 @@ +package com.finance.system.authorization; + +public enum AuthorizationMode { + SHADOW, + ENFORCE +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapEntity.java new file mode 100644 index 0000000..bea4c71 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapEntity.java @@ -0,0 +1,42 @@ +package com.finance.system.authorization; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Table; +import java.io.Serializable; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_permission_policy_map") +public class AuthorizationPermissionPolicyMapEntity { + @EmbeddedId + private Id id; + + @Enumerated(EnumType.STRING) + @Column(name = "min_access_level", nullable = false, length = 8) + private RolePermissionAccess minAccessLevel; + + @Enumerated(EnumType.STRING) + @Column(name = "mapping_type", nullable = false, length = 16) + private PermissionPolicyMappingType mappingType; + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Embeddable + public static class Id implements Serializable { + @Column(name = "permission_id") + private Long permissionId; + @Column(name = "policy_id") + private Long policyId; + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapRepository.java new file mode 100644 index 0000000..50fd0b9 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPermissionPolicyMapRepository.java @@ -0,0 +1,10 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Collection; +import java.util.List; + +public interface AuthorizationPermissionPolicyMapRepository extends JpaRepository { + List findByIdPermissionIdIn(Collection permissionIds); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyDto.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyDto.java new file mode 100644 index 0000000..975f685 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyDto.java @@ -0,0 +1,29 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Value; + +import java.time.LocalDateTime; +import java.util.Map; + +/** Public canonical policy representation; never exposes the JPA entity. */ +@Value +@Builder +public class AuthorizationPolicyDto { + Long id; + String policyCode; + String resource; + String action; + PolicyEffect effect; + DataScope dataScope; + String scopeParameter; + Integer priority; + Boolean enabled; + Boolean delegable; + PolicyRiskLevel riskLevel; + Boolean protectedPolicy; + LocalDateTime validFrom; + LocalDateTime validUntil; + Long version; + Map fieldAccess; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyEntity.java new file mode 100644 index 0000000..c6ab6ff --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyEntity.java @@ -0,0 +1,54 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_policy") +public class AuthorizationPolicyEntity { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "policy_code", nullable = false, length = 120, unique = true) + private String policyCode; + @Column(name = "resource_code", nullable = false, length = 80) + private String resourceCode; + @Column(name = "action_code", nullable = false, length = 80) + private String actionCode; + @Enumerated(EnumType.STRING) @Column(nullable = false, length = 10) + private PolicyEffect effect; + @Enumerated(EnumType.STRING) @Column(name = "data_scope", nullable = false, length = 24) + private DataScope dataScope; + @Column(name = "scope_parameter", length = 120) + private String scopeParameter; + @Column(nullable = false) + private Integer priority; + @Column(nullable = false) + private Boolean enabled; + @Column(nullable = false) + private Boolean delegable; + @Enumerated(EnumType.STRING) + @Column(name = "risk_level", nullable = false, length = 16) + private PolicyRiskLevel riskLevel; + @Column(name = "protected_policy", nullable = false) + private Boolean protectedPolicy; + @Column(name = "valid_from") + private LocalDateTime validFrom; + @Column(name = "valid_until") + private LocalDateTime validUntil; + @Version @Column(name = "record_version", nullable = false) + private Long recordVersion; + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; + + public boolean activeAt(LocalDateTime now) { + return Boolean.TRUE.equals(enabled) && (validFrom == null || !validFrom.isAfter(now)) + && (validUntil == null || validUntil.isAfter(now)); + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyEvaluator.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyEvaluator.java new file mode 100644 index 0000000..4a34ea5 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyEvaluator.java @@ -0,0 +1,157 @@ +package com.finance.system.authorization; + +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.*; +import java.util.regex.Pattern; + +/** Pure, default-deny policy evaluator. DENY always wins over ALLOW. */ +@Component +public class AuthorizationPolicyEvaluator { + private static final Pattern PART = Pattern.compile("[a-z][a-z0-9_.-]{0,79}"); + + public AuthorizationDecision evaluate(AuthorizationRequest request, + Collection candidates, + long policyVersion) { + if (!isValid(request)) return denied("INVALID_REQUEST", policyVersion, Collections.emptyList()); + String resource = normalizePart(request.getResource()); + String action = normalizePart(request.getAction()); + List matched = new ArrayList<>(); + if (candidates != null) { + for (EffectivePolicy policy : candidates) { + if (policy == null || policy.getEffect() == null || policy.getDataScope() == null) continue; + if (!matchesPart(policy.getResource(), resource) || !matchesPart(policy.getAction(), action)) continue; + if (matchesScope(request.getSubject(), request.getResourceContext(), policy)) matched.add(policy); + } + } + matched.sort(Comparator.comparingInt(EffectivePolicy::getPriority).reversed() + .thenComparing(p -> p.getPolicyId() == null ? Long.MAX_VALUE : p.getPolicyId())); + List ids = policyIds(matched); + for (EffectivePolicy policy : matched) { + if (policy.getEffect() == PolicyEffect.DENY) return denied("EXPLICIT_DENY", policyVersion, ids); + } + List allows = new ArrayList<>(); + for (EffectivePolicy policy : matched) if (policy.getEffect() == PolicyEffect.ALLOW) allows.add(policy); + if (allows.isEmpty()) return denied("DEFAULT_DENY", policyVersion, ids); + + Map fields = new TreeMap<>(); + DataScope scope = null; + for (EffectivePolicy policy : allows) { + scope = broader(scope, policy.getDataScope()); + if (policy.getFieldAccess() == null) continue; + for (Map.Entry entry : policy.getFieldAccess().entrySet()) { + String field = normalizeField(entry.getKey()); + if (field != null) fields.put(field, FieldAccess.stronger(fields.get(field), entry.getValue())); + } + } + return AuthorizationDecision.builder().allowed(true).reasonCode("ALLOW_POLICY") + .resolvedScope(scope).matchedPolicyIds(ids).fieldAccess(fields) + .policyVersion(policyVersion).shadow(false).build(); + } + + public String normalizePart(String value) { + if (!StringUtils.hasText(value)) return null; + String normalized = value.trim().toLowerCase(Locale.ROOT); + if (!PART.matcher(normalized).matches()) return null; + return normalized; + } + + public String permissionCode(String resource, String action) { + String normalizedResource = normalizePart(resource); + String normalizedAction = normalizePart(action); + if (normalizedResource == null || normalizedAction == null) return null; + return normalizedResource + ":" + normalizedAction; + } + + private boolean isValid(AuthorizationRequest request) { + return request != null && request.getSubject() != null + && request.getSubject().getUserId() != null + && normalizePart(request.getResource()) != null + && normalizePart(request.getAction()) != null; + } + + private boolean matchesPart(String configured, String actual) { + if ("*".equals(configured)) return true; + String normalized = normalizePart(configured); + return normalized != null && normalized.equals(actual); + } + + private boolean matchesScope(SubjectContext subject, ResourceContext resource, EffectivePolicy policy) { + switch (policy.getDataScope()) { + case GLOBAL: + return resource != null && resource.isExplicitGlobal(); + case ALL: + return sameIsolationBoundary(subject, resource); + case SELF: + return resource != null && Objects.equals(subject.getUserId(), resource.getOwnerId()) + && sameIsolationBoundary(subject, resource); + case CURRENT_APPROVER: + return resource != null && Objects.equals(subject.getUserId(), resource.getCurrentApproverId()) + && sameIsolationBoundary(subject, resource); + case DEPARTMENT: + return resource != null && subject.getDepartmentId() != null + && Objects.equals(subject.getDepartmentId(), resource.getDepartmentId()) + && matchesScopeParameter(resource.getDepartmentId(), policy.getScopeParameter()) + && sameIsolationBoundary(subject, resource); + case DEPARTMENT_TREE: + return resource != null && resource.getDepartmentId() != null + && (Objects.equals(subject.getDepartmentId(), resource.getDepartmentId()) + || subject.safeDepartmentTreeIds().contains(resource.getDepartmentId())) + && matchesScopeParameter(resource.getDepartmentId(), policy.getScopeParameter()) + && sameIsolationBoundary(subject, resource); + default: + return false; + } + } + + private boolean sameIsolationBoundary(SubjectContext subject, ResourceContext resource) { + return resource != null && StringUtils.hasText(subject.getTenantId()) + && StringUtils.hasText(resource.getTenantId()) + && subject.getOrganizationId() != null && resource.getOrganizationId() != null + && subject.getTenantId().equals(resource.getTenantId()) + && Objects.equals(subject.getOrganizationId(), resource.getOrganizationId()); + } + + private boolean matchesScopeParameter(Long resourceDepartmentId, String configured) { + if (!StringUtils.hasText(configured)) return true; + try { + return Objects.equals(resourceDepartmentId, Long.valueOf(configured.trim())); + } catch (NumberFormatException ex) { + return false; + } + } + + private String normalizeField(String value) { + if (!StringUtils.hasText(value)) return null; + String field = value.trim(); + return field.matches("[A-Za-z][A-Za-z0-9_.-]{0,119}") ? field : null; + } + + private List policyIds(List policies) { + List result = new ArrayList<>(); + for (EffectivePolicy policy : policies) if (policy.getPolicyId() != null) result.add(policy.getPolicyId()); + return result; + } + + private AuthorizationDecision denied(String reason, long version, List ids) { + return AuthorizationDecision.builder().allowed(false).reasonCode(reason) + .matchedPolicyIds(ids).fieldAccess(Collections.emptyMap()) + .policyVersion(version).shadow(false).build(); + } + + private DataScope broader(DataScope left, DataScope right) { + if (left == null) return right; + if (right == null) return left; + return scopeRank(left) >= scopeRank(right) ? left : right; + } + + private int scopeRank(DataScope scope) { + if (scope == DataScope.GLOBAL) return 6; + if (scope == DataScope.ALL) return 5; + if (scope == DataScope.DEPARTMENT_TREE) return 4; + if (scope == DataScope.DEPARTMENT) return 3; + if (scope == DataScope.CURRENT_APPROVER) return 2; + return 1; + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyRepository.java new file mode 100644 index 0000000..23331f0 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyRepository.java @@ -0,0 +1,9 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface AuthorizationPolicyRepository extends JpaRepository { + Optional findByPolicyCode(String policyCode); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyRequest.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyRequest.java new file mode 100644 index 0000000..d7e0bc0 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyRequest.java @@ -0,0 +1,55 @@ +package com.finance.system.authorization; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Controlled create/update payload for canonical policies. */ +@Data +public class AuthorizationPolicyRequest { + @NotBlank @Size(max = 120) + private String policyCode; + @NotBlank @Pattern(regexp = "[a-z][a-z0-9_.-]{0,79}") + private String resource; + @NotBlank @Pattern(regexp = "[a-z][a-z0-9_.-]{0,79}") + private String action; + @NotNull + private PolicyEffect effect; + @NotNull + private DataScope dataScope; + @Size(max = 120) + private String scopeParameter; + @Min(-10000) @Max(10000) + private Integer priority; + private Boolean enabled; + private Boolean delegable; + private PolicyRiskLevel riskLevel; + @JsonProperty("protected") + private Boolean protectedPolicy; + @Size(max = 200) + private Map fieldAccess; + + Map toMap() { + Map values = new LinkedHashMap<>(); + values.put("policyCode", policyCode); values.put("resource", resource); values.put("action", action); + values.put("effect", effect == null ? null : effect.name()); + values.put("dataScope", dataScope == null ? null : dataScope.name()); + put(values, "scopeParameter", scopeParameter); put(values, "priority", priority); + put(values, "enabled", enabled); put(values, "delegable", delegable); + put(values, "riskLevel", riskLevel == null ? null : riskLevel.name()); + put(values, "protected", protectedPolicy); put(values, "fieldAccess", fieldAccess); + return values; + } + + private void put(Map values, String key, Object value) { + if (value != null) values.put(key, value); + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionEntity.java new file mode 100644 index 0000000..32a9a33 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionEntity.java @@ -0,0 +1,19 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_policy_version") +public class AuthorizationPolicyVersionEntity { + @Id private Integer id; + @Column(name = "policy_version", nullable = false) + private Long policyVersion; + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionRepository.java new file mode 100644 index 0000000..d62bf47 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationPolicyVersionRepository.java @@ -0,0 +1,11 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; + +public interface AuthorizationPolicyVersionRepository extends JpaRepository { + @Modifying + @Query("update AuthorizationPolicyVersionEntity v set v.policyVersion = v.policyVersion + 1, v.updatedAt = CURRENT_TIMESTAMP where v.id = 1") + int incrementPolicyVersion(); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationProperties.java b/src/main/java/com/finance/system/authorization/AuthorizationProperties.java new file mode 100644 index 0000000..55fc920 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationProperties.java @@ -0,0 +1,17 @@ +package com.finance.system.authorization; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "authorization") +public class AuthorizationProperties { + /** Safe rollout default: observe new decisions while legacy callers remain compatible. */ + private AuthorizationMode mode = AuthorizationMode.SHADOW; + private boolean legacyAdapterEnabled = true; + + public AuthorizationMode getMode() { return mode; } + public void setMode(AuthorizationMode mode) { this.mode = mode == null ? AuthorizationMode.SHADOW : mode; } + public boolean isLegacyAdapterEnabled() { return legacyAdapterEnabled; } + public void setLegacyAdapterEnabled(boolean legacyAdapterEnabled) { this.legacyAdapterEnabled = legacyAdapterEnabled; } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationRequest.java b/src/main/java/com/finance/system/authorization/AuthorizationRequest.java new file mode 100644 index 0000000..d9acd72 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationRequest.java @@ -0,0 +1,13 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Value; + +@Value +@Builder +public class AuthorizationRequest { + SubjectContext subject; + String resource; + String action; + ResourceContext resourceContext; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationRolePolicyEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationRolePolicyEntity.java new file mode 100644 index 0000000..6e6604a --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationRolePolicyEntity.java @@ -0,0 +1,41 @@ +package com.finance.system.authorization; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.io.Serializable; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "authz_role_policy") +public class AuthorizationRolePolicyEntity { + @EmbeddedId + private Id id; + + @Enumerated(EnumType.STRING) + @Column(name = "assignment_source", nullable = false, length = 16) + private AuthorizationAssignmentSource assignmentSource; + + public AuthorizationRolePolicyEntity(Long roleId, Long policyId) { + this.id = new Id(roleId, policyId); + this.assignmentSource = AuthorizationAssignmentSource.LEGACY; + } + + public AuthorizationRolePolicyEntity(Long roleId, Long policyId, AuthorizationAssignmentSource assignmentSource) { + this.id = new Id(roleId, policyId); + this.assignmentSource = assignmentSource; + } + + @Data + @NoArgsConstructor + @AllArgsConstructor + @Embeddable + public static class Id implements Serializable { + @Column(name = "role_id") private Long roleId; + @Column(name = "policy_id") private Long policyId; + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationRolePolicyRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationRolePolicyRepository.java new file mode 100644 index 0000000..3f89a10 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationRolePolicyRepository.java @@ -0,0 +1,30 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Collection; +import java.util.List; + +public interface AuthorizationRolePolicyRepository extends JpaRepository { + List findByIdRoleIdIn(Collection roleIds); + List findByIdRoleId(Long roleId); + List findByIdRoleIdAndAssignmentSource(Long roleId, AuthorizationAssignmentSource assignmentSource); + List findByIdPolicyId(Long policyId); + void deleteByIdRoleId(Long roleId); + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Query(value = "UPDATE authz_role_policy rp JOIN authz_policy p ON p.id = rp.policy_id " + + "SET rp.assignment_source = 'SYSTEM' " + + "WHERE rp.role_id = :roleId AND p.effect = 'DENY' AND rp.assignment_source <> 'SYSTEM'", nativeQuery = true) + int protectDenyByRoleId(@Param("roleId") Long roleId); + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Query(value = "DELETE rp FROM authz_role_policy rp JOIN authz_policy p ON p.id = rp.policy_id " + + "WHERE rp.role_id = :roleId AND rp.assignment_source <> 'SYSTEM' " + + "AND p.effect = 'ALLOW' AND p.delegable = TRUE AND p.protected_policy = FALSE " + + "AND p.risk_level IS NOT NULL AND p.risk_level <> 'CRITICAL' " + + "AND EXISTS (SELECT 1 FROM authz_permission_policy_map ppm " + + "WHERE ppm.policy_id = rp.policy_id AND ppm.mapping_type = 'BUSINESS')", nativeQuery = true) + int deleteReplaceableBusinessMappedByRoleId(@Param("roleId") Long roleId); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionEntity.java new file mode 100644 index 0000000..dd317ee --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionEntity.java @@ -0,0 +1,21 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_role_profile_version") +public class AuthorizationRoleProfileVersionEntity { + @Id + @Column(name = "role_id") + private Long roleId; + @Column(nullable = false) + private Long version; + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionRepository.java new file mode 100644 index 0000000..ae2625f --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationRoleProfileVersionRepository.java @@ -0,0 +1,21 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.repository.query.Param; + +import javax.persistence.LockModeType; +import java.util.Optional; + +public interface AuthorizationRoleProfileVersionRepository extends JpaRepository { + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select v from AuthorizationRoleProfileVersionEntity v where v.roleId = :roleId") + Optional findByRoleIdForUpdate(@Param("roleId") Long roleId); + + @Modifying + @Query(value = "INSERT INTO authz_role_profile_version(role_id,version,updated_at) VALUES (:roleId,1,CURRENT_TIMESTAMP(6)) " + + "ON DUPLICATE KEY UPDATE version=version+1,updated_at=CURRENT_TIMESTAMP(6)", nativeQuery = true) + int bumpRoleVersion(@Param("roleId") Long roleId); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationService.java b/src/main/java/com/finance/system/authorization/AuthorizationService.java new file mode 100644 index 0000000..581b85d --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationService.java @@ -0,0 +1,339 @@ +package com.finance.system.authorization; + +import com.finance.system.adapter.feishu.FeishuDirectoryAccessService; +import com.finance.system.entity.SysUserGroupMember; +import com.finance.system.entity.SysUserGroupRole; +import com.finance.system.entity.SysRole; +import com.finance.system.entity.SysUser; +import com.finance.system.entity.SysUserGroup; +import com.finance.system.entity.SysUserRole; +import com.finance.system.repository.SysUserGroupMemberRepository; +import com.finance.system.repository.SysUserGroupRoleRepository; +import com.finance.system.repository.SysUserGroupRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.repository.SysRoleRepository; +import com.finance.system.repository.SysUserRoleRepository; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.entity.SysDepartment; +import com.finance.system.security.UserPrincipal; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; + +@Slf4j +@Service +@RequiredArgsConstructor +public class AuthorizationService { + private static final String DEFAULT_EMPLOYEE_GROUP = "DEFAULT_EMPLOYEE"; + private static final String EMPLOYEE_ROLE = "EMPLOYEE"; + private final AuthorizationPolicyEvaluator evaluator; + private final AuthorizationPolicyRepository policies; + private final AuthorizationRolePolicyRepository rolePolicies; + private final AuthorizationSubjectRoleBindingRepository subjectBindings; + private final AuthorizationFieldRuleRepository fieldRules; + private final AuthorizationPolicyVersionRepository versions; + private final SysUserGroupMemberRepository groupMembers; + private final SysUserGroupRoleRepository legacyGroupRoles; + private final SysUserRoleRepository legacyUserRoles; + private final SysUserRepository users; + private final SysUserGroupRepository groups; + private final SysRoleRepository roles; + private final SysDepartmentRepository departments; + private final LegacyPermissionAdapter legacyAdapter; + private final AuthorizationProperties properties; + private final AuthorizationDenialAuditService denialAudit; + private AuthorizationShadowMetrics shadowMetrics; + private FeishuDirectoryAccessService directoryAccess; + + @Autowired + void setShadowMetrics(AuthorizationShadowMetrics shadowMetrics) { + this.shadowMetrics = shadowMetrics; + } + + @Autowired(required = false) + void setDirectoryAccess(FeishuDirectoryAccessService directoryAccess) { + this.directoryAccess = directoryAccess; + } + + @Transactional(readOnly = true) + public AuthorizationDecision evaluate(AuthorizationRequest request) { + if (request == null || request.getSubject() == null) { + return evaluator.evaluate(request, Collections.emptyList(), policyVersion()); + } + return evaluator.evaluate(request, loadEffectivePolicies(request.getSubject()), policyVersion()); + } + + /** Always enforces the canonical decision; rollout mode does not weaken this API. */ + @Transactional(readOnly = true) + public AuthorizationDecision check(AuthorizationRequest request) { + AuthorizationDecision decision = evaluate(request); + if (!decision.isAllowed()) { + try { + denialAudit.record(request, decision); + } catch (RuntimeException ex) { + log.error("授权拒绝审计记录失败 authorization_denial_audit_failed reason={}", safeCode(decision.getReasonCode())); + } + throw new AccessDeniedException("Authorization denied: " + decision.getReasonCode()); + } + return decision; + } + + @Transactional(readOnly = true) + public boolean can(AuthorizationRequest request) { + return evaluate(request).isAllowed(); + } + + /** Legacy method-security bridge. SHADOW preserves the legacy result; ENFORCE uses only the canonical result. */ + @Transactional(readOnly = true) + public boolean evaluateLegacy(SubjectContext subject, String legacyPermissionCode, + boolean edit, boolean legacyAllowed) { + if (!properties.isLegacyAdapterEnabled()) return false; + LegacyPermissionAdapter.CanonicalPermission canonical = legacyAdapter.adapt(legacyPermissionCode, edit); + AuthorizationDecision canonicalDecision; + if (canonical == null || canonical.getResource().startsWith("ui.page")) { + canonicalDecision = AuthorizationDecision.builder().allowed(false) + .reasonCode(canonical == null ? "LEGACY_UNMAPPED" : "UI_PERMISSION_NOT_BUSINESS_AUTHORITY") + .policyVersion(policyVersion()).shadow(true).legacyAllowed(legacyAllowed).build(); + } else { + ResourceContext context = canonical.getResource().startsWith("iam.") + ? ResourceContext.global(canonical.getResource()) + : ResourceContext.unscoped(canonical.getResource()); + canonicalDecision = evaluate(AuthorizationRequest.builder().subject(subject) + .resource(canonical.getResource()).action(canonical.getAction()) + .resourceContext(context).build()); + } + if (canonicalDecision.isAllowed() != legacyAllowed) { + log.warn("授权影子校验结果不一致 authorization_shadow_mismatch code={} canonical={} legacy={} reason={}", + safeCode(legacyPermissionCode), canonicalDecision.isAllowed(), legacyAllowed, + canonicalDecision.getReasonCode()); + } + if (shadowMetrics != null) shadowMetrics.record(canonicalDecision.isAllowed(), legacyAllowed); + return properties.getMode() == AuthorizationMode.SHADOW ? legacyAllowed : canonicalDecision.isAllowed(); + } + + @Transactional(readOnly = true) + public List filter(SubjectContext subject, String resource, String action, + Collection values, Function contextFactory) { + List result = new ArrayList<>(); + if (values == null || contextFactory == null) return result; + for (T value : values) { + AuthorizationRequest request = AuthorizationRequest.builder().subject(subject) + .resource(resource).action(action).resourceContext(contextFactory.apply(value)).build(); + if (evaluate(request).isAllowed()) result.add(value); + } + return result; + } + + /** Applies server-side read obligations to a flat DTO/map. Unknown fields default to HIDDEN. */ + public Map project(Map source, AuthorizationDecision decision) { + Map result = new LinkedHashMap<>(); + if (source == null || decision == null || !decision.isAllowed()) return result; + for (Map.Entry entry : source.entrySet()) { + FieldAccess access = decision.accessFor(entry.getKey()); + if (access == FieldAccess.READ || access == FieldAccess.EDIT) result.put(entry.getKey(), entry.getValue()); + else if (access == FieldAccess.MASKED) result.put(entry.getKey(), mask(entry.getValue())); + } + return result; + } + + @Transactional(readOnly = true) + public Set capabilities(SubjectContext subject) { + Set result = new TreeSet<>(); + if (subject == null || subject.getUserId() == null) return result; + LocalDateTime now = LocalDateTime.now(); + List effectivePolicies = loadEffectivePolicies(subject, now); + long version = policyVersion(); + for (AuthorizationPolicyEntity policy : safe(policies.findAll())) { + if (policy == null || !policy.activeAt(now)) continue; + String permissionCode = evaluator.permissionCode(policy.getResourceCode(), policy.getActionCode()); + if (permissionCode == null || permissionCode.trim().isEmpty()) continue; + ResourceContext context = policy.getDataScope() == DataScope.GLOBAL + ? ResourceContext.global(policy.getResourceCode()) + : ResourceContext.builder().resourceType(policy.getResourceCode()) + .ownerId(subject.getUserId()).currentApproverId(subject.getUserId()) + .tenantId(subject.getTenantId()).departmentId(subject.getDepartmentId()) + .organizationId(subject.getOrganizationId()).build(); + AuthorizationDecision decision = evaluator.evaluate(AuthorizationRequest.builder().subject(subject) + .resource(policy.getResourceCode()).action(policy.getActionCode()) + .resourceContext(context).build(), effectivePolicies, version); + if (decision.isAllowed()) result.add(permissionCode); + } + return result; + } + + public SubjectContext subject(UserPrincipal principal) { + if (principal == null) return null; + SubjectContext.SubjectContextBuilder builder = SubjectContext.builder().userId(principal.getId()) + .tenantId(principal.getTenantId()).organizationId(principal.getOrganizationId()) + .departmentId(principal.getDepartmentId()); + for (Long departmentId : departmentTree(principal.getDepartmentId())) builder.departmentTreeId(departmentId); + return builder.build(); + } + + private Set departmentTree(Long rootId) { + if (rootId == null) return Collections.emptySet(); + Map> children = new HashMap<>(); + List activeDepartments = departments.findByStatus("ACTIVE"); + if (activeDepartments == null) activeDepartments = Collections.emptyList(); + for (SysDepartment department : activeDepartments) { + if (department.getId() == null || department.getParentId() == null) continue; + children.computeIfAbsent(department.getParentId(), key -> new ArrayList<>()).add(department.getId()); + } + Set result = new LinkedHashSet<>(); + Deque queue = new ArrayDeque<>(); + queue.add(rootId); + while (!queue.isEmpty() && result.size() < 10000) { + Long current = queue.removeFirst(); + if (!result.add(current)) continue; + for (Long child : children.getOrDefault(current, Collections.emptyList())) queue.addLast(child); + } + return result; + } + + private List loadEffectivePolicies(SubjectContext subject) { + return loadEffectivePolicies(subject, LocalDateTime.now()); + } + + private List loadEffectivePolicies(SubjectContext subject, LocalDateTime now) { + Map> grants = roleGrants(subject, now); + if (grants.isEmpty()) return Collections.emptyList(); + List links = rolePolicies.findByIdRoleIdIn(grants.keySet()); + Set policyIds = new LinkedHashSet<>(); + for (AuthorizationRolePolicyEntity link : links) { + if (link != null && link.getId() != null && link.getId().getPolicyId() != null) policyIds.add(link.getId().getPolicyId()); + } + if (policyIds.isEmpty()) return Collections.emptyList(); + Map policyById = new HashMap<>(); + for (AuthorizationPolicyEntity policy : policies.findAllById(policyIds)) { + if (policy.activeAt(now)) policyById.put(policy.getId(), policy); + } + Map> fieldsByPolicy = new HashMap<>(); + for (AuthorizationFieldRuleEntity rule : fieldRules.findByPolicyIdIn(policyIds)) { + if (rule.getPolicyId() == null || rule.getFieldAccess() == null) continue; + fieldsByPolicy.computeIfAbsent(rule.getPolicyId(), k -> new LinkedHashMap<>()) + .merge(rule.getFieldCode(), rule.getFieldAccess(), FieldAccess::stronger); + } + List result = new ArrayList<>(); + for (AuthorizationRolePolicyEntity link : links) { + if (link == null || link.getId() == null) continue; + AuthorizationPolicyEntity policy = policyById.get(link.getId().getPolicyId()); + if (policy == null) continue; + for (RoleGrant grant : grants.getOrDefault(link.getId().getRoleId(), Collections.emptyList())) { + DataScope scope = grant.scopeOverride == null ? policy.getDataScope() : grant.scopeOverride; + String scopeParameter = grant.scopeReferenceId == null ? policy.getScopeParameter() + : String.valueOf(grant.scopeReferenceId); + result.add(EffectivePolicy.builder().policyId(policy.getId()).resource(policy.getResourceCode()) + .action(policy.getActionCode()).effect(policy.getEffect()).dataScope(scope) + .scopeParameter(scopeParameter).priority(policy.getPriority() == null ? 0 : policy.getPriority()) + .fieldAccess(fieldsByPolicy.getOrDefault(policy.getId(), Collections.emptyMap())) + .build()); + } + } + return result; + } + + private Map> roleGrants(SubjectContext subject, LocalDateTime now) { + Map> result = new LinkedHashMap<>(); + SysUser user = users.findById(subject.getUserId()).orElse(null); + if (user == null || !isActive(user.getStatus())) return result; + if (!Objects.equals(user.getTenantId(), subject.getTenantId()) + || !Objects.equals(user.getOrganizationId(), subject.getOrganizationId()) + || !Objects.equals(user.getDepartmentId(), subject.getDepartmentId())) return result; + for (SysUserRole link : safe(legacyUserRoles.findByIdUserId(subject.getUserId()))) { + if (link != null && link.getId() != null) addGrant(result, link.getId().getRoleId(), null, null); + } + Set candidateGroupIds = new LinkedHashSet<>(); + for (SysUserGroupMember membership : safe(groupMembers.findByIdUserId(subject.getUserId()))) { + if (membership != null && membership.getId() != null) candidateGroupIds.add(membership.getId().getGroupId()); + } + if (isDynamicDefaultEmployee(user)) { + roles.findByRoleCode(EMPLOYEE_ROLE) + .filter(role -> role.getId() != null && isActive(role.getStatus())) + .map(SysRole::getId) + .ifPresent(roleId -> addGrant(result, roleId, null, null)); + } + Set groupIds = new LinkedHashSet<>(); + if (!candidateGroupIds.isEmpty()) { + for (SysUserGroup group : safe(groups.findAllById(candidateGroupIds))) { + if (group != null && group.getId() != null && isActive(group.getStatus())) groupIds.add(group.getId()); + } + } + for (Long groupId : groupIds) { + for (SysUserGroupRole link : safe(legacyGroupRoles.findByIdGroupId(groupId))) { + if (link != null && link.getId() != null) addGrant(result, link.getId().getRoleId(), null, null); + } + } + for (AuthorizationSubjectRoleBindingEntity binding : safe(subjectBindings.findBySubjectTypeAndSubjectId("USER", subject.getUserId()))) { + if (binding != null && binding.activeAt(now)) addGrant(result, binding.getRoleId(), binding.getScopeOverride(), binding.getScopeReferenceId()); + } + if (!groupIds.isEmpty()) { + for (AuthorizationSubjectRoleBindingEntity binding : safe(subjectBindings.findBySubjectTypeAndSubjectIdIn("GROUP", groupIds))) { + if (binding != null && binding.activeAt(now)) addGrant(result, binding.getRoleId(), binding.getScopeOverride(), binding.getScopeReferenceId()); + } + } + if (!result.isEmpty()) { + Set activeRoleIds = new LinkedHashSet<>(); + for (SysRole role : safe(roles.findAllById(result.keySet()))) { + if (role != null && role.getId() != null && isActive(role.getStatus())) activeRoleIds.add(role.getId()); + } + result.keySet().retainAll(activeRoleIds); + } + return result; + } + + private boolean isDynamicDefaultEmployee(SysUser user) { + SysUserGroup defaultGroup = groups.findByGroupCode(DEFAULT_EMPLOYEE_GROUP).orElse(null); + return defaultGroup != null + && DEFAULT_EMPLOYEE_GROUP.equalsIgnoreCase(defaultGroup.getGroupCode()) + && isActive(defaultGroup.getStatus()) + && directoryAccess != null + && directoryAccess.directoryAllowed(user) + && user.getDirectoryLastSeenRunId() != null + && StringUtils.hasText(user.getFeishuOpenId()); + } + + private boolean isActive(String status) { + return "ACTIVE".equalsIgnoreCase(status); + } + + private Iterable safe(Iterable values) { + return values == null ? Collections.emptyList() : values; + } + + private void addGrant(Map> target, Long roleId, DataScope scope, Long ref) { + if (roleId != null) target.computeIfAbsent(roleId, k -> new ArrayList<>()).add(new RoleGrant(scope, ref)); + } + + private long policyVersion() { + return versions.findById(1).map(AuthorizationPolicyVersionEntity::getPolicyVersion).orElse(0L); + } + + private String safeCode(String code) { + if (code == null) return "null"; + return code.length() > 120 ? code.substring(0, 120) : code.replaceAll("[^A-Za-z0-9._:-]", "_"); + } + + private String mask(Object value) { + if (value == null) return null; + String text = String.valueOf(value); + if (text.length() <= 4) return "****"; + return text.substring(0, 2) + "****" + text.substring(text.length() - 2); + } + + private static final class RoleGrant { + private final DataScope scopeOverride; + private final Long scopeReferenceId; + private RoleGrant(DataScope scopeOverride, Long scopeReferenceId) { + this.scopeOverride = scopeOverride; + this.scopeReferenceId = scopeReferenceId; + } + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationShadowMetrics.java b/src/main/java/com/finance/system/authorization/AuthorizationShadowMetrics.java new file mode 100644 index 0000000..f4b5af0 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationShadowMetrics.java @@ -0,0 +1,38 @@ +package com.finance.system.authorization; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.MeterRegistry; +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicLong; + +@Component +public class AuthorizationShadowMetrics { + private final Counter allowMismatch; + private final Counter denyMismatch; + private final AtomicLong evaluations = new AtomicLong(); + private final AtomicLong mismatches = new AtomicLong(); + + public AuthorizationShadowMetrics(MeterRegistry registry) { + allowMismatch = Counter.builder("authorization.shadow.allow.mismatch") + .description("Canonical allow while legacy denied").register(registry); + denyMismatch = Counter.builder("authorization.shadow.deny.mismatch") + .description("Canonical deny while legacy allowed").register(registry); + Gauge.builder("authorization.shadow.mismatch.ratio", this, AuthorizationShadowMetrics::ratio) + .description("Canonical/legacy mismatch ratio").register(registry); + } + + public void record(boolean canonicalAllowed, boolean legacyAllowed) { + evaluations.incrementAndGet(); + if (canonicalAllowed == legacyAllowed) return; + mismatches.incrementAndGet(); + if (canonicalAllowed) allowMismatch.increment(); + else denyMismatch.increment(); + } + + double ratio() { + long total = evaluations.get(); + return total == 0L ? 0.0d : ((double) mismatches.get()) / total; + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationSodRuleEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationSodRuleEntity.java new file mode 100644 index 0000000..7a565da --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationSodRuleEntity.java @@ -0,0 +1,29 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_sod_rule") +public class AuthorizationSodRuleEntity { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "rule_code", nullable = false, unique = true, length = 120) + private String ruleCode; + @Column(name = "left_duty", nullable = false, length = 80) + private String leftDuty; + @Column(name = "right_duty", nullable = false, length = 80) + private String rightDuty; + @Column(name = "relation_type", nullable = false, length = 32) + private String relationType; + @Column(nullable = false) + private Boolean enabled; + @Column(name = "valid_from") private LocalDateTime validFrom; + @Column(name = "valid_until") private LocalDateTime validUntil; + @Version @Column(name = "record_version", nullable = false) private Long recordVersion; +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationSodRuleRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationSodRuleRepository.java new file mode 100644 index 0000000..92eafe3 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationSodRuleRepository.java @@ -0,0 +1,9 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface AuthorizationSodRuleRepository extends JpaRepository { + List findByEnabledTrue(); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingEntity.java new file mode 100644 index 0000000..2da1c93 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingEntity.java @@ -0,0 +1,41 @@ +package com.finance.system.authorization; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "authz_subject_role_binding") +public class AuthorizationSubjectRoleBindingEntity { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "subject_type", nullable = false, length = 16) + private String subjectType; + @Column(name = "subject_id", nullable = false) + private Long subjectId; + @Column(name = "role_id", nullable = false) + private Long roleId; + @Enumerated(EnumType.STRING) @Column(name = "scope_override", length = 24) + private DataScope scopeOverride; + @Column(name = "scope_reference_id") + private Long scopeReferenceId; + @Column(nullable = false) + private Boolean enabled; + @Column(name = "valid_from") + private LocalDateTime validFrom; + @Column(name = "valid_until") + private LocalDateTime validUntil; + @Column(name = "created_by") + private Long createdBy; + @Version @Column(name = "record_version", nullable = false) + private Long recordVersion; + + public boolean activeAt(LocalDateTime now) { + return Boolean.TRUE.equals(enabled) && (validFrom == null || !validFrom.isAfter(now)) + && (validUntil == null || validUntil.isAfter(now)); + } +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingRepository.java new file mode 100644 index 0000000..e84cc4f --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationSubjectRoleBindingRepository.java @@ -0,0 +1,23 @@ +package com.finance.system.authorization; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Collection; +import java.util.List; + +public interface AuthorizationSubjectRoleBindingRepository extends JpaRepository { + List findBySubjectTypeAndSubjectId(String subjectType, Long subjectId); + List findBySubjectTypeAndSubjectIdIn(String subjectType, Collection subjectIds); + + @Query("select case when count(b)>0 then true else false end from AuthorizationSubjectRoleBindingEntity b " + + "where b.subjectType=:subjectType and b.subjectId=:subjectId and b.roleId=:roleId " + + "and ((:scopeOverride is null and b.scopeOverride is null) or b.scopeOverride=:scopeOverride) " + + "and ((:scopeReferenceId is null and b.scopeReferenceId is null) or b.scopeReferenceId=:scopeReferenceId)") + boolean existsNormalized(@Param("subjectType") String subjectType, + @Param("subjectId") Long subjectId, + @Param("roleId") Long roleId, + @Param("scopeOverride") DataScope scopeOverride, + @Param("scopeReferenceId") Long scopeReferenceId); +} diff --git a/src/main/java/com/finance/system/authorization/AuthorizationSubjectType.java b/src/main/java/com/finance/system/authorization/AuthorizationSubjectType.java new file mode 100644 index 0000000..a96d351 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/AuthorizationSubjectType.java @@ -0,0 +1,6 @@ +package com.finance.system.authorization; + +public enum AuthorizationSubjectType { + USER, + GROUP +} diff --git a/src/main/java/com/finance/system/authorization/DataScope.java b/src/main/java/com/finance/system/authorization/DataScope.java new file mode 100644 index 0000000..8952c42 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/DataScope.java @@ -0,0 +1,11 @@ +package com.finance.system.authorization; + +public enum DataScope { + /** Explicit cross-organization system-administration scope. */ + GLOBAL, + SELF, + CURRENT_APPROVER, + DEPARTMENT, + DEPARTMENT_TREE, + ALL +} diff --git a/src/main/java/com/finance/system/authorization/EffectivePolicy.java b/src/main/java/com/finance/system/authorization/EffectivePolicy.java new file mode 100644 index 0000000..24b89ec --- /dev/null +++ b/src/main/java/com/finance/system/authorization/EffectivePolicy.java @@ -0,0 +1,20 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Singular; +import lombok.Value; + +import java.util.Map; + +@Value +@Builder +public class EffectivePolicy { + Long policyId; + String resource; + String action; + PolicyEffect effect; + DataScope dataScope; + String scopeParameter; + int priority; + @Singular("fieldAccess") Map fieldAccess; +} diff --git a/src/main/java/com/finance/system/authorization/FieldAccess.java b/src/main/java/com/finance/system/authorization/FieldAccess.java new file mode 100644 index 0000000..75030b0 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/FieldAccess.java @@ -0,0 +1,24 @@ +package com.finance.system.authorization; + +public enum FieldAccess { + HIDDEN(0), + MASKED(1), + READ(2), + EDIT(3); + + private final int rank; + + FieldAccess(int rank) { + this.rank = rank; + } + + public int rank() { + return rank; + } + + public static FieldAccess stronger(FieldAccess left, FieldAccess right) { + if (left == null) return right == null ? HIDDEN : right; + if (right == null) return left; + return left.rank >= right.rank ? left : right; + } +} diff --git a/src/main/java/com/finance/system/authorization/LegacyPermissionAdapter.java b/src/main/java/com/finance/system/authorization/LegacyPermissionAdapter.java new file mode 100644 index 0000000..6f5f213 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/LegacyPermissionAdapter.java @@ -0,0 +1,61 @@ +package com.finance.system.authorization; + +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +/** + * Temporary compatibility mapping. Page/menu permissions intentionally map + * only to ui.page and can never authorize a business resource. + */ +@Component +public class LegacyPermissionAdapter { + private final Map mappings; + + public LegacyPermissionAdapter() { + Map values = new HashMap<>(); + map(values, "system.role.create", "iam.role", "create"); + map(values, "system.role.edit", "iam.role", "update"); + map(values, "system.role.delete", "iam.role", "delete"); + map(values, "system.role.permission.configure", "iam.policy", "manage"); + map(values, "system.group.create", "iam.group", "create"); + map(values, "system.group.edit", "iam.group", "update"); + map(values, "system.group.delete", "iam.group", "delete"); + map(values, "system.group.member.bind", "iam.group.member", "manage"); + map(values, "system.group.role.bind", "iam.group.role", "manage"); + map(values, "system.user.status.change", "iam.user.status", "manage"); + map(values, "system.role.view", "iam.role", "read"); + map(values, "system.group.view", "iam.group", "read"); + map(values, "system.user.view", "iam.user", "read"); + mappings = Collections.unmodifiableMap(values); + } + + public CanonicalPermission adapt(String legacyCode, boolean edit) { + if (legacyCode == null) return null; + String normalized = legacyCode.trim().toLowerCase(Locale.ROOT); + if (normalized.startsWith("page.")) { + return new CanonicalPermission("ui.page", normalized.substring("page.".length()) + ".view"); + } + return mappings.get(normalized); + } + + private void map(Map values, String legacy, String resource, String action) { + values.put(legacy.toLowerCase(Locale.ROOT), new CanonicalPermission(resource, action)); + } + + public static final class CanonicalPermission { + private final String resource; + private final String action; + + CanonicalPermission(String resource, String action) { + this.resource = resource; + this.action = action; + } + + public String getResource() { return resource; } + public String getAction() { return action; } + } +} diff --git a/src/main/java/com/finance/system/authorization/PermissionPolicyMappingType.java b/src/main/java/com/finance/system/authorization/PermissionPolicyMappingType.java new file mode 100644 index 0000000..d7edab3 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/PermissionPolicyMappingType.java @@ -0,0 +1,6 @@ +package com.finance.system.authorization; + +public enum PermissionPolicyMappingType { + BUSINESS, + SYSTEM +} diff --git a/src/main/java/com/finance/system/authorization/PolicyEffect.java b/src/main/java/com/finance/system/authorization/PolicyEffect.java new file mode 100644 index 0000000..1ffbfb7 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/PolicyEffect.java @@ -0,0 +1,6 @@ +package com.finance.system.authorization; + +public enum PolicyEffect { + ALLOW, + DENY +} diff --git a/src/main/java/com/finance/system/authorization/PolicyRiskLevel.java b/src/main/java/com/finance/system/authorization/PolicyRiskLevel.java new file mode 100644 index 0000000..bdc247d --- /dev/null +++ b/src/main/java/com/finance/system/authorization/PolicyRiskLevel.java @@ -0,0 +1,8 @@ +package com.finance.system.authorization; + +/** Closed risk vocabulary for canonical authorization policies. */ +public enum PolicyRiskLevel { + NORMAL, + HIGH, + CRITICAL +} diff --git a/src/main/java/com/finance/system/authorization/ResourceContext.java b/src/main/java/com/finance/system/authorization/ResourceContext.java new file mode 100644 index 0000000..3e148b3 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/ResourceContext.java @@ -0,0 +1,32 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Singular; +import lombok.Value; + +import java.util.Map; + +@Value +@Builder +public class ResourceContext { + String resourceType; + String resourceId; + String tenantId; + Long organizationId; + Long ownerId; + Long currentApproverId; + Long departmentId; + @Singular("attribute") Map attributes; + + public static ResourceContext unscoped(String resourceType) { + return ResourceContext.builder().resourceType(resourceType).build(); + } + + public static ResourceContext global(String resourceType) { + return ResourceContext.builder().resourceType(resourceType).attribute("scope", "GLOBAL").build(); + } + + public boolean isExplicitGlobal() { + return attributes != null && "GLOBAL".equals(attributes.get("scope")); + } +} diff --git a/src/main/java/com/finance/system/authorization/RoleAuthorizationProfileDto.java b/src/main/java/com/finance/system/authorization/RoleAuthorizationProfileDto.java new file mode 100644 index 0000000..f1aeb0c --- /dev/null +++ b/src/main/java/com/finance/system/authorization/RoleAuthorizationProfileDto.java @@ -0,0 +1,16 @@ +package com.finance.system.authorization; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.Map; + +@Data +@AllArgsConstructor +public class RoleAuthorizationProfileDto { + private Long roleId; + private Long version; + private Long catalogVersion; + private Map permissionAccess; + private RoleAuthorizationSummaryDto derivedSummary; +} diff --git a/src/main/java/com/finance/system/authorization/RoleAuthorizationProfileService.java b/src/main/java/com/finance/system/authorization/RoleAuthorizationProfileService.java new file mode 100644 index 0000000..c7d2113 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/RoleAuthorizationProfileService.java @@ -0,0 +1,206 @@ +package com.finance.system.authorization; + +import com.finance.system.entity.SysRole; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.repository.SysRoleRepository; +import com.finance.system.service.RoleService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class RoleAuthorizationProfileService { + private final SysRoleRepository roles; + private final AuthorizationRoleProfileVersionRepository versions; + private final RoleService roleService; + private final AuthorizationCatalogVersionRepository catalogVersions; + private final AuthorizationPermissionPolicyMapRepository permissionPolicyMappings; + private final AuthorizationRolePolicyRepository rolePolicies; + private final AuthorizationPolicyRepository policies; + private final com.finance.system.repository.SysPermissionRepository permissions; + private final AuthorizationPolicyVersionRepository policyVersions; + + @Transactional(readOnly = true) + public RoleAuthorizationProfileDto get(Long roleId) { + if (!roles.existsById(roleId)) throw new ResourceNotFoundException("角色不存在"); + return snapshot(roleId, versions.findById(roleId).map(AuthorizationRoleProfileVersionEntity::getVersion).orElse(0L), catalogVersion()); + } + + @Transactional + public RoleAuthorizationProfileDto replace(Long roleId, UpdateRoleAuthorizationProfileRequest request, Long actorId) { + if (request == null || request.getExpectedVersion() == null || request.getExpectedVersion() < 0) + throw new BusinessException("expectedVersion无效", 400); + SysRole role = roles.findByIdForUpdate(roleId).orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + AuthorizationRoleProfileVersionEntity version = versions.findByRoleIdForUpdate(roleId).orElse(null); + long currentVersion = version == null ? 0L : version.getVersion(); + if (request.getExpectedVersion() != currentVersion) + throw new BusinessException("权限已被他人更新,请刷新", 409); + long catalogVersion = catalogVersion(); + if (request.getCatalogVersion() == null || request.getCatalogVersion() != catalogVersion) + throw new BusinessException("权限目录已更新,请刷新后重试", 409); + + Map access = new LinkedHashMap<>(); + if (request.getPermissionAccess() == null) throw new BusinessException("permissionAccess不能为空", 400); + request.getPermissionAccess().forEach((code, level) -> { + if (code == null || level == null) throw new BusinessException("permissionAccess包含无效项目", 400); + access.put(code, level.name()); + }); + // The catalog write and canonical derivation join this transaction. No + // client-provided policy identifier or scope ever crosses this boundary. + roleService.replaceRoleProfilePermissions(roleId, access, actorId); + // Derive from the normalized, persisted snapshot so ancestor grants and + // layer normalization cannot drift from the canonical binding update. + replaceDerivedPolicies(roleId, persistedPermissionAccess(roleId)); + if (policyVersions.incrementPolicyVersion() != 1) + throw new BusinessException("授权版本更新失败", 500); + + if (version == null) { + version = new AuthorizationRoleProfileVersionEntity(); + version.setRoleId(role.getId()); + } + version.setVersion(currentVersion + 1); + version.setUpdatedAt(LocalDateTime.now()); + versions.save(version); + return snapshot(roleId, version.getVersion(), catalogVersion); + } + + private void replaceDerivedPolicies(Long roleId, Map access) { + Map catalog = permissions.findAll().stream() + .collect(Collectors.toMap(com.finance.system.entity.SysPermission::getPermissionCode, item -> item)); + Set selectedPermissionIds = new HashSet<>(); + Map levels = new HashMap<>(); + for (Map.Entry entry : access.entrySet()) { + com.finance.system.entity.SysPermission permission = catalog.get(entry.getKey()); + if (permission == null) throw new BusinessException("权限目录已变化,请刷新后重试", 409); + RolePermissionAccess level; + try { level = RolePermissionAccess.valueOf(entry.getValue()); } + catch (RuntimeException ex) { throw new BusinessException("权限档案包含无效项目", 400); } + if (level != RolePermissionAccess.HIDDEN) { + selectedPermissionIds.add(permission.getId()); + levels.put(permission.getId(), level); + } + } + + Set desired = new HashSet<>(); + List mappings = selectedPermissionIds.isEmpty() + ? Collections.emptyList() + : permissionPolicyMappings.findByIdPermissionIdIn(selectedPermissionIds); + for (AuthorizationPermissionPolicyMapEntity mapping : mappings) { + if (mapping == null || mapping.getId() == null || mapping.getId().getPolicyId() == null + || mapping.getId().getPermissionId() == null) continue; + if (mapping.getMappingType() != PermissionPolicyMappingType.BUSINESS) continue; + RolePermissionAccess selected = levels.get(mapping.getId().getPermissionId()); + if (selected != null && grants(selected, mapping.getMinAccessLevel())) desired.add(mapping.getId().getPolicyId()); + } + Map policyById = policies.findAllById(desired).stream() + .collect(Collectors.toMap(AuthorizationPolicyEntity::getId, policy -> policy)); + if (policyById.size() != desired.size()) throw new BusinessException("权限映射引用不存在的内部授权", 500); + // BUSINESS mappings only control policies that are safe to derive. Any + // malformed mapping that points at a safety boundary is ignored here and + // the existing binding is left untouched. + desired.removeIf(policyId -> !isSafelyDerivable(policyById.get(policyId))); + + // DENY bindings are security invariants, never menu-derived grants. + // Promote any legacy/mislabeled row before replacing mutable DERIVED + // ALLOW bindings so a complete profile save cannot remove a deny. + rolePolicies.protectDenyByRoleId(roleId); + // Replace every safely derivable BUSINESS grant, including historical + // LEGACY rows. The permission tree is the sole source of truth for this + // subset; SYSTEM and all security-boundary policies remain untouched. + rolePolicies.deleteReplaceableBusinessMappedByRoleId(roleId); + Set preservedPolicyIds = rolePolicies.findByIdRoleId(roleId).stream() + .map(link -> link.getId().getPolicyId()) + .collect(Collectors.toSet()); + for (Long policyId : desired) { + if (!preservedPolicyIds.contains(policyId)) + rolePolicies.save(new AuthorizationRolePolicyEntity(roleId, policyId, AuthorizationAssignmentSource.DERIVED)); + } + } + + private boolean isSafelyDerivable(AuthorizationPolicyEntity policy) { + return policy != null + && policy.getEffect() == PolicyEffect.ALLOW + && Boolean.TRUE.equals(policy.getDelegable()) + && !Boolean.TRUE.equals(policy.getProtectedPolicy()) + && policy.getRiskLevel() != null + && policy.getRiskLevel() != PolicyRiskLevel.CRITICAL; + } + + private boolean grants(RolePermissionAccess selected, RolePermissionAccess minimum) { + if (selected == null || minimum == null || selected == RolePermissionAccess.HIDDEN) return false; + return minimum == RolePermissionAccess.READ || selected == RolePermissionAccess.EDIT; + } + + private Map persistedPermissionAccess(Long roleId) { + Map persisted = stringMap(roleService.rolePermissions(roleId).get("permissionAccess")); + if (persisted.isEmpty() && !permissions.findAll().isEmpty()) + throw new BusinessException("权限档案持久化失败", 500); + return persisted; + } + + private Map stringMap(Object raw) { + if (!(raw instanceof Map)) return Collections.emptyMap(); + Map result = new LinkedHashMap<>(); + ((Map) raw).forEach((key, value) -> { + if (key instanceof String && value instanceof String) result.put((String) key, (String) value); + }); + return result; + } + + private RoleAuthorizationProfileDto snapshot(Long roleId, Long version, long catalogVersion) { + Map legacy = roleService.rolePermissions(roleId); + Map access = new LinkedHashMap<>(); + Object raw = legacy.get("permissionAccess"); + if (raw instanceof Map) { + ((Map) raw).forEach((code, level) -> { + if (code instanceof String && level instanceof String) + access.put((String) code, RolePermissionAccess.valueOf((String) level)); + }); + } + return new RoleAuthorizationProfileDto(roleId, version, catalogVersion, access, summary(roleId)); + } + + private RoleAuthorizationSummaryDto summary(Long roleId) { + List links = rolePolicies.findByIdRoleId(roleId); + Map sources = new EnumMap<>(AuthorizationAssignmentSource.class); + Set ids = new HashSet<>(); + for (AuthorizationRolePolicyEntity link : links) { + AuthorizationAssignmentSource source = link.getAssignmentSource() == null + ? AuthorizationAssignmentSource.LEGACY : link.getAssignmentSource(); + sources.put(source, sources.getOrDefault(source, 0L) + 1L); + ids.add(link.getId().getPolicyId()); + } + Map risks = new LinkedHashMap<>(); + Map scopes = new LinkedHashMap<>(); + for (AuthorizationPolicyEntity policy : policies.findAllById(ids)) { + String risk = policy.getRiskLevel() == null ? "UNKNOWN" : policy.getRiskLevel().name(); + String scope = policy.getDataScope() == null ? "UNKNOWN" : policy.getDataScope().name(); + risks.put(risk, risks.getOrDefault(risk, 0L) + 1L); + scopes.put(scope, scopes.getOrDefault(scope, 0L) + 1L); + } + return new RoleAuthorizationSummaryDto(sources.getOrDefault(AuthorizationAssignmentSource.DERIVED, 0L), + sources.getOrDefault(AuthorizationAssignmentSource.SYSTEM, 0L), + sources.getOrDefault(AuthorizationAssignmentSource.LEGACY, 0L), risks, scopes); + } + + private long catalogVersion() { + AuthorizationCatalogVersionEntity version = catalogVersions.findById(1) + .orElseThrow(() -> new BusinessException("权限目录版本不存在", 500)); + if (version.getVersion() == null || version.getVersion() < 1) + throw new BusinessException("权限目录版本无效", 500); + return version.getVersion(); + } +} diff --git a/src/main/java/com/finance/system/authorization/RoleAuthorizationSummaryDto.java b/src/main/java/com/finance/system/authorization/RoleAuthorizationSummaryDto.java new file mode 100644 index 0000000..3d62eb8 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/RoleAuthorizationSummaryDto.java @@ -0,0 +1,17 @@ +package com.finance.system.authorization; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.Map; + +/** Aggregate-only summary: deliberately contains no policy identifier or policy code. */ +@Data +@AllArgsConstructor +public class RoleAuthorizationSummaryDto { + private long derivedCount; + private long systemCount; + private long legacyCount; + private Map riskLevels; + private Map scopes; +} diff --git a/src/main/java/com/finance/system/authorization/RolePermissionAccess.java b/src/main/java/com/finance/system/authorization/RolePermissionAccess.java new file mode 100644 index 0000000..ba40d96 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/RolePermissionAccess.java @@ -0,0 +1,5 @@ +package com.finance.system.authorization; + +public enum RolePermissionAccess { + HIDDEN, READ, EDIT +} diff --git a/src/main/java/com/finance/system/authorization/SegregationOfDutiesEvaluator.java b/src/main/java/com/finance/system/authorization/SegregationOfDutiesEvaluator.java new file mode 100644 index 0000000..e019c55 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/SegregationOfDutiesEvaluator.java @@ -0,0 +1,32 @@ +package com.finance.system.authorization; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.util.Locale; + +/** Domain services call this hook before approval/payment duties are committed. */ +@Component +@RequiredArgsConstructor +public class SegregationOfDutiesEvaluator { + private final AuthorizationSodRuleRepository rules; + + public void check(Long actorId, Long relatedActorId, String leftDuty, String rightDuty) { + if (actorId == null || relatedActorId == null || !actorId.equals(relatedActorId)) return; + LocalDateTime now = LocalDateTime.now(); + for (AuthorizationSodRuleEntity rule : rules.findByEnabledTrue()) { + if ((rule.getValidFrom() != null && rule.getValidFrom().isAfter(now)) + || (rule.getValidUntil() != null && !rule.getValidUntil().isAfter(now))) continue; + if (same(rule.getLeftDuty(), leftDuty) && same(rule.getRightDuty(), rightDuty)) { + throw new AccessDeniedException("职责分离规则禁止同一主体执行该操作"); + } + } + } + + private boolean same(String left, String right) { + return left != null && right != null && left.trim().toUpperCase(Locale.ROOT) + .equals(right.trim().toUpperCase(Locale.ROOT)); + } +} diff --git a/src/main/java/com/finance/system/authorization/SubjectContext.java b/src/main/java/com/finance/system/authorization/SubjectContext.java new file mode 100644 index 0000000..13c91f9 --- /dev/null +++ b/src/main/java/com/finance/system/authorization/SubjectContext.java @@ -0,0 +1,26 @@ +package com.finance.system.authorization; + +import lombok.Builder; +import lombok.Singular; +import lombok.Value; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +@Value +@Builder +public class SubjectContext { + Long userId; + String tenantId; + Long organizationId; + Long departmentId; + @Singular Set departmentTreeIds; + @Singular Set groupIds; + @Singular Set roleIds; + @Singular("attribute") Map attributes; + + public Set safeDepartmentTreeIds() { + return departmentTreeIds == null ? Collections.emptySet() : departmentTreeIds; + } +} diff --git a/src/main/java/com/finance/system/authorization/UpdateRoleAuthorizationProfileRequest.java b/src/main/java/com/finance/system/authorization/UpdateRoleAuthorizationProfileRequest.java new file mode 100644 index 0000000..85b182a --- /dev/null +++ b/src/main/java/com/finance/system/authorization/UpdateRoleAuthorizationProfileRequest.java @@ -0,0 +1,23 @@ +package com.finance.system.authorization; + +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.finance.system.exception.BadRequestException; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.util.Map; + +@Data +public class UpdateRoleAuthorizationProfileRequest { + @NotNull + private Long expectedVersion; + @NotNull + private Long catalogVersion; + @NotNull + private Map permissionAccess; + + @JsonAnySetter + public void rejectUnsupportedField(String name, Object ignored) { + throw new BadRequestException("授权档案请求包含不支持字段: " + name); + } +} diff --git a/src/main/java/com/finance/system/config/AsyncConfig.java b/src/main/java/com/finance/system/config/AsyncConfig.java index 971a425..f52b36a 100644 --- a/src/main/java/com/finance/system/config/AsyncConfig.java +++ b/src/main/java/com/finance/system/config/AsyncConfig.java @@ -1,5 +1,7 @@ package com.finance.system.config; +import com.finance.system.observability.MdcTaskDecorator; +import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; @@ -10,8 +12,11 @@ import java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync +@RequiredArgsConstructor public class AsyncConfig { + private final MdcTaskDecorator mdcTaskDecorator; + @Bean(name = "apiAccessLogExecutor") public Executor apiAccessLogExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); @@ -19,7 +24,10 @@ public class AsyncConfig { executor.setMaxPoolSize(4); executor.setQueueCapacity(2000); executor.setThreadNamePrefix("api-access-log-"); - executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); + executor.setTaskDecorator(mdcTaskDecorator); + // Never discard an access record without a signal. Under exceptional + // pressure the caller performs the write, applying natural backpressure. + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } diff --git a/src/main/java/com/finance/system/config/FrontendOriginPolicy.java b/src/main/java/com/finance/system/config/FrontendOriginPolicy.java new file mode 100644 index 0000000..55ac2a1 --- /dev/null +++ b/src/main/java/com/finance/system/config/FrontendOriginPolicy.java @@ -0,0 +1,114 @@ +package com.finance.system.config; + +import com.finance.system.exception.BusinessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** Exact trusted frontend origins used by CORS and OAuth redirects. */ +@Component +public class FrontendOriginPolicy { + private final String defaultOrigin; + private final List allowedOrigins; + + public FrontendOriginPolicy( + @Value("${app.frontend-url:}") String configuredDefault, + @Value("${app.frontend-allowed-origins:}") String configuredAllowed) { + Set origins = new LinkedHashSet<>(); + if (StringUtils.hasText(configuredAllowed)) { + for (String value : configuredAllowed.split(",")) { + if (StringUtils.hasText(value)) origins.add(parseConfigured(value)); + } + } + if (StringUtils.hasText(configuredDefault)) { + this.defaultOrigin = parseConfigured(configuredDefault); + origins.add(this.defaultOrigin); + } else if (!origins.isEmpty()) { + this.defaultOrigin = origins.iterator().next(); + } else { + throw new IllegalStateException("At least one exact frontend origin must be configured"); + } + this.allowedOrigins = Collections.unmodifiableList(new ArrayList<>(origins)); + } + + public String getDefaultOrigin() { + return defaultOrigin; + } + + public List getAllowedOrigins() { + return allowedOrigins; + } + + /** Missing origin retains the legacy default; an untrusted supplied origin fails closed. */ + public String resolveRequestedOrigin(String requestedOrigin) { + if (!StringUtils.hasText(requestedOrigin)) return defaultOrigin; + final String normalized; + try { + normalized = normalize(requestedOrigin); + } catch (RuntimeException invalid) { + throw new BusinessException("前端来源不受信任", 400); + } + if (!allowedOrigins.contains(normalized)) { + throw new BusinessException("前端来源不受信任", 400); + } + return normalized; + } + + private String parseConfigured(String value) { + try { + return normalize(value); + } catch (RuntimeException invalid) { + throw new IllegalStateException("Frontend origins must be exact HTTP(S) origins", invalid); + } + } + + private String normalize(String value) { + String candidate = value == null ? "" : value.trim(); + if (candidate.isEmpty() || candidate.indexOf('*') >= 0 || hasControlCharacter(candidate)) { + throw new IllegalArgumentException("Invalid origin"); + } + URI uri = URI.create(candidate); + String scheme = uri.getScheme(); + String host = uri.getHost(); + int port = uri.getPort(); + if (scheme == null || host == null || port == 0 || port > 65535 + || !("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) + || uri.getUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null + || (uri.getRawPath() != null && !uri.getRawPath().isEmpty()) + || (uri.getRawAuthority() != null && uri.getRawAuthority().endsWith(":"))) { + throw new IllegalArgumentException("Invalid origin"); + } + String normalizedScheme = scheme.toLowerCase(Locale.ROOT); + String normalizedHost = host.toLowerCase(Locale.ROOT); + if (normalizedHost.startsWith("[") && normalizedHost.endsWith("]")) { + normalizedHost = normalizedHost.substring(1, normalizedHost.length() - 1); + } + // A terminal DNS root dot is deliberately rejected instead of being + // silently equated with the non-dotted host in an origin allowlist. + if (normalizedHost.endsWith(".")) { + throw new IllegalArgumentException("Invalid origin"); + } + if (normalizedHost.indexOf(':') >= 0 && !normalizedHost.startsWith("[")) { + normalizedHost = "[" + normalizedHost + "]"; + } + boolean defaultPort = port < 0 + || ("http".equals(normalizedScheme) && port == 80) + || ("https".equals(normalizedScheme) && port == 443); + return normalizedScheme + "://" + normalizedHost + (defaultPort ? "" : ":" + port); + } + + private boolean hasControlCharacter(String value) { + for (int i = 0; i < value.length(); i++) { + if (Character.isISOControl(value.charAt(i))) return true; + } + return false; + } +} diff --git a/src/main/java/com/finance/system/config/LocalDataInitializer.java b/src/main/java/com/finance/system/config/LocalDataInitializer.java index e5fb53c..be1111e 100644 --- a/src/main/java/com/finance/system/config/LocalDataInitializer.java +++ b/src/main/java/com/finance/system/config/LocalDataInitializer.java @@ -4,6 +4,7 @@ import com.finance.system.entity.SysApprovalNode; import com.finance.system.entity.SysBankAccount; import com.finance.system.entity.SysDepartment; import com.finance.system.entity.SysExpenseType; +import com.finance.system.entity.SysPayee; import com.finance.system.entity.SysRole; import com.finance.system.entity.SysUser; import com.finance.system.entity.SysUserGroup; @@ -13,11 +14,13 @@ import com.finance.system.repository.SysApprovalNodeRepository; import com.finance.system.repository.SysBankAccountRepository; import com.finance.system.repository.SysDepartmentRepository; import com.finance.system.repository.SysExpenseTypeRepository; +import com.finance.system.repository.SysPayeeRepository; import com.finance.system.repository.SysRoleRepository; import com.finance.system.repository.SysUserRepository; import com.finance.system.repository.SysUserGroupMemberRepository; import com.finance.system.repository.SysUserGroupRepository; import com.finance.system.repository.SysUserGroupRoleRepository; +import com.finance.system.security.finance.BankAccountProtection; import org.springframework.boot.CommandLineRunner; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; @@ -38,33 +41,39 @@ public class LocalDataInitializer implements CommandLineRunner { private final SysDepartmentRepository departments; private final SysExpenseTypeRepository expenseTypes; private final SysBankAccountRepository bankAccounts; + private final SysPayeeRepository payees; private final SysApprovalNodeRepository nodes; private final SysRoleRepository roles; private final SysUserGroupRepository groups; private final SysUserGroupMemberRepository members; private final SysUserGroupRoleRepository groupRoles; private final PasswordEncoder passwordEncoder; + private final BankAccountProtection bankAccountProtection; private final boolean superAdminBootstrapEnabled; private final String superAdminBootstrapPassword; public LocalDataInitializer(SysUserRepository users, SysDepartmentRepository departments, SysExpenseTypeRepository expenseTypes, SysBankAccountRepository bankAccounts, + SysPayeeRepository payees, SysApprovalNodeRepository nodes, SysRoleRepository roles, SysUserGroupRepository groups, SysUserGroupMemberRepository members, SysUserGroupRoleRepository groupRoles, PasswordEncoder passwordEncoder, + BankAccountProtection bankAccountProtection, @Value("${finance.local-bootstrap.super-admin.enabled:false}") boolean superAdminBootstrapEnabled, @Value("${finance.local-bootstrap.super-admin.password:}") String superAdminBootstrapPassword) { this.users = users; this.departments = departments; this.expenseTypes = expenseTypes; this.bankAccounts = bankAccounts; + this.payees = payees; this.nodes = nodes; this.roles = roles; this.groups = groups; this.members = members; this.groupRoles = groupRoles; this.passwordEncoder = passwordEncoder; + this.bankAccountProtection = bankAccountProtection; this.superAdminBootstrapEnabled = superAdminBootstrapEnabled; this.superAdminBootstrapPassword = superAdminBootstrapPassword; } @@ -104,11 +113,21 @@ public class LocalDataInitializer implements CommandLineRunner { SysBankAccount bank = new SysBankAccount(); bank.setUserId(employee.getId()); + SysPayee payee = SysPayee.builder().tenantId(employee.getTenantId()) + .organizationId(employee.getOrganizationId()).payeeType("EMPLOYEE") + .displayName(employee.getRealName()).employeeUserId(employee.getId()) + .employeeOpenId(employee.getFeishuOpenId()).status("ACTIVE").build(); + payee = payees.save(payee); + bank.setPayeeId(payee.getId()); bank.setBankName("本地测试银行"); bank.setBranchName("测试支行"); - bank.setAccountNo("6222000000001001"); - bank.setAccountNoMask("************1001"); - bank.setAccountName(employee.getRealName()); + BankAccountProtection.ProtectedValue protectedValue = + bankAccountProtection.protect("6222000000001001"); + bank.setAccountNo(null); + bank.setAccountNoCiphertext(protectedValue.getCiphertext()); + bank.setAccountFingerprint(protectedValue.getFingerprint()); + bank.setAccountNoMask(protectedValue.getMask()); + bank.setEncryptionKeyVersion(protectedValue.getKeyVersion()); bank.setIsDefault(true); bank.setStatus("ACTIVE"); bankAccounts.save(bank); diff --git a/src/main/java/com/finance/system/config/SecurityConfig.java b/src/main/java/com/finance/system/config/SecurityConfig.java index 124fbe1..6e4fdef 100644 --- a/src/main/java/com/finance/system/config/SecurityConfig.java +++ b/src/main/java/com/finance/system/config/SecurityConfig.java @@ -2,6 +2,7 @@ package com.finance.system.config; import com.finance.system.security.ApiAccessLogFilter; import com.finance.system.security.JwtAuthenticationFilter; +import com.finance.system.observability.RequestContextFilter; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -27,6 +28,7 @@ public class SecurityConfig { private final JwtAuthenticationFilter jwtAuthenticationFilter; private final ApiAccessLogFilter apiAccessLogFilter; + private final RequestContextFilter requestContextFilter; private final Environment environment; @Bean @@ -45,7 +47,7 @@ public class SecurityConfig { // OAuth initiation/callback and the signed Feishu event receiver are the // only Feishu endpoints intentionally reachable without a local session. .antMatchers("/api/feishu/auth-url", "/api/feishu/callback", "/api/feishu/webhook").permitAll() - .antMatchers("/actuator/health").permitAll() + .antMatchers("/actuator/health", "/actuator/health/**").permitAll() .anyRequest().authenticated(); }) .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint( @@ -58,6 +60,7 @@ public class SecurityConfig { } )) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + .addFilterBefore(requestContextFilter, JwtAuthenticationFilter.class) .addFilterAfter(apiAccessLogFilter, UsernamePasswordAuthenticationFilter.class) .headers(headers -> headers .frameOptions(frame -> frame.sameOrigin()) @@ -89,4 +92,21 @@ public class SecurityConfig { registration.setEnabled(false); return registration; } + + /** Keep JWT authentication only inside the security chain to prevent double execution. */ + @Bean + public FilterRegistrationBean disableJwtAuthenticationFilterRegistration( + JwtAuthenticationFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + /** Keep request context in the security chain so ordering and cleanup are deterministic. */ + @Bean + public FilterRegistrationBean disableRequestContextFilterRegistration(RequestContextFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } } diff --git a/src/main/java/com/finance/system/config/WebConfig.java b/src/main/java/com/finance/system/config/WebConfig.java index d18eb4d..99309c3 100644 --- a/src/main/java/com/finance/system/config/WebConfig.java +++ b/src/main/java/com/finance/system/config/WebConfig.java @@ -1,8 +1,8 @@ package com.finance.system.config; +import com.finance.system.observability.OutboundTraceInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.beans.factory.annotation.Value; import org.springframework.web.client.RestTemplate; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.cors.CorsConfiguration; @@ -11,27 +11,25 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Arrays; -import java.util.Collections; @Configuration public class WebConfig implements WebMvcConfigurer { - @Value("${app.frontend-url:}") - private String frontendUrl; + private final FrontendOriginPolicy frontendOrigins; + + public WebConfig(FrontendOriginPolicy frontendOrigins) { + this.frontendOrigins = frontendOrigins; + } @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); - if (frontendUrl != null && !frontendUrl.trim().isEmpty()) { - config.setAllowedOrigins(Collections.singletonList(frontendUrl.trim())); - } else { - // An empty origin configuration disables cross-origin requests; - // never weaken this to a wildcard when credentials are enabled. - config.setAllowedOrigins(Collections.emptyList()); - } + config.setAllowedOrigins(frontendOrigins.getAllowedOrigins()); config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); config.setAllowedHeaders(Arrays.asList( - "Authorization", "Content-Type", "Idempotency-Key", "X-Request-Id")); + "Authorization", "Content-Type", "Idempotency-Key", "X-Request-Id", + "traceparent", "tracestate", "baggage")); + config.setExposedHeaders(Arrays.asList("X-Request-Id", "traceparent")); config.setAllowCredentials(true); config.setMaxAge(3600L); @@ -41,10 +39,12 @@ public class WebConfig implements WebMvcConfigurer { } @Bean - public RestTemplate restTemplate() { + public RestTemplate restTemplate(OutboundTraceInterceptor outboundTraceInterceptor) { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(5000); factory.setReadTimeout(10000); - return new RestTemplate(factory); + RestTemplate restTemplate = new RestTemplate(factory); + restTemplate.getInterceptors().add(outboundTraceInterceptor); + return restTemplate; } } diff --git a/src/main/java/com/finance/system/controller/AccountsPayableController.java b/src/main/java/com/finance/system/controller/AccountsPayableController.java index 3d6190e..cdb834c 100644 --- a/src/main/java/com/finance/system/controller/AccountsPayableController.java +++ b/src/main/java/com/finance/system/controller/AccountsPayableController.java @@ -29,7 +29,8 @@ public class AccountsPayableController { @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { Pageable pageable = PageRequest.of(page, size); - Page tasks = reimApplicationService.getAccountsPayableTasks(status, pageable); + Page tasks = reimApplicationService.getAccountsPayableTasks( + AuditUtil.getCurrentUserId(), status, pageable); return ResponseEntity.ok(ApiResponse.success(PageResponse.of( tasks.getContent(), tasks.getTotalElements(), page, size))); } @@ -58,6 +59,15 @@ public class AccountsPayableController { return ResponseEntity.ok(ApiResponse.success()); } + @PostMapping("/transfer") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.approval.decide')") + public ResponseEntity> transfer( + @javax.validation.Valid @RequestBody TransferApprovalRequest request) { + Long userId = AuditUtil.getCurrentUserId(); + return ResponseEntity.ok(ApiResponse.success(reimApprovalService.transfer( + request.getApplicationId(), userId, request.getTargetApproverId(), request.getComment()))); + } + @GetMapping("/history") @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") public ResponseEntity>> getHistory() { diff --git a/src/main/java/com/finance/system/controller/ApplicationController.java b/src/main/java/com/finance/system/controller/ApplicationController.java deleted file mode 100644 index 5fd5a00..0000000 --- a/src/main/java/com/finance/system/controller/ApplicationController.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.finance.system.controller; - -import com.finance.system.dto.ApiResponse; -import com.finance.system.security.UserPrincipal; -import com.finance.system.util.AuditUtil; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import java.math.BigDecimal; -import java.util.*; - -@Slf4j -@RestController -@RequestMapping("/api/applications") -@RequiredArgsConstructor -public class ApplicationController { - - /** - * Mock数据 - 付款申请列表 - * 对应原型中的员工报销数据(员工报销类) - */ - private static final List> MOCK_APPLICATIONS = new ArrayList<>(); - - static { - Map a1 = new LinkedHashMap<>(); - a1.put("id", 1L); - a1.put("applicationNo", "BX20260812001"); - a1.put("date", "2026-08-12"); - a1.put("title", "上海客户现场技术交流差旅"); - a1.put("type", "费用报销"); - a1.put("subtype", "差旅交通"); - a1.put("payee", "李志豪"); - a1.put("amount", new BigDecimal("3286.50")); - a1.put("owner", "李志豪"); - a1.put("department", "销售中心"); - a1.put("applicationStatus", "退回"); - a1.put("receiptStatus", "未触发"); - a1.put("paymentStatus", "未付款"); - a1.put("budgetStatus", "已占用"); - a1.put("approvalNode", "申请人补充材料"); - a1.put("approver", "李志豪"); - a1.put("expenseType", "员工报销类"); - MOCK_APPLICATIONS.add(a1); - - Map a2 = new LinkedHashMap<>(); - a2.put("id", 2L); - a2.put("applicationNo", "BX20260809003"); - a2.put("date", "2026-08-09"); - a2.put("title", "八月客户拜访交通费"); - a2.put("type", "费用报销"); - a2.put("subtype", "交通费"); - a2.put("payee", "李志豪"); - a2.put("amount", new BigDecimal("1260.00")); - a2.put("owner", "李志豪"); - a2.put("department", "销售中心"); - a2.put("applicationStatus", "审批中"); - a2.put("receiptStatus", "未触发"); - a2.put("paymentStatus", "未付款"); - a2.put("budgetStatus", "已占用"); - a2.put("approvalNode", "应付会计审核"); - a2.put("approver", "刘雅"); - a2.put("expenseType", "员工报销类"); - MOCK_APPLICATIONS.add(a2); - - Map a3 = new LinkedHashMap<>(); - a3.put("id", 3L); - a3.put("applicationNo", "BX20260808006"); - a3.put("date", "2026-08-08"); - a3.put("title", "研发现场餐费报销"); - a3.put("type", "费用报销"); - a3.put("subtype", "业务招待"); - a3.put("payee", "王忠辉"); - a3.put("amount", new BigDecimal("680.00")); - a3.put("owner", "王忠辉"); - a3.put("department", "数字化中心"); - a3.put("applicationStatus", "审批中"); - a3.put("receiptStatus", "未触发"); - a3.put("paymentStatus", "未付款"); - a3.put("budgetStatus", "已占用"); - a3.put("approvalNode", "财务经理审批"); - a3.put("approver", "周岚"); - a3.put("expenseType", "员工报销类"); - MOCK_APPLICATIONS.add(a3); - - Map a4 = new LinkedHashMap<>(); - a4.put("id", 4L); - a4.put("applicationNo", "BX20260802011"); - a4.put("date", "2026-08-02"); - a4.put("title", "苏州园区客户拜访费用"); - a4.put("type", "费用报销"); - a4.put("subtype", "交通费"); - a4.put("payee", "赵海峰"); - a4.put("amount", new BigDecimal("2180.00")); - a4.put("owner", "赵海峰"); - a4.put("department", "供应链中心"); - a4.put("applicationStatus", "审批通过"); - a4.put("receiptStatus", "待收单"); - a4.put("paymentStatus", "未付款"); - a4.put("budgetStatus", "已转执行"); - a4.put("approvalNode", "流程已完成"); - a4.put("approver", "—"); - a4.put("expenseType", "员工报销类"); - MOCK_APPLICATIONS.add(a4); - - Map a5 = new LinkedHashMap<>(); - a5.put("id", 5L); - a5.put("applicationNo", "BX20260801009"); - a5.put("date", "2026-08-01"); - a5.put("title", "七月云资源差旅补贴"); - a5.put("type", "费用报销"); - a5.put("subtype", "差旅补贴"); - a5.put("payee", "王忠辉"); - a5.put("amount", new BigDecimal("3200.00")); - a5.put("owner", "王忠辉"); - a5.put("department", "数字化中心"); - a5.put("applicationStatus", "审批通过"); - a5.put("receiptStatus", "已收单"); - a5.put("paymentStatus", "未付款"); - a5.put("budgetStatus", "已转执行"); - a5.put("approvalNode", "流程已完成"); - a5.put("approver", "—"); - a5.put("expenseType", "员工报销类"); - MOCK_APPLICATIONS.add(a5); - - Map a6 = new LinkedHashMap<>(); - a6.put("id", 6L); - a6.put("applicationNo", "BX20260728004"); - a6.put("date", "2026-07-28"); - a6.put("title", "上海项目住宿费"); - a6.put("type", "费用报销"); - a6.put("subtype", "住宿费"); - a6.put("payee", "赵海峰"); - a6.put("amount", new BigDecimal("4100.00")); - a6.put("owner", "赵海峰"); - a6.put("department", "供应链中心"); - a6.put("applicationStatus", "审批通过"); - a6.put("receiptStatus", "已收单"); - a6.put("paymentStatus", "部分付款"); - a6.put("budgetStatus", "已转执行"); - a6.put("approvalNode", "流程已完成"); - a6.put("approver", "—"); - a6.put("expenseType", "员工报销类"); - MOCK_APPLICATIONS.add(a6); - } - - /** - * 获取付款申请列表(应付会计B视图,过滤 expenseType=员工报销类) - */ - @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") - public ResponseEntity>>> listApplications( - @RequestParam(required = false) String status, - @RequestParam(required = false) String expenseType) { - try { - List> result = new ArrayList<>(MOCK_APPLICATIONS); - - // 默认过滤 expenseType=员工报销类 - if (expenseType != null && !expenseType.isEmpty()) { - result.removeIf(app -> !expenseType.equals(app.get("expenseType"))); - } else { - result.removeIf(app -> !"员工报销类".equals(app.get("expenseType"))); - } - - // 按状态过滤 - if (status != null && !status.isEmpty()) { - result.removeIf(app -> !status.equals(app.get("applicationStatus"))); - } - - return ResponseEntity.ok(ApiResponse.success(result)); - } catch (Exception e) { - log.error("获取付款申请列表失败", e); - return ResponseEntity.ok(ApiResponse.error(500, "获取付款申请列表失败: " + e.getMessage())); - } - } - - /** - * 获取付款申请详情 - */ - @GetMapping("/{id}") - @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") - public ResponseEntity>> getApplicationDetail(@PathVariable Long id) { - try { - Map application = MOCK_APPLICATIONS.stream() - .filter(a -> id.equals(a.get("id"))) - .findFirst() - .orElse(null); - - if (application == null) { - return ResponseEntity.status(404) - .body(ApiResponse.error(404, "申请单不存在: " + id)); - } - - // 追加详细信息 - Map detail = new LinkedHashMap<>(application); - detail.put("bankName", "中国工商银行苏州新区支行"); - detail.put("bankAccount", "6222 **** 0086 0728"); - detail.put("description", getDescriptionById(id)); - detail.put("invoices", getInvoicesById(id)); - detail.put("attachments", getAttachmentsById(id)); - detail.put("returnReason", getReturnReasonById(id)); - detail.put("lastUpdated", "2026-08-12 10:24"); - - return ResponseEntity.ok(ApiResponse.success(detail)); - } catch (Exception e) { - log.error("获取申请详情失败: id={}", id, e); - return ResponseEntity.ok(ApiResponse.error(500, "获取申请详情失败: " + e.getMessage())); - } - } - - private String getDescriptionById(Long id) { - if (id == 1L) return "上海客户现场技术交流产生的交通及住宿费用。"; - if (id == 2L) return "客户拜访交通费用。"; - if (id == 3L) return "研发现场支持期间的工作餐费用。"; - if (id == 4L) return "园区客户拜访交通与停车费用。"; - if (id == 5L) return "七月现场支持差旅补贴。"; - if (id == 6L) return "上海项目住宿费用。"; - return ""; - } - - private List> getInvoicesById(Long id) { - List> invoices = new ArrayList<>(); - if (id == 2L) { - Map inv = new LinkedHashMap<>(); - inv.put("number", "03300260011142888901"); - inv.put("amount", new BigDecimal("1260.00")); - inv.put("file", "出租车发票_08月.pdf"); - invoices.add(inv); - } - if (id == 4L) { - Map inv = new LinkedHashMap<>(); - inv.put("number", "03300260011142887771"); - inv.put("amount", new BigDecimal("2180.00")); - inv.put("file", "停车及交通发票.pdf"); - invoices.add(inv); - } - if (id == 6L) { - Map inv = new LinkedHashMap<>(); - inv.put("number", "03300260011142885550"); - inv.put("amount", new BigDecimal("4100.00")); - inv.put("file", "住宿发票.pdf"); - invoices.add(inv); - } - return invoices; - } - - private List> getAttachmentsById(Long id) { - List> attachments = new ArrayList<>(); - if (id == 1L) { - Map att1 = new LinkedHashMap<>(); - att1.put("type", "出差申请"); - att1.put("name", "出差申请_上海客户现场.pdf"); - attachments.add(att1); - Map att2 = new LinkedHashMap<>(); - att2.put("type", "行程证明"); - att2.put("name", "高铁行程单.pdf"); - attachments.add(att2); - } - return attachments; - } - - private String getReturnReasonById(Long id) { - if (id == 1L) return "请补充住宿发票影像,并说明住宿日期。"; - return null; - } -} diff --git a/src/main/java/com/finance/system/controller/AuditEventQueryController.java b/src/main/java/com/finance/system/controller/AuditEventQueryController.java new file mode 100644 index 0000000..b0025e6 --- /dev/null +++ b/src/main/java/com/finance/system/controller/AuditEventQueryController.java @@ -0,0 +1,41 @@ +package com.finance.system.controller; + +import com.finance.system.audit.query.AuditEventView; +import com.finance.system.audit.query.AuditQueryAuthorization; +import com.finance.system.audit.query.AuditQueryService; +import com.finance.system.audit.query.CursorPage; +import com.finance.system.dto.ApiResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; + +@RestController +@RequestMapping("/api/audit/events") +@RequiredArgsConstructor +@PreAuthorize("isAuthenticated()") +public class AuditEventQueryController { + private final AuditQueryAuthorization authorization; + private final AuditQueryService service; + + @GetMapping("/{category}") + public ApiResponse> search(@PathVariable String category, + @RequestParam(required = false) String action, + @RequestParam(required = false) String outcome, + @RequestParam(required = false) Long actorId, + @RequestParam(required = false) String resourceType, + @RequestParam(required = false) String resourceId, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + LocalDateTime cursorTime, + @RequestParam(required = false) Long cursorId, + @RequestParam(required = false) Integer limit) { + return ApiResponse.success(service.search(authorization.authorize(category), category, action, + outcome, actorId, resourceType, resourceId, cursorTime, cursorId, limit)); + } +} diff --git a/src/main/java/com/finance/system/controller/AuthController.java b/src/main/java/com/finance/system/controller/AuthController.java index b4b5ba2..e768318 100644 --- a/src/main/java/com/finance/system/controller/AuthController.java +++ b/src/main/java/com/finance/system/controller/AuthController.java @@ -135,6 +135,7 @@ public class AuthController { } @GetMapping("/me") + @PreAuthorize("isAuthenticated()") public ResponseEntity> getCurrentUser() { UserPrincipal principal = AuditUtil.getCurrentUser(); if (principal == null) { @@ -151,6 +152,7 @@ public class AuthController { } @PostMapping("/refresh") + @PreAuthorize("isAuthenticated()") public ResponseEntity> refreshToken() { UserPrincipal principal = AuditUtil.getCurrentUser(); if (principal == null) { @@ -179,6 +181,7 @@ public class AuthController { } @PostMapping("/logout") + @PreAuthorize("isAuthenticated()") public ResponseEntity> logout() { return ResponseEntity.ok(ApiResponse.success()); } @@ -187,7 +190,7 @@ public class AuthController { * 获取所有用户列表 */ @GetMapping("/users") - @PreAuthorize("@permissionChecker.has(authentication, 'page.users')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.user', 'read')") public ResponseEntity>> listUsers() { List users = sysUserRepository.findAll(); List profiles = users.stream() @@ -200,7 +203,7 @@ public class AuthController { * 更新用户角色 */ @PutMapping("/users/{id}/role") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.user.legacy-role.change')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')") public ResponseEntity> updateUserRole( @PathVariable Long id, @RequestBody Map request) { @@ -212,7 +215,7 @@ public class AuthController { * 切换用户状态 */ @PutMapping("/users/{id}/status") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.user.status.change')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.user.status', 'manage')") public ResponseEntity> toggleUserStatus( @PathVariable Long id, @RequestBody Map request) { @@ -245,7 +248,7 @@ public class AuthController { /** Retired: roles are assigned only through the user-group API. */ @PutMapping("/users/{id}/roles") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.user.role.assign')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')") public ResponseEntity> updateUserRoles(@PathVariable Long id, @RequestBody Map request) { return ResponseEntity.status(410) @@ -265,6 +268,8 @@ public class AuthController { .id(user.getId()) .employeeNo(user.getEmployeeNo()) .realName(user.getRealName()) + .feishuOpenId(java.util.Objects.equals(user.getId(), AuditUtil.getCurrentUserId()) + ? user.getFeishuOpenId() : null) .avatarUrl(user.getAvatarUrl()) .email(user.getEmail()) .departmentName(deptName) diff --git a/src/main/java/com/finance/system/controller/BusinessConfigController.java b/src/main/java/com/finance/system/controller/BusinessConfigController.java new file mode 100644 index 0000000..76084e7 --- /dev/null +++ b/src/main/java/com/finance/system/controller/BusinessConfigController.java @@ -0,0 +1,88 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.service.PrototypeBusinessConfigService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/business-config") +@RequiredArgsConstructor +public class BusinessConfigController { + private final PrototypeBusinessConfigService service; + + @GetMapping("/references") + @PreAuthorize("@permissionChecker.has(authentication, 'page.cost-centers') or @permissionChecker.has(authentication, 'page.payment-accounts') or @permissionChecker.has(authentication, 'page.budgets')") + public ResponseEntity>> references(Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.references(authentication))); + } + + @GetMapping("/budgets/overview") + @PreAuthorize("@permissionChecker.has(authentication, 'page.budgets')") + public ResponseEntity>> budgetOverview(Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.budgetOverview(authentication))); + } + + @PostMapping("/budget-subjects") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'ui.budgets.subject-create')") + public ResponseEntity>> createBudgetSubject( + @RequestBody Map body, + Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.createBudgetSubject(body, authentication))); + } + + @PatchMapping("/budget-subjects/{id}/status") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'ui.budgets.subject-status')") + public ResponseEntity>> changeBudgetSubjectStatus( + @PathVariable Long id, + @RequestBody Map body) { + return ResponseEntity.ok(ApiResponse.success(service.changeBudgetSubjectStatus(id, body))); + } + + @PostMapping("/budget-adjustments") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'ui.budgets.adjust')") + public ResponseEntity>> requestBudgetAdjustment( + @RequestBody Map body, + Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.requestBudgetAdjustment(body, authentication))); + } + + @GetMapping("/{resource}") + @PreAuthorize("@permissionChecker.has(authentication, 'page.' + #resource)") + public ResponseEntity>>> list( + @PathVariable String resource, + Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.list(resource, authentication))); + } + + @PostMapping("/{resource}") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'ui.' + #resource + '.create')") + public ResponseEntity>> create( + @PathVariable String resource, + @RequestBody Map body, + Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.create(resource, body, authentication))); + } + + @PatchMapping("/{resource}/{id}/status") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'ui.' + #resource + '.deactivate')") + public ResponseEntity>> changeStatus( + @PathVariable String resource, + @PathVariable Long id, + @RequestBody Map body, + Authentication authentication) { + return ResponseEntity.ok(ApiResponse.success(service.changeStatus(resource, id, body, authentication))); + } +} diff --git a/src/main/java/com/finance/system/controller/CashierController.java b/src/main/java/com/finance/system/controller/CashierController.java index c409648..34de9b2 100644 --- a/src/main/java/com/finance/system/controller/CashierController.java +++ b/src/main/java/com/finance/system/controller/CashierController.java @@ -26,7 +26,7 @@ public class CashierController { private final ReimPaymentService reimPaymentService; @GetMapping("/tasks") - @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") public ResponseEntity>> getTasks( @RequestParam(defaultValue = "UNPAID") String status, @RequestParam(defaultValue = "0") int page, @@ -39,7 +39,7 @@ public class CashierController { } @GetMapping("/tasks/{id}") - @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") public ResponseEntity> getTaskDetail(@PathVariable Long id) { PaymentDetailDto detail = reimPaymentService.getPaymentDetail(id, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success(detail)); @@ -72,8 +72,27 @@ public class CashierController { return ResponseEntity.ok(ApiResponse.success(result)); } + @PostMapping("/payments/verify") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.verify') || @permissionChecker.hasEdit(authentication, 'finance.payment.register')") + public ResponseEntity> verifyPayment( + @javax.validation.Valid @RequestBody PaymentReviewRequest request) { + return ResponseEntity.ok(ApiResponse.success(reimPaymentService.verifyPayment( + request.getPaymentId(), AuditUtil.getCurrentUserId()))); + } + + @PostMapping("/payments/reject") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.reject') || @permissionChecker.hasEdit(authentication, 'finance.payment.register')") + public ResponseEntity> rejectPayment( + @javax.validation.Valid @RequestBody PaymentReviewRequest request) { + if (!StringUtils.hasText(request.getRejectionCode())) { + throw new BadRequestException("付款拒绝码不能为空"); + } + return ResponseEntity.ok(ApiResponse.success(reimPaymentService.rejectPayment( + request.getPaymentId(), AuditUtil.getCurrentUserId(), request.getRejectionCode()))); + } + @GetMapping("/history") - @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") public ResponseEntity>> getPaymentHistory() { Long userId = AuditUtil.getCurrentUserId(); List history = reimPaymentService.getPaymentHistoryByOperator(userId); @@ -81,7 +100,7 @@ public class CashierController { } @GetMapping("/payments/{paymentNo}") - @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.finance-receipt')") public ResponseEntity> getPaymentByNo(@PathVariable String paymentNo) { PaymentRecordDto payment = reimPaymentService.getPaymentByNo(paymentNo, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success(payment)); diff --git a/src/main/java/com/finance/system/controller/DashboardController.java b/src/main/java/com/finance/system/controller/DashboardController.java index 264ca7e..8f9973c 100644 --- a/src/main/java/com/finance/system/controller/DashboardController.java +++ b/src/main/java/com/finance/system/controller/DashboardController.java @@ -20,7 +20,7 @@ public class DashboardController { private final DashboardService dashboardService; @GetMapping("/stats") - @PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.applications')") public ResponseEntity> getStats() { Long userId = AuditUtil.getCurrentUserId(); DashboardStats stats = dashboardService.getDashboardStats(userId); @@ -28,7 +28,7 @@ public class DashboardController { } @GetMapping("/recent") - @PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')") + @PreAuthorize("@permissionChecker.has(authentication, 'page.applications')") public ResponseEntity>> getRecent( @RequestParam(defaultValue = "5") int limit) { Long userId = AuditUtil.getCurrentUserId(); diff --git a/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java b/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java index 10c0e89..83233d0 100644 --- a/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java +++ b/src/main/java/com/finance/system/controller/FeishuApprovalDefinitionController.java @@ -2,6 +2,9 @@ package com.finance.system.controller; import com.finance.system.adapter.feishu.FeishuDefinitionSyncService; import com.finance.system.dto.*; +import com.finance.system.integration.audit.IntegrationAuditEvents; +import com.finance.system.security.integration.IntegrationAccess; +import com.finance.system.security.integration.IntegrationAuthorization; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -12,10 +15,24 @@ import org.springframework.web.bind.annotation.*; @RequiredArgsConstructor public class FeishuApprovalDefinitionController { private final FeishuDefinitionSyncService syncService; + private final IntegrationAuthorization authorization; + private final IntegrationAuditEvents auditEvents; @PostMapping("/sync") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.feishu.approval.sync')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'sync')") public ResponseEntity> sync() { - return ResponseEntity.ok(ApiResponse.success(syncService.sync())); + IntegrationAccess access = authorization.require("integration.feishu", "sync"); + try { + FeishuDefinitionSyncResult result = syncService.sync(); + auditEvents.management(access.getTenantId(), access.getActorId(), + "integration.feishu.approval.sync", "FEISHU_APPROVAL_DEFINITION", + "ACTIVE", "SYNCED", java.util.Collections.emptyList()); + return ResponseEntity.ok(ApiResponse.success(result)); + } catch (RuntimeException failure) { + auditEvents.failed(access.getTenantId(), access.getActorId(), + "integration.feishu.approval.sync", "FEISHU_APPROVAL_DEFINITION", + "ACTIVE", "SYNC_FAILED"); + throw failure; + } } } diff --git a/src/main/java/com/finance/system/controller/FeishuAuthController.java b/src/main/java/com/finance/system/controller/FeishuAuthController.java index 3aeddef..7e350df 100644 --- a/src/main/java/com/finance/system/controller/FeishuAuthController.java +++ b/src/main/java/com/finance/system/controller/FeishuAuthController.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.finance.system.adapter.feishu.FeishuApprovalService; import com.finance.system.adapter.feishu.FeishuAuthService; import com.finance.system.adapter.feishu.FeishuApprovalResponse; +import com.finance.system.adapter.feishu.FeishuOAuthStateOriginStore; +import com.finance.system.config.FrontendOriginPolicy; import com.finance.system.dto.ApiResponse; import com.finance.system.entity.SysWebhookEvent; import com.finance.system.entity.IntFeishuApproval; @@ -14,9 +16,9 @@ import com.finance.system.repository.SysWebhookEventRepository; import com.finance.system.service.FeishuWebhookInboxService; import com.finance.system.service.ReimApplicationService; import com.finance.system.util.AuditUtil; +import com.finance.system.security.integration.IntegrationAuthorization; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -47,6 +49,9 @@ public class FeishuAuthController { private final SysWebhookEventRepository webhookEventRepository; private final IntFeishuApprovalRepository feishuApprovalRepository; private final ReimApplicationService reimApplicationService; + private final IntegrationAuthorization integrationAuthorization; + private final FrontendOriginPolicy frontendOrigins; + private final FeishuOAuthStateOriginStore stateOrigins; private FeishuWebhookInboxService webhookInboxService; @Autowired(required = false) @@ -54,12 +59,13 @@ public class FeishuAuthController { this.webhookInboxService = webhookInboxService; } - @Value("${app.frontend-url:}") - private String frontendUrl; - @GetMapping("/auth-url") - public ResponseEntity>> getAuthUrl(HttpServletRequest request) { - FeishuAuthService.AuthUrl auth = feishuAuthService.buildAuthUrlWithState(); + public ResponseEntity>> getAuthUrl( + @RequestParam(value = "origin", required = false) String requestedOrigin, + HttpServletRequest request) { + String trustedOrigin = frontendOrigins.resolveRequestedOrigin(requestedOrigin); + FeishuAuthService.AuthUrl auth = feishuAuthService.buildAuthUrlForFrontendOrigin(trustedOrigin); + stateOrigins.bind(auth.getState(), trustedOrigin); Map result = new HashMap<>(); result.put("authUrl", auth.getAuthUrl()); String state = auth.getState(); @@ -81,17 +87,23 @@ public class FeishuAuthController { @RequestParam(value = "state", required = false) String state, @RequestParam(value = "error", required = false) String error, @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { - log.info("Feishu OAuth callback received"); + log.info("已收到飞书 OAuth 授权回调"); + String redirectOrigin = frontendOrigins.getDefaultOrigin(); try { + // Validate server state before using its stored origin. The second + // check enforces a matching cookie when one is present, while a + // cross-host callback may safely rely on the server-side binding. + feishuAuthService.validateCallbackState(state, null, false); + redirectOrigin = stateOrigins.consume(state); + feishuAuthService.validateCallbackState(state, browserState, false); if (code == null || code.trim().isEmpty() || code.length() > 4096 || error != null) { throw new BusinessException("飞书回调参数无效,请重新发起授权", 400); } // The frontend exchanges the authorization code at /api/auth/feishu-login. - // Validate the callback here, but leave the one-time state for that - // exchange endpoint to consume after it verifies the browser cookie. - feishuAuthService.validateCallbackState(state, browserState, false); - String redirectUrl = frontendUrl + "/login?code=" + encodeUrl(code) + // The shared database state remains for that exchange endpoint to + // consume after it verifies the browser cookie. + String redirectUrl = redirectOrigin + "/login?code=" + encodeUrl(code) + "&state=" + encodeUrl(state); HttpHeaders headers = new HttpHeaders(); applySensitiveRedirectHeaders(headers); @@ -99,15 +111,15 @@ public class FeishuAuthController { return new ResponseEntity<>(headers, HttpStatus.FOUND); } catch (BusinessException e) { - log.warn("Feishu OAuth callback rejected; category=business status={}", e.getStatusCode()); - String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请重新发起授权"); + log.warn("飞书 OAuth 授权回调被拒绝; category=business status={}", e.getStatusCode()); + String errorUrl = redirectOrigin + "/login?error=" + encodeUrl("飞书登录失败,请重新发起授权"); HttpHeaders headers = new HttpHeaders(); applySensitiveRedirectHeaders(headers); headers.setLocation(URI.create(errorUrl)); return new ResponseEntity<>(headers, HttpStatus.FOUND); } catch (Exception e) { - log.error("Feishu OAuth callback failed; category=internal"); - String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请稍后重试"); + log.error("飞书 OAuth 授权回调失败; category=internal"); + String errorUrl = redirectOrigin + "/login?error=" + encodeUrl("飞书登录失败,请稍后重试"); HttpHeaders headers = new HttpHeaders(); applySensitiveRedirectHeaders(headers); headers.setLocation(URI.create(errorUrl)); @@ -146,7 +158,7 @@ public class FeishuAuthController { return ResponseEntity.badRequest().body(responseMap(1, "invalid webhook body")); } - log.info("Feishu webhook request received"); + log.info("已收到飞书事件回调请求"); if (!feishuAuthService.isWebhookAuthorized(body, signature, timestamp, nonce, rawBody)) { return ResponseEntity.status(401).body(responseMap(1, "invalid webhook signature")); @@ -158,7 +170,7 @@ public class FeishuAuthController { if(!(challengeValue instanceof String)||((String)challengeValue).isEmpty()||((String)challengeValue).length()>512) return ResponseEntity.badRequest().body(responseMap(1,"invalid webhook challenge")); String challenge = (String) challengeValue; - log.info("Feishu webhook verification request accepted"); + log.info("飞书事件回调验证请求已通过"); Map result = new HashMap<>(); result.put("challenge", challenge); return ResponseEntity.ok(result); @@ -240,7 +252,7 @@ public class FeishuAuthController { try { claim = webhookInboxService.begin(eventId); } catch (Exception e) { - log.error("Feishu webhook inbox unavailable; category=storage"); + log.error("飞书事件回调收件箱不可用; category=storage"); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) .body(responseMap(1, "webhook inbox unavailable")); } @@ -258,7 +270,7 @@ public class FeishuAuthController { return ResponseEntity.ok(responseMap(0, "success")); } catch (Exception e) { try { webhookInboxService.failed(eventId); } catch (Exception ignored) { } - log.error("Feishu webhook processing failed; category=handler"); + log.error("飞书事件回调处理失败; category=handler"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(responseMap(1, "webhook processing failed")); } @@ -287,7 +299,7 @@ public class FeishuAuthController { event.setStatus(SysWebhookEvent.FAILED); webhookEventRepository.save(event); } - log.error("Feishu webhook processing failed; category=handler"); + log.error("飞书事件回调处理失败; category=handler"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(responseMap(1, "webhook processing failed")); } @@ -304,13 +316,14 @@ public class FeishuAuthController { * 获取审批定义(审批节点信息) */ @GetMapping("/approval/definition") - @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'read')") public ResponseEntity> getApprovalDefinition() { + integrationAuthorization.require("integration.feishu", "read"); try { FeishuApprovalResponse definition = feishuApprovalService.getApprovalDefinition(); return ResponseEntity.ok(ApiResponse.success(definition)); } catch (Exception e) { - log.error("Feishu approval definition request failed; category=internal"); + log.error("飞书审批定义请求失败; category=internal"); return ResponseEntity.ok(ApiResponse.error(500, "获取审批定义失败,请稍后重试")); } } @@ -319,13 +332,14 @@ public class FeishuAuthController { * 获取审批节点列表 */ @GetMapping("/approval/nodes") - @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'read')") public ResponseEntity> getApprovalNodes() { + integrationAuthorization.require("integration.feishu", "read"); try { java.util.List nodes = feishuApprovalService.getApprovalNodes(); return ResponseEntity.ok(ApiResponse.success(nodes)); } catch (Exception e) { - log.error("Feishu approval node request failed; category=internal"); + log.error("飞书审批节点请求失败; category=internal"); return ResponseEntity.ok(ApiResponse.error(500, "获取审批节点失败,请稍后重试")); } } @@ -344,7 +358,7 @@ public class FeishuAuthController { FeishuApprovalResponse detail = feishuApprovalService.getApprovalInstanceDetail(instanceCode); return ResponseEntity.ok(ApiResponse.success(detail)); } catch (Exception e) { - log.error("Feishu approval instance request failed; category=internal"); + log.error("飞书审批实例请求失败; category=internal"); return ResponseEntity.ok(ApiResponse.error(500, "获取审批实例详情失败,请稍后重试")); } } @@ -361,7 +375,7 @@ public class FeishuAuthController { java.util.List timeline = feishuApprovalService.getApprovalTimelineByApplication(applicationId); return ResponseEntity.ok(ApiResponse.success(timeline)); } catch (Exception e) { - log.error("Feishu approval timeline request failed; category=internal"); + log.error("飞书审批时间线请求失败; category=internal"); return ResponseEntity.ok(ApiResponse.error(500, "获取审批进度失败,请稍后重试")); } } diff --git a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java index 0842aa1..7edeab0 100644 --- a/src/main/java/com/finance/system/controller/FeishuDirectoryController.java +++ b/src/main/java/com/finance/system/controller/FeishuDirectoryController.java @@ -2,11 +2,13 @@ package com.finance.system.controller; import com.finance.system.adapter.feishu.FeishuDirectoryService; import com.finance.system.dto.ApiResponse; +import com.finance.system.integration.audit.IntegrationAuditEvents; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -import com.finance.system.security.PermissionChecker; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.core.Authentication; +import com.finance.system.security.integration.IntegrationAccess; +import com.finance.system.security.integration.IntegrationAuthorization; +import com.finance.system.service.ScheduledTaskService; import org.springframework.web.bind.annotation.*; import java.util.Map; @@ -15,31 +17,57 @@ import java.util.Map; @RequestMapping("/api/feishu/directory") public class FeishuDirectoryController { private final FeishuDirectoryService directory; - private final PermissionChecker permissions; + private final ScheduledTaskService scheduledTasks; + private final IntegrationAuthorization authorization; + private final IntegrationAuditEvents auditEvents; @PostMapping("/sync") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.feishu.directory.sync')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'sync')") public ResponseEntity> sync() { - FeishuDirectoryService.Run run = directory.enqueue("MANUAL"); - return ResponseEntity.accepted().body(ApiResponse.success(run)); + IntegrationAccess access = authorization.require("integration.feishu", "sync"); + try { + FeishuDirectoryService.Run run = directory.enqueue("MANUAL"); + auditEvents.management(access.getTenantId(), access.getActorId(), + "integration.feishu.directory.sync-trigger", "FEISHU_DIRECTORY_RUN", + run.getRunId(), "QUEUED", java.util.Collections.emptyList()); + return ResponseEntity.accepted().body(ApiResponse.success(run)); + } catch (RuntimeException failure) { + auditEvents.failed(access.getTenantId(), access.getActorId(), + "integration.feishu.directory.sync-trigger", "FEISHU_DIRECTORY_RUN", + "MANUAL", "ENQUEUE_FAILED"); + throw failure; + } } @GetMapping("/status") - @PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory')") - public ApiResponse> status() { return ApiResponse.success(directory.status()); } + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'read')") + public ApiResponse> status() { + authorization.require("integration.feishu", "read"); + return ApiResponse.success(directory.status()); + } + + @GetMapping("/runs") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'read')") + public ApiResponse> runs( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + IntegrationAccess access = authorization.require("integration.feishu", "read"); + return ApiResponse.success(scheduledTasks.runs( + ScheduledTaskService.FEISHU, page, size, access.getTenantId())); + } @GetMapping("/organization") - @PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'read')") public ApiResponse> organization( - Authentication authentication, @RequestParam(value = "includeUsers", defaultValue = "false") boolean includeUsers) { - boolean withUsers = includeUsers && permissions.has(authentication, "page.feishu-directory"); - return ApiResponse.success(directory.organization(withUsers)); + authorization.require("integration.feishu", "read"); + return ApiResponse.success(directory.organization(includeUsers)); } @GetMapping("/organization/members") - @PreAuthorize("@permissionChecker.has(authentication, 'page.feishu-directory')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.feishu', 'read')") public ApiResponse> organizationMembers( @RequestParam("departmentId") String departmentId, @RequestParam(value = "includeDescendants", defaultValue = "true") boolean includeDescendants) { + authorization.require("integration.feishu", "read"); return ApiResponse.success(directory.organizationMembers(departmentId, includeDescendants)); } } diff --git a/src/main/java/com/finance/system/controller/IntegrationConfigController.java b/src/main/java/com/finance/system/controller/IntegrationConfigController.java index f32d0c9..bae3645 100644 --- a/src/main/java/com/finance/system/controller/IntegrationConfigController.java +++ b/src/main/java/com/finance/system/controller/IntegrationConfigController.java @@ -1,6 +1,8 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; +import com.finance.system.security.integration.IntegrationAccess; +import com.finance.system.security.integration.IntegrationAuthorization; import com.finance.system.service.IntegrationConfigService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -14,18 +16,29 @@ import java.util.Map; @RequiredArgsConstructor public class IntegrationConfigController { private final IntegrationConfigService service; + private final IntegrationAuthorization authorization; @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") - public ResponseEntity>> get() { return ResponseEntity.ok(ApiResponse.success(service.view())); } + @PreAuthorize("@permissionChecker.check(authentication, 'integration.config', 'read')") + public ResponseEntity>> get() { + IntegrationAccess access = authorization.require("integration.config", "read"); + return ResponseEntity.ok(ApiResponse.success(service.view(access.getTenantId()))); + } @PutMapping - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.config.update')") - public ResponseEntity> put(@RequestBody Map body) { service.update(body); return ResponseEntity.ok(ApiResponse.success()); } + @PreAuthorize("@permissionChecker.check(authentication, 'integration.config', 'update')") + public ResponseEntity> put(@RequestBody Map body) { + IntegrationAccess access = authorization.require("integration.config", "update"); + service.update(body, access.getTenantId(), access.getActorId()); + return ResponseEntity.ok(ApiResponse.success()); + } @PostMapping("/test") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.config.test')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.config', 'test')") public ResponseEntity>> test(@RequestBody Map body) { - Object provider = body == null ? null : body.get("provider"); return ResponseEntity.ok(ApiResponse.success(service.test(provider == null ? null : String.valueOf(provider)))); + IntegrationAccess access = authorization.require("integration.config", "test"); + Object provider = body == null ? null : body.get("provider"); + return ResponseEntity.ok(ApiResponse.success(service.test(provider == null ? null : String.valueOf(provider), + access.getTenantId(), access.getActorId()))); } } diff --git a/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java b/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java index fa2dc57..3b93c9c 100644 --- a/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java +++ b/src/main/java/com/finance/system/controller/KingdeeAccountBindingController.java @@ -2,7 +2,8 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; import com.finance.system.service.KingdeeAccountBindingService; -import com.finance.system.util.AuditUtil; +import com.finance.system.security.integration.IntegrationAccess; +import com.finance.system.security.integration.IntegrationAuthorization; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -14,46 +15,52 @@ import java.util.Map; @RestController @RequestMapping("/api/kingdee/account-bindings") @RequiredArgsConstructor +@PreAuthorize("isAuthenticated()") public class KingdeeAccountBindingController { private final KingdeeAccountBindingService service; + private final IntegrationAuthorization authorization; @GetMapping - @PreAuthorize("@permissionChecker.hasAny(authentication, 'page.kingdee-account-binding', 'finance.kingdee.account.view-own', 'finance.kingdee.account.view-all')") public ResponseEntity>>> list() { - return ResponseEntity.ok(ApiResponse.success(service.listBindings(AuditUtil.getCurrentUserId()))); + IntegrationAccess access = authorization.requireOwnOrAll( + "integration.kingdee.account", "read-all", "read-own"); + return ResponseEntity.ok(ApiResponse.success(service.listBindings(access))); } @GetMapping("/me") - @PreAuthorize("@permissionChecker.hasAny(authentication, 'page.kingdee-account-binding', 'finance.kingdee.account.view-own', 'finance.kingdee.document.write')") public ResponseEntity>> me() { - return ResponseEntity.ok(ApiResponse.success(service.myBinding(AuditUtil.getCurrentUserId()))); + IntegrationAccess access = authorization.requireOwnOrAll( + "integration.kingdee.account", "read-all", "read-own"); + return ResponseEntity.ok(ApiResponse.success(service.myBinding(access))); } - @PutMapping("/{userId}") - @PreAuthorize("@permissionChecker.hasAnyEdit(authentication, 'finance.kingdee.account.bind', 'finance.kingdee.account.bind-own')") + @PutMapping("/{employeeOpenId}") public ResponseEntity>> bind( - @PathVariable Long userId, + @PathVariable String employeeOpenId, @RequestBody Map body) { String username = body == null ? null : stringValue(body.get("kingdeeUsername")); String password = body == null ? null : stringValue(body.get("kingdeePassword")); boolean verify = body == null || body.get("verifyLogin") == null || Boolean.parseBoolean(String.valueOf(body.get("verifyLogin"))); - return ResponseEntity.ok(ApiResponse.success( - service.bind(userId, username, password, AuditUtil.getCurrentUserId(), verify))); + IntegrationAccess access = authorization.requireOwnOrAll( + "integration.kingdee.account", "manage-all", "manage-own"); + return ResponseEntity.ok(ApiResponse.success(service.bind(service.resolveEmployeeId(employeeOpenId, access), username, password, access, verify))); } - @DeleteMapping("/{userId}") - @PreAuthorize("@permissionChecker.hasAnyEdit(authentication, 'finance.kingdee.account.unbind', 'finance.kingdee.account.unbind-own')") - public ResponseEntity> unbind(@PathVariable Long userId) { - service.unbind(userId, AuditUtil.getCurrentUserId()); + @DeleteMapping("/{employeeOpenId}") + public ResponseEntity> unbind(@PathVariable String employeeOpenId) { + IntegrationAccess access = authorization.requireOwnOrAll( + "integration.kingdee.account", "manage-all", "manage-own"); + service.unbind(service.resolveEmployeeId(employeeOpenId, access), access); return ResponseEntity.ok(ApiResponse.success()); } - @PostMapping("/{userId}/test") - @PreAuthorize("@permissionChecker.hasAnyEdit(authentication, 'finance.kingdee.account.bind', 'finance.kingdee.account.bind-own')") - public ResponseEntity>> test(@PathVariable Long userId) { - return ResponseEntity.ok(ApiResponse.success(service.testBinding(userId, AuditUtil.getCurrentUserId()))); + @PostMapping("/{employeeOpenId}/test") + public ResponseEntity>> test(@PathVariable String employeeOpenId) { + IntegrationAccess access = authorization.requireOwnOrAll( + "integration.kingdee.account", "manage-all", "manage-own"); + return ResponseEntity.ok(ApiResponse.success(service.testBinding(service.resolveEmployeeId(employeeOpenId, access), access))); } private String stringValue(Object value) { diff --git a/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java b/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java index a2d2604..06149d5 100644 --- a/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java +++ b/src/main/java/com/finance/system/controller/KingdeeSyncConfigController.java @@ -2,6 +2,8 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; import com.finance.system.service.KingdeeSyncConfigService; +import com.finance.system.security.integration.IntegrationAccess; +import com.finance.system.security.integration.IntegrationAuthorization; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -22,59 +24,69 @@ import java.util.Map; @RequiredArgsConstructor public class KingdeeSyncConfigController { private final KingdeeSyncConfigService service; + private final IntegrationAuthorization authorization; @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'read')") public ResponseEntity>>> list() { - return ResponseEntity.ok(ApiResponse.success(service.list())); + IntegrationAccess access = authorization.require("integration.kingdee", "read"); + return ResponseEntity.ok(ApiResponse.success(service.list(access.getTenantId()))); } @PostMapping - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.create')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'manage')") public ResponseEntity>> create(@RequestBody KingdeeSyncConfigService.ConfigRequest request) { - return ResponseEntity.ok(ApiResponse.success(service.create(request))); + IntegrationAccess access = authorization.require("integration.kingdee", "manage"); + return ResponseEntity.ok(ApiResponse.success(service.create(request, access.getTenantId(), access.getActorId()))); } @GetMapping("/{id}") - @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'read')") public ResponseEntity>> get(@PathVariable Long id) { - return ResponseEntity.ok(ApiResponse.success(service.get(id))); + IntegrationAccess access = authorization.require("integration.kingdee", "read"); + return ResponseEntity.ok(ApiResponse.success(service.get(id, access.getTenantId()))); } @PutMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.update')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'manage')") public ResponseEntity>> update(@PathVariable Long id, @RequestBody KingdeeSyncConfigService.ConfigRequest request) { - return ResponseEntity.ok(ApiResponse.success(service.update(id, request))); + IntegrationAccess access = authorization.require("integration.kingdee", "manage"); + return ResponseEntity.ok(ApiResponse.success(service.update(id, request, access.getTenantId(), access.getActorId()))); } @DeleteMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.rule.delete')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'manage')") public ResponseEntity> delete(@PathVariable Long id) { - service.delete(id); return ResponseEntity.ok(ApiResponse.success()); + IntegrationAccess access = authorization.require("integration.kingdee", "manage"); + service.delete(id, access.getTenantId(), access.getActorId()); return ResponseEntity.ok(ApiResponse.success()); } @PostMapping("/{id}/preview") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.data.preview')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'read')") public ResponseEntity>> preview(@PathVariable Long id) { - return ResponseEntity.ok(ApiResponse.success(service.preview(id))); + IntegrationAccess access = authorization.require("integration.kingdee", "read"); + return ResponseEntity.ok(ApiResponse.success(service.preview(id, access.getTenantId()))); } @PostMapping("/{id}/prepare-table") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.table.prepare')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'manage')") public ResponseEntity>> prepareTable(@PathVariable Long id) { - return ResponseEntity.ok(ApiResponse.success(service.prepareTable(id))); + IntegrationAccess access = authorization.require("integration.kingdee", "manage"); + return ResponseEntity.ok(ApiResponse.success(service.prepareTable(id, access.getTenantId()))); } @PostMapping("/{id}/sync") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.integration.kingdee.sync.execute')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'sync')") public ResponseEntity>> sync(@PathVariable Long id) { - return ResponseEntity.ok(ApiResponse.success(service.sync(id))); + IntegrationAccess access = authorization.require("integration.kingdee", "sync"); + return ResponseEntity.ok(ApiResponse.success(service.sync(id, access.getTenantId(), access.getActorId()))); } @GetMapping("/{id}/runs") - @PreAuthorize("@permissionChecker.has(authentication, 'page.integration-config')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.kingdee', 'read')") public ResponseEntity>>> runs(@PathVariable Long id) { - return ResponseEntity.ok(ApiResponse.success(service.runs(id))); + IntegrationAccess access = authorization.require("integration.kingdee", "read"); + return ResponseEntity.ok(ApiResponse.success(service.runs(id, access.getTenantId()))); } } diff --git a/src/main/java/com/finance/system/controller/LogController.java b/src/main/java/com/finance/system/controller/LogController.java index 0e0cfba..8824dea 100644 --- a/src/main/java/com/finance/system/controller/LogController.java +++ b/src/main/java/com/finance/system/controller/LogController.java @@ -2,14 +2,13 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; import com.finance.system.service.ApiAccessLogService; -import com.finance.system.service.RoleService; -import com.finance.system.util.AuditUtil; +import com.finance.system.audit.query.AuditQueryAuthorization; +import com.finance.system.audit.query.AuditQueryScope; +import com.finance.system.audit.query.CursorPage; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.util.StringUtils; +import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -17,69 +16,54 @@ import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; +import java.time.LocalDateTime; -@Slf4j @RestController @RequestMapping("/api/logs") @RequiredArgsConstructor +@PreAuthorize("isAuthenticated()") public class LogController { private final ApiAccessLogService apiAccessLogService; - private final RoleService roleService; + private final AuditQueryAuthorization authorization; /** * Lists persisted API access logs for the in-app operation log page. * view-all sees everyone; view-own (or page only) is limited to the current operator. */ @GetMapping - @PreAuthorize("@permissionChecker.hasAny(authentication, 'page.operation-log', 'system.operation-log.view-own', 'system.operation-log.view-all')") public ResponseEntity>>> listLogs( @RequestParam(required = false) String category, + @RequestParam(required = false) Long actorId, @RequestParam(required = false) String operator, @RequestParam(defaultValue = "200") int limit) { - try { - Long userId = AuditUtil.getCurrentUserId(); - boolean viewAll = roleService.hasPermission(userId, "system.operation-log.view-all"); - boolean viewOwn = roleService.hasPermission(userId, "system.operation-log.view-own") - || roleService.hasPermission(userId, "page.operation-log"); - if (!viewAll && !viewOwn) throw new AccessDeniedException("无权查看操作日志"); - - String scopedOperator = operator; - if (!viewAll) { - String selfName = AuditUtil.getCurrentUserRealName(); - if (StringUtils.hasText(operator) && selfName != null - && !"系统".equals(selfName) - && !operator.trim().equalsIgnoreCase(selfName.trim())) { - throw new AccessDeniedException("当前权限仅可查看本人操作日志"); - } - scopedOperator = "系统".equals(selfName) ? null : selfName; - } - List> rows = apiAccessLogService.list(category, scopedOperator, limit); - if (!viewAll && userId != null) { - String selfName = AuditUtil.getCurrentUserRealName(); - rows = rows.stream() - .filter(row -> Objects.equals(userId, asLong(row.get("operatorId"))) - || (selfName != null && selfName.equals(String.valueOf(row.get("operator"))))) - .collect(Collectors.toList()); - } - return ResponseEntity.ok(ApiResponse.success(rows)); - } catch (AccessDeniedException e) { - throw e; - } catch (Exception e) { - log.error("获取操作日志列表失败", e); - return ResponseEntity.ok(ApiResponse.error(500, "获取操作日志列表失败: " + e.getMessage())); - } + AuditQueryScope scope = authorization.authorize("ACCESS"); + Long scopedActorId = scopedActor(scope, actorId); + String scopedOperator = scope.isAllActors() ? operator : null; + return ResponseEntity.ok(ApiResponse.success( + apiAccessLogService.list(scope.getTenantId(), scope.getOrganizationId(), + category, scopedActorId, scopedOperator, limit))); } - private Long asLong(Object value) { - if (value instanceof Number) return ((Number) value).longValue(); - if (value == null) return null; - try { - return Long.parseLong(String.valueOf(value)); - } catch (NumberFormatException e) { - return null; - } + @GetMapping("/cursor") + public ApiResponse>> cursor( + @RequestParam(required = false) String category, + @RequestParam(required = false) Long actorId, + @RequestParam(required = false) String operator, + @RequestParam(required = false) String outcome, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + LocalDateTime cursorTime, + @RequestParam(required = false) Long cursorId, + @RequestParam(required = false) Integer limit) { + AuditQueryScope scope = authorization.authorize("ACCESS"); + return ApiResponse.success(apiAccessLogService.cursor(scope.getTenantId(), scope.getOrganizationId(), category, + scopedActor(scope, actorId), scope.isAllActors() ? operator : null, + outcome, cursorTime, cursorId, limit)); + } + + private Long scopedActor(AuditQueryScope scope, Long requested) { + if (!scope.isAllActors() && requested != null && !requested.equals(scope.getActorId())) + throw new org.springframework.security.access.AccessDeniedException("仅可查询本人访问日志"); + return scope.isAllActors() ? requested : scope.getActorId(); } } diff --git a/src/main/java/com/finance/system/controller/MetadataController.java b/src/main/java/com/finance/system/controller/MetadataController.java index c03a51e..ed33246 100644 --- a/src/main/java/com/finance/system/controller/MetadataController.java +++ b/src/main/java/com/finance/system/controller/MetadataController.java @@ -1,7 +1,10 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; +import com.finance.system.dto.PayeeAccountDto; import com.finance.system.repository.SysExpenseTypeRepository; +import com.finance.system.service.PayeeAccountService; +import com.finance.system.util.AuditUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; @@ -18,40 +21,7 @@ import java.util.stream.Collectors; public class MetadataController { private final SysExpenseTypeRepository expenseTypeRepository; - - /** - * Mock数据 - 收款人 - */ - private static final List> PAYEES = new ArrayList<>(); - - static { - Map p1 = new LinkedHashMap<>(); - p1.put("id", 1); - p1.put("name", "李志豪"); - p1.put("employeeNo", "EMP000086"); - p1.put("department", "销售中心"); - p1.put("bankName", "中国工商银行苏州新区支行"); - p1.put("bankAccount", "6222 0200 0086 0728"); - PAYEES.add(p1); - - Map p2 = new LinkedHashMap<>(); - p2.put("id", 2); - p2.put("name", "王忠辉"); - p2.put("employeeNo", "EMP000087"); - p2.put("department", "数字化中心"); - p2.put("bankName", "招商银行苏州分行"); - p2.put("bankAccount", "6222 **** 3402"); - PAYEES.add(p2); - - Map p3 = new LinkedHashMap<>(); - p3.put("id", 3); - p3.put("name", "赵海峰"); - p3.put("employeeNo", "EMP000088"); - p3.put("department", "供应链中心"); - p3.put("bankName", "招商银行苏州工业园区支行"); - p3.put("bankAccount", "6214 **** 8001"); - PAYEES.add(p3); - } + private final PayeeAccountService payeeAccountService; /** * 获取费用类型列表 @@ -76,37 +46,10 @@ public class MetadataController { * 获取收款人列表 */ @GetMapping("/payees") - @PreAuthorize("@permissionChecker.has(authentication, 'page.payees') || @permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')") - public ResponseEntity>>> getPayees( + @PreAuthorize("@permissionChecker.has(authentication, 'page.application-create') || @permissionChecker.has(authentication, 'page.application-edit')") + public ResponseEntity>> getPayees( @RequestParam(required = false) String keyword) { - try { - List> result = PAYEES.stream().map(payee -> { - Map safe = new LinkedHashMap<>(payee); - Object rawAccount = safe.remove("bankAccount"); - if (rawAccount != null) safe.put("bankAccountMask", maskAccount(String.valueOf(rawAccount))); - return safe; - }).collect(Collectors.toList()); - - if (keyword != null && !keyword.isEmpty()) { - String lowerKeyword = keyword.toLowerCase(); - result.removeIf(p -> { - String name = (String) p.get("name"); - String empNo = (String) p.get("employeeNo"); - return !(name != null && name.toLowerCase().contains(lowerKeyword)) - && !(empNo != null && empNo.toLowerCase().contains(lowerKeyword)); - }); - } - - return ResponseEntity.ok(ApiResponse.success(result)); - } catch (Exception e) { - log.error("获取收款人列表失败", e); - return ResponseEntity.ok(ApiResponse.error(500, "获取收款人列表失败: " + e.getMessage())); - } - } - - private static String maskAccount(String value) { - String digits = value.replaceAll("\\s+", ""); - if (digits.length() <= 4) return "已脱敏"; - return "**** " + digits.substring(digits.length() - 4); + return ResponseEntity.ok(ApiResponse.success( + payeeAccountService.listOwnActiveForReimbursement(AuditUtil.getCurrentUserId(), keyword))); } } diff --git a/src/main/java/com/finance/system/controller/PayeeAccountController.java b/src/main/java/com/finance/system/controller/PayeeAccountController.java new file mode 100644 index 0000000..76e31c7 --- /dev/null +++ b/src/main/java/com/finance/system/controller/PayeeAccountController.java @@ -0,0 +1,137 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.dto.PayeeAccountDto; +import com.finance.system.dto.PayeeAccountRequest; +import com.finance.system.dto.PayeeUserDto; +import com.finance.system.dto.PayeeSubjectDto; +import com.finance.system.dto.PayeeSubjectRequest; +import com.finance.system.service.PayeeAccountService; +import com.finance.system.service.PayeeSubjectService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequestMapping("/api/payees") +@RequiredArgsConstructor +@PreAuthorize("isAuthenticated()") +public class PayeeAccountController { + private final PayeeAccountService service; + private final PayeeSubjectService subjectService; + + @GetMapping("/subjects") + public ResponseEntity>> subjects( + @RequestParam(required = false) String keyword) { + return ResponseEntity.ok(ApiResponse.success( + subjectService.list(AuditUtil.getCurrentUserId(), keyword))); + } + + @GetMapping("/subjects/{payeeId}") + public ResponseEntity> subject(@PathVariable Long payeeId) { + return ResponseEntity.ok(ApiResponse.success( + subjectService.get(AuditUtil.getCurrentUserId(), payeeId))); + } + + @PostMapping("/subjects") + public ResponseEntity> createSubject( + @Valid @RequestBody PayeeSubjectRequest request) { + return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success( + subjectService.create(AuditUtil.getCurrentUserId(), request))); + } + + @PutMapping("/subjects/{payeeId}") + public ResponseEntity> updateSubject( + @PathVariable Long payeeId, @Valid @RequestBody PayeeSubjectRequest request) { + return ResponseEntity.ok(ApiResponse.success( + subjectService.update(AuditUtil.getCurrentUserId(), payeeId, request))); + } + + @DeleteMapping("/subjects/{payeeId}") + public ResponseEntity> deactivateSubject(@PathVariable Long payeeId) { + return ResponseEntity.ok(ApiResponse.success( + subjectService.deactivate(AuditUtil.getCurrentUserId(), payeeId))); + } + + @GetMapping("/subjects/{payeeId}/accounts") + public ResponseEntity>> subjectAccounts(@PathVariable Long payeeId) { + return ResponseEntity.ok(ApiResponse.success( + subjectService.listAccounts(AuditUtil.getCurrentUserId(), payeeId))); + } + + @PostMapping("/subjects/{payeeId}/accounts") + public ResponseEntity> createSubjectAccount( + @PathVariable Long payeeId, @Valid @RequestBody PayeeAccountRequest request) { + return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success( + subjectService.createAccount(AuditUtil.getCurrentUserId(), payeeId, request))); + } + + @PutMapping("/subjects/{payeeId}/accounts/{accountId}") + public ResponseEntity> updateSubjectAccount( + @PathVariable Long payeeId, @PathVariable Long accountId, + @Valid @RequestBody PayeeAccountRequest request) { + return ResponseEntity.ok(ApiResponse.success(subjectService.updateAccount( + AuditUtil.getCurrentUserId(), payeeId, accountId, request))); + } + + @PutMapping("/subjects/{payeeId}/accounts/{accountId}/default") + public ResponseEntity> setDefaultSubjectAccount( + @PathVariable Long payeeId, @PathVariable Long accountId) { + return ResponseEntity.ok(ApiResponse.success(subjectService.setDefaultAccount( + AuditUtil.getCurrentUserId(), payeeId, accountId))); + } + + @DeleteMapping("/subjects/{payeeId}/accounts/{accountId}") + public ResponseEntity> deactivateSubjectAccount( + @PathVariable Long payeeId, @PathVariable Long accountId) { + return ResponseEntity.ok(ApiResponse.success(subjectService.deactivateAccount( + AuditUtil.getCurrentUserId(), payeeId, accountId))); + } + + @GetMapping + public ResponseEntity>> list( + @RequestParam(required = false) String keyword) { + return ResponseEntity.ok(ApiResponse.success( + service.list(AuditUtil.getCurrentUserId(), keyword))); + } + + @GetMapping("/eligible-users") + public ResponseEntity>> eligibleUsers() { + return ResponseEntity.ok(ApiResponse.success( + service.eligibleUsers(AuditUtil.getCurrentUserId()))); + } + + @PostMapping + public ResponseEntity> create( + @Valid @RequestBody PayeeAccountRequest request) { + return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success( + service.create(AuditUtil.getCurrentUserId(), request))); + } + + @PutMapping("/{id}") + public ResponseEntity> update( + @PathVariable Long id, @Valid @RequestBody PayeeAccountRequest request) { + return ResponseEntity.ok(ApiResponse.success( + service.update(AuditUtil.getCurrentUserId(), id, request))); + } + + @DeleteMapping("/{id}") + public ResponseEntity> deactivate(@PathVariable Long id) { + return ResponseEntity.ok(ApiResponse.success( + service.deactivate(AuditUtil.getCurrentUserId(), id))); + } +} diff --git a/src/main/java/com/finance/system/controller/PaymentController.java b/src/main/java/com/finance/system/controller/PaymentController.java deleted file mode 100644 index 170cfa1..0000000 --- a/src/main/java/com/finance/system/controller/PaymentController.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.finance.system.controller; - -import com.finance.system.dto.ApiResponse; -import com.finance.system.security.UserPrincipal; -import com.finance.system.util.AuditUtil; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.context.annotation.Profile; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import java.math.BigDecimal; -import java.util.*; - -@Slf4j -@RestController -@RequestMapping("/api/payments") -@RequiredArgsConstructor -@Profile({"local", "test"}) -public class PaymentController { - - /** - * Mock数据 - 付款记录 - */ - private static final List> MOCK_PAYMENTS = new ArrayList<>(); - - static { - Map p1 = new LinkedHashMap<>(); - p1.put("id", "PAY-20260803-01"); - p1.put("applicationId", "BX20260728004"); - p1.put("applicationNo", "BX20260728004"); - p1.put("title", "上海项目住宿费"); - p1.put("payee", "赵海峰"); - p1.put("amount", new BigDecimal("1800.00")); - p1.put("paidAmount", new BigDecimal("1800.00")); - p1.put("unpaidAmount", new BigDecimal("2300.00")); - p1.put("time", "2026-08-03 15:24"); - p1.put("method", "银行转账"); - p1.put("account", "招商银行 · 9032"); - p1.put("reference", "FLOW202608030883"); - p1.put("operator", "周敏"); - p1.put("status", "有效"); - p1.put("expenseType", "员工报销类"); - MOCK_PAYMENTS.add(p1); - } - - /** - * Mock数据 - 付款申请列表(带付款信息) - */ - private static final List> MOCK_PAYMENT_APPLICATIONS = new ArrayList<>(); - - static { - Map a1 = new LinkedHashMap<>(); - a1.put("id", "BX20260728004"); - a1.put("date", "2026-07-28"); - a1.put("title", "上海项目住宿费"); - a1.put("payee", "赵海峰"); - a1.put("owner", "赵海峰"); - a1.put("department", "供应链中心"); - a1.put("amount", new BigDecimal("4100.00")); - a1.put("paidAmount", new BigDecimal("1800.00")); - a1.put("unpaidAmount", new BigDecimal("2300.00")); - a1.put("receiptStatus", "已收单"); - a1.put("paymentStatus", "部分付款"); - a1.put("expenseType", "员工报销类"); - MOCK_PAYMENT_APPLICATIONS.add(a1); - - Map a2 = new LinkedHashMap<>(); - a2.put("id", "BX20260801009"); - a2.put("date", "2026-08-01"); - a2.put("title", "七月云资源差旅补贴"); - a2.put("payee", "王忠辉"); - a2.put("owner", "王忠辉"); - a2.put("department", "数字化中心"); - a2.put("amount", new BigDecimal("3200.00")); - a2.put("paidAmount", new BigDecimal("0.00")); - a2.put("unpaidAmount", new BigDecimal("3200.00")); - a2.put("receiptStatus", "已收单"); - a2.put("paymentStatus", "未付款"); - a2.put("expenseType", "员工报销类"); - MOCK_PAYMENT_APPLICATIONS.add(a2); - - Map a3 = new LinkedHashMap<>(); - a3.put("id", "BX20260802011"); - a3.put("date", "2026-08-02"); - a3.put("title", "苏州园区客户拜访费用"); - a3.put("payee", "赵海峰"); - a3.put("owner", "赵海峰"); - a3.put("department", "供应链中心"); - a3.put("amount", new BigDecimal("2180.00")); - a3.put("paidAmount", new BigDecimal("0.00")); - a3.put("unpaidAmount", new BigDecimal("2180.00")); - a3.put("receiptStatus", "待收单"); - a3.put("paymentStatus", "未付款"); - a3.put("expenseType", "员工报销类"); - MOCK_PAYMENT_APPLICATIONS.add(a3); - - Map a4 = new LinkedHashMap<>(); - a4.put("id", "BX20260809003"); - a4.put("date", "2026-08-09"); - a4.put("title", "八月客户拜访交通费"); - a4.put("payee", "李志豪"); - a4.put("owner", "李志豪"); - a4.put("department", "销售中心"); - a4.put("amount", new BigDecimal("1260.00")); - a4.put("paidAmount", new BigDecimal("0.00")); - a4.put("unpaidAmount", new BigDecimal("1260.00")); - a4.put("receiptStatus", "未触发"); - a4.put("paymentStatus", "未付款"); - a4.put("expenseType", "员工报销类"); - MOCK_PAYMENT_APPLICATIONS.add(a4); - } - - /** - * 获取付款列表(资金出纳B视图,过滤 expenseType=员工报销类) - */ - @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.payments')") - public ResponseEntity>> listPayments( - @RequestParam(required = false) String status, - @RequestParam(required = false) String expenseType) { - try { - List> applications = new ArrayList<>(MOCK_PAYMENT_APPLICATIONS); - - // 默认过滤 expenseType=员工报销类 - if (expenseType != null && !expenseType.isEmpty()) { - applications.removeIf(app -> !expenseType.equals(app.get("expenseType"))); - } else { - applications.removeIf(app -> !"员工报销类".equals(app.get("expenseType"))); - } - - // 按付款状态过滤 - if (status != null && !status.isEmpty()) { - applications.removeIf(app -> !status.equals(app.get("paymentStatus"))); - } - - Map result = new LinkedHashMap<>(); - result.put("applications", applications); - result.put("payments", new ArrayList<>(MOCK_PAYMENTS)); - result.put("total", applications.size()); - - return ResponseEntity.ok(ApiResponse.success(result)); - } catch (Exception e) { - log.error("获取付款列表失败", e); - return ResponseEntity.ok(ApiResponse.error(500, "获取付款列表失败: " + e.getMessage())); - } - } - - /** - * 登记付款 - */ - @PostMapping("/register") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'finance.payment.register')") - public ResponseEntity>> registerPayment(@RequestBody Map request) { - try { - UserPrincipal principal = AuditUtil.getCurrentUser(); - String applicationNo = (String) request.get("applicationNo"); - Object amountObj = request.get("amount"); - BigDecimal amount; - if (amountObj instanceof Number) { - amount = new BigDecimal(((Number) amountObj).toString()); - } else { - amount = new BigDecimal(String.valueOf(amountObj)); - } - String method = (String) request.getOrDefault("method", "银行转账"); - String account = (String) request.getOrDefault("account", "招商银行 · 9032"); - String reference = (String) request.getOrDefault("reference", "FLOW-" + System.currentTimeMillis()); - - if (applicationNo == null || applicationNo.trim().isEmpty()) { - return ResponseEntity.badRequest() - .body(ApiResponse.error(400, "申请单号不能为空")); - } - if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) { - return ResponseEntity.badRequest() - .body(ApiResponse.error(400, "付款金额必须大于0")); - } - - // 创建付款记录 - Map payment = new LinkedHashMap<>(); - payment.put("id", "PAY-" + java.time.LocalDate.now().toString().replace("-", "") + "-" + String.format("%02d", MOCK_PAYMENTS.size() + 1)); - payment.put("applicationNo", applicationNo); - payment.put("amount", amount); - payment.put("time", java.time.LocalDateTime.now().toString().replace("T", " ")); - payment.put("method", method); - payment.put("account", account); - payment.put("reference", reference); - payment.put("operator", principal != null ? principal.getRealName() : "系统"); - payment.put("status", "有效"); - - // 添加到mock列表 - MOCK_PAYMENTS.add(payment); - - log.info("付款登记成功: applicationNo={}, amount={}", applicationNo, amount); - - return ResponseEntity.ok(ApiResponse.success(payment)); - } catch (Exception e) { - log.error("登记付款失败", e); - return ResponseEntity.ok(ApiResponse.error(500, "登记付款失败: " + e.getMessage())); - } - } -} diff --git a/src/main/java/com/finance/system/controller/ReimApplicationController.java b/src/main/java/com/finance/system/controller/ReimApplicationController.java index d58b013..2457248 100644 --- a/src/main/java/com/finance/system/controller/ReimApplicationController.java +++ b/src/main/java/com/finance/system/controller/ReimApplicationController.java @@ -49,12 +49,10 @@ public class ReimApplicationController { } @GetMapping("/workbench") - @PreAuthorize("@permissionChecker.has(authentication, 'page.dashboard')" - + " || @permissionChecker.has(authentication, 'page.applications')" + @PreAuthorize("@permissionChecker.has(authentication, 'page.applications')" + " || @permissionChecker.has(authentication, 'page.application-create')" + " || @permissionChecker.has(authentication, 'page.application-edit')" - + " || @permissionChecker.has(authentication, 'page.finance-receipt')" - + " || @permissionChecker.has(authentication, 'page.payments')") + + " || @permissionChecker.has(authentication, 'page.finance-receipt')") public ResponseEntity> getWorkbench() { Long userId = AuditUtil.getCurrentUserId(); WorkbenchDto workbench = reimApplicationService.getWorkbench(userId); @@ -142,7 +140,7 @@ public class ReimApplicationController { } @DeleteMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.edit')") + @PreAuthorize("@permissionChecker.hasEdit(authentication, 'reimbursement.application.delete')") public ResponseEntity> delete(@PathVariable Long id) { reimApplicationService.deleteApplication(id, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); diff --git a/src/main/java/com/finance/system/controller/RoleController.java b/src/main/java/com/finance/system/controller/RoleController.java index c21efbe..503fdec 100644 --- a/src/main/java/com/finance/system/controller/RoleController.java +++ b/src/main/java/com/finance/system/controller/RoleController.java @@ -6,10 +6,14 @@ import com.finance.system.entity.SysUser; import com.finance.system.repository.SysUserRepository; import com.finance.system.security.UserPrincipal; import com.finance.system.service.RoleService; +import com.finance.system.authorization.RoleAuthorizationProfileDto; +import com.finance.system.authorization.RoleAuthorizationProfileService; +import com.finance.system.authorization.UpdateRoleAuthorizationProfileRequest; import com.finance.system.util.AuditUtil; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; import java.util.*; @@ -18,10 +22,13 @@ import java.util.*; public class RoleController { private final SysUserRepository sysUserRepository; private final RoleService roleService; + private final RoleAuthorizationProfileService authorizationProfileService; - public RoleController(SysUserRepository sysUserRepository, RoleService roleService) { + public RoleController(SysUserRepository sysUserRepository, RoleService roleService, + RoleAuthorizationProfileService authorizationProfileService) { this.sysUserRepository = sysUserRepository; this.roleService = roleService; + this.authorizationProfileService = authorizationProfileService; } private static final List> ROLE_PROFILES = new ArrayList<>(); @@ -40,10 +47,12 @@ public class RoleController { /** Kept for the existing login page contract. */ @GetMapping("/profiles") + @PreAuthorize("isAuthenticated()") public ResponseEntity>>> getRoleProfiles() { return ResponseEntity.ok(ApiResponse.success(ROLE_PROFILES)); } /** Kept for the existing role drawer contract. */ @GetMapping("/current") + @PreAuthorize("isAuthenticated()") public ResponseEntity>> getCurrentRole() { UserPrincipal principal = AuditUtil.getCurrentUser(); if (principal == null) return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录")); @@ -61,45 +70,77 @@ public class RoleController { } @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.roles') || @permissionChecker.has(authentication, 'page.groups') || @permissionChecker.hasEdit(authentication, 'system.group.role.bind')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.role', 'read')") public ResponseEntity>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listRoles())); } @PostMapping - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.create')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.role', 'create')") public ResponseEntity>> create(@RequestBody Map body) { return ResponseEntity.status(201).body(ApiResponse.success(toMap(roleService.saveRole(null, body)))); } @PutMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.edit')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.role', 'update')") public ResponseEntity>> update(@PathVariable Long id, @RequestBody Map body) { return ResponseEntity.ok(ApiResponse.success(toMap(roleService.saveRole(id, body)))); } @DeleteMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.delete')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.role', 'delete')") public ResponseEntity> delete(@PathVariable Long id) { roleService.deleteRole(id); return ResponseEntity.ok(ApiResponse.success()); } @GetMapping("/permissions") - @PreAuthorize("@permissionChecker.has(authentication, 'page.roles')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')") public ResponseEntity>>> catalog() { return ResponseEntity.ok(ApiResponse.success(roleService.permissionCatalog())); } @GetMapping("/{id}/permissions") - @PreAuthorize("@permissionChecker.has(authentication, 'page.roles')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')") public ResponseEntity>> getPermissions(@PathVariable Long id) { return ResponseEntity.ok(ApiResponse.success(roleService.rolePermissions(id))); } + @GetMapping("/{id}/groups") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.role', 'read')") + public ResponseEntity>> groups(@PathVariable Long id) { + return ResponseEntity.ok(ApiResponse.success(Collections.singletonMap("groupIds", roleService.roleGroupIds(id)))); + } + + @PutMapping("/{id}/groups") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.role', 'manage')") + public ResponseEntity> setGroups(@PathVariable Long id, @RequestBody Map body) { + if (!(body.get("groupIds") instanceof Collection) || !(body.get("expectedGroupIds") instanceof Collection)) { + throw new com.finance.system.exception.BusinessException("groupIds 和 expectedGroupIds 必须是数组", 400); + } + roleService.replaceRoleGroups(id, (Collection) body.get("groupIds"), + (Collection) body.get("expectedGroupIds"), AuditUtil.getCurrentUserId()); + return ResponseEntity.ok(ApiResponse.success()); + } + @PutMapping("/{id}/permissions") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.role.permission.configure')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')") public ResponseEntity> setPermissions(@PathVariable Long id, @RequestBody Map body) { - roleService.replaceRolePermissions(id, body, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success()); + throw new com.finance.system.exception.BusinessException("旧角色权限写入接口已停用,请使用授权目录接口", 410); + } + + @GetMapping("/{id}/authorization-profile") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.role', 'read') and @permissionChecker.check(authentication, 'iam.policy', 'read')") + public ResponseEntity> getAuthorizationProfile(@PathVariable Long id) { + return ResponseEntity.ok(ApiResponse.success(authorizationProfileService.get(id))); + } + + @PutMapping("/{id}/authorization-profile") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')") + public ResponseEntity> replaceAuthorizationProfile( + @PathVariable Long id, @Valid @RequestBody UpdateRoleAuthorizationProfileRequest request) { + return ResponseEntity.ok(ApiResponse.success( + authorizationProfileService.replace(id, request, AuditUtil.getCurrentUserId()))); } @GetMapping("/current-permissions") + @PreAuthorize("isAuthenticated()") public ResponseEntity>> currentPermissions() { Long userId = AuditUtil.getCurrentUserId(); if (userId == null) return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录")); return ResponseEntity.ok(ApiResponse.success(roleService.currentPermissionsMap(userId))); } private String display(String code) { if ("SUPER_ADMIN".equals(code)) return "超级管理员"; if ("FINANCE".equals(code)) return "财务人员"; return "员工"; } - private Map toMap(SysRole role) { Map x = new LinkedHashMap<>(); x.put("id", role.getId()); x.put("roleCode", role.getRoleCode()); x.put("roleName", role.getRoleName()); x.put("description", role.getDescription()); x.put("status", role.getStatus()); x.put("builtIn", role.getBuiltIn()); return x; } + private Map toMap(SysRole role) { Map x = new LinkedHashMap<>(); x.put("id", role.getId()); x.put("roleCode", role.getRoleCode()); x.put("roleName", role.getRoleName()); x.put("description", role.getDescription()); x.put("status", role.getStatus()); x.put("builtIn", role.getBuiltIn()); x.put("privilegeTier", role.getPrivilegeTier()); return x; } } diff --git a/src/main/java/com/finance/system/controller/ScheduledTaskController.java b/src/main/java/com/finance/system/controller/ScheduledTaskController.java index 7a5fed4..859897f 100644 --- a/src/main/java/com/finance/system/controller/ScheduledTaskController.java +++ b/src/main/java/com/finance/system/controller/ScheduledTaskController.java @@ -3,6 +3,8 @@ package com.finance.system.controller; import com.finance.system.dto.ApiResponse; import com.finance.system.dto.ScheduledTaskRunDto; import com.finance.system.service.ScheduledTaskService; +import com.finance.system.security.integration.IntegrationAccess; +import com.finance.system.security.integration.IntegrationAuthorization; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -23,37 +25,44 @@ import java.util.Map; @RequestMapping("/api/scheduled-tasks") public class ScheduledTaskController { private final ScheduledTaskService service; + private final IntegrationAuthorization authorization; @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.schedule', 'read')") public ApiResponse>> list() { - return ApiResponse.success(service.list()); + IntegrationAccess access = authorization.require("integration.schedule", "read"); + return ApiResponse.success(service.list(access.getTenantId())); } @GetMapping("/{code}") - @PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.schedule', 'read')") public ApiResponse> detail(@PathVariable String code) { - return ApiResponse.success(service.detail(code)); + IntegrationAccess access = authorization.require("integration.schedule", "read"); + return ApiResponse.success(service.detail(code, access.getTenantId())); } @PutMapping("/{code}/schedule") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.scheduled-task.config.update')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.schedule', 'manage')") public ApiResponse> update(@PathVariable String code, @RequestBody ScheduledTaskService.ScheduleRequest request) { - return ApiResponse.success(service.update(code, request)); + IntegrationAccess access = authorization.require("integration.schedule", "manage"); + return ApiResponse.success(service.update(code, request, access.getTenantId(), access.getActorId())); } @PostMapping("/{code}/execute") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.scheduled-task.execute')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.schedule', 'execute')") public ResponseEntity> execute(@PathVariable String code) { - return ResponseEntity.accepted().body(ApiResponse.success(service.execute(code))); + IntegrationAccess access = authorization.require("integration.schedule", "execute"); + return ResponseEntity.accepted().body(ApiResponse.success( + service.execute(code, access.getTenantId(), access.getActorId()))); } @GetMapping("/{code}/runs") - @PreAuthorize("@permissionChecker.has(authentication, 'page.scheduled-tasks')") + @PreAuthorize("@permissionChecker.check(authentication, 'integration.schedule', 'read')") public ApiResponse> runs(@PathVariable String code, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { - return ApiResponse.success(service.runs(code, page, size)); + IntegrationAccess access = authorization.require("integration.schedule", "read"); + return ApiResponse.success(service.runs(code, page, size, access.getTenantId())); } } diff --git a/src/main/java/com/finance/system/controller/TravelApplicationController.java b/src/main/java/com/finance/system/controller/TravelApplicationController.java new file mode 100644 index 0000000..fbae57e --- /dev/null +++ b/src/main/java/com/finance/system/controller/TravelApplicationController.java @@ -0,0 +1,35 @@ +package com.finance.system.controller; + +import com.finance.system.dto.ApiResponse; +import com.finance.system.dto.TravelApplicationDto; +import com.finance.system.service.TravelApplicationService; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/travel-applications") +@RequiredArgsConstructor +public class TravelApplicationController { + private final TravelApplicationService service; + + @GetMapping("/mine") + @PreAuthorize("@permissionChecker.has(authentication, 'page.travel-applications')") + public ResponseEntity>> mine() { + return ResponseEntity.ok(ApiResponse.success(service.mine(AuditUtil.getCurrentUserId()))); + } + + @GetMapping("/{id}") + @PreAuthorize("@permissionChecker.has(authentication, 'page.travel-applications')") + public ResponseEntity> detail(@PathVariable Long id) { + return ResponseEntity.ok(ApiResponse.success( + service.mineById(AuditUtil.getCurrentUserId(), id))); + } +} diff --git a/src/main/java/com/finance/system/controller/UserGroupController.java b/src/main/java/com/finance/system/controller/UserGroupController.java index 2ee88bc..926ebc8 100644 --- a/src/main/java/com/finance/system/controller/UserGroupController.java +++ b/src/main/java/com/finance/system/controller/UserGroupController.java @@ -22,35 +22,35 @@ public class UserGroupController { private final RoleService roleService; @GetMapping - @PreAuthorize("@permissionChecker.has(authentication, 'page.groups')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group', 'read')") public ResponseEntity>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listGroups())); } @PostMapping - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.create')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group', 'create')") public ResponseEntity>> create(@RequestBody Map body) { SysUserGroup saved = roleService.saveGroup(null, body); return ResponseEntity.status(201).body(ApiResponse.success(roleService.groupDetails(saved.getId()))); } @PutMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.edit')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group', 'update')") public ResponseEntity>> update(@PathVariable Long id, @RequestBody Map body) { roleService.saveGroup(id, body); return ResponseEntity.ok(ApiResponse.success(roleService.groupDetails(id))); } @DeleteMapping("/{id}") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.delete')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group', 'delete')") public ResponseEntity> delete(@PathVariable Long id) { roleService.deleteGroup(id); return ResponseEntity.ok(ApiResponse.success()); } @GetMapping("/{id}/roles") - @PreAuthorize("@permissionChecker.has(authentication, 'page.groups')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.role', 'read')") public ResponseEntity>> roles(@PathVariable Long id) { Map result = new LinkedHashMap<>(); result.put("roleIds", roleService.groupRoleIds(id)); return ResponseEntity.ok(ApiResponse.success(result)); } @PutMapping("/{id}/roles") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.role.bind')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.role', 'manage')") public ResponseEntity> setRoles(@PathVariable Long id, @RequestBody Map body) { roleService.replaceGroupRoles(id, requiredList(body, "roleIds"), requiredList(body, "expectedRoleIds"), AuditUtil.getCurrentUserId()); @@ -58,13 +58,13 @@ public class UserGroupController { } @GetMapping("/{id}/members") - @PreAuthorize("@permissionChecker.has(authentication, 'page.groups')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.member', 'read')") public ResponseEntity>> members(@PathVariable Long id) { return ResponseEntity.ok(ApiResponse.success(roleService.groupMembers(id))); } @PutMapping("/{id}/members") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.member', 'manage')") public ResponseEntity>> setMembers(@PathVariable Long id, @RequestBody Map body) { List userIds = requiredLongList(body, "userIds"); @@ -80,7 +80,7 @@ public class UserGroupController { } @GetMapping("/candidates") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind') || @permissionChecker.has(authentication, 'page.groups') || (#groupId == null && @permissionChecker.has(authentication, 'page.users'))") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.member', 'read')") public ResponseEntity>>> candidates( @RequestParam(value = "groupId", required = false) Long groupId, @RequestParam(value = "q", required = false) String q, @@ -90,7 +90,7 @@ public class UserGroupController { } @GetMapping("/{id}/member-candidates") - @PreAuthorize("@permissionChecker.hasEdit(authentication, 'system.group.member.bind') || @permissionChecker.has(authentication, 'page.groups')") + @PreAuthorize("@permissionChecker.check(authentication, 'iam.group.member', 'read')") public ResponseEntity> memberCandidates( @PathVariable Long id, @RequestParam(value = "q", required = false) String query) { return ResponseEntity.ok(ApiResponse.success(roleService.memberCandidates(id, query))); diff --git a/src/main/java/com/finance/system/dto/PayeeAccountDto.java b/src/main/java/com/finance/system/dto/PayeeAccountDto.java new file mode 100644 index 0000000..d0e1fd0 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PayeeAccountDto.java @@ -0,0 +1,28 @@ +package com.finance.system.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Builder; +import lombok.Value; + +import java.time.LocalDateTime; + +@Value +@Builder +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PayeeAccountDto { + Long id; + Long payeeId; + String payeeType; + Long userId; + String name; + String employeeNo; + String department; + String supplierCreditCode; + String bankName; + String branchName; + String bankAccountMask; + Boolean isDefault; + String status; + Boolean manageable; + LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/dto/PayeeAccountRequest.java b/src/main/java/com/finance/system/dto/PayeeAccountRequest.java new file mode 100644 index 0000000..41d8821 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PayeeAccountRequest.java @@ -0,0 +1,31 @@ +package com.finance.system.dto; + +import lombok.Data; +import lombok.ToString; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +@Data +public class PayeeAccountRequest { + private Long userId; + + @NotBlank(message = "银行名称不能为空") + @Size(max = 200, message = "银行名称不能超过200个字符") + private String bankName; + + @Size(max = 200, message = "支行名称不能超过200个字符") + private String branchName; + + /** Required when creating; blank on update means that the existing number is retained. */ + @ToString.Exclude + @Size(max = 100, message = "银行账号不能超过100个字符") + private String accountNo; + + private Boolean isDefault; + + @NotBlank(message = "账户状态不能为空") + @Pattern(regexp = "(?i)ACTIVE|INACTIVE", message = "账户状态必须为ACTIVE或INACTIVE") + private String status; +} diff --git a/src/main/java/com/finance/system/dto/PayeeInitialAccountRequest.java b/src/main/java/com/finance/system/dto/PayeeInitialAccountRequest.java new file mode 100644 index 0000000..5582db7 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PayeeInitialAccountRequest.java @@ -0,0 +1,22 @@ +package com.finance.system.dto; + +import lombok.Data; +import lombok.ToString; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +public class PayeeInitialAccountRequest { + @NotBlank(message = "银行名称不能为空") + @Size(max = 200, message = "银行名称不能超过200个字符") + private String bankName; + + @Size(max = 200, message = "支行名称不能超过200个字符") + private String branchName; + + @NotBlank(message = "银行账号不能为空") + @Size(max = 100, message = "银行账号不能超过100个字符") + @ToString.Exclude + private String accountNo; +} diff --git a/src/main/java/com/finance/system/dto/PayeeSubjectDto.java b/src/main/java/com/finance/system/dto/PayeeSubjectDto.java new file mode 100644 index 0000000..d2f9ad5 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PayeeSubjectDto.java @@ -0,0 +1,23 @@ +package com.finance.system.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Builder; +import lombok.Value; + +import java.time.LocalDateTime; + +@Value +@Builder +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PayeeSubjectDto { + Long id; + String payeeType; + String displayName; + String employeeOpenId; + String identityNumber; + String supplierCreditCode; + String status; + Integer accountCount; + Boolean manageable; + LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/dto/PayeeSubjectRequest.java b/src/main/java/com/finance/system/dto/PayeeSubjectRequest.java new file mode 100644 index 0000000..542339e --- /dev/null +++ b/src/main/java/com/finance/system/dto/PayeeSubjectRequest.java @@ -0,0 +1,33 @@ +package com.finance.system.dto; + +import lombok.Data; + +import javax.validation.Valid; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +@Data +public class PayeeSubjectRequest { + @NotBlank(message = "付款对象类型不能为空") + @Pattern(regexp = "(?i)EMPLOYEE|SUPPLIER", message = "付款对象类型必须为EMPLOYEE或SUPPLIER") + private String payeeType; + + private String employeeOpenId; + + @Size(max = 18, message = "身份证号不能超过18个字符") + private String identityNumber; + + @Valid + private PayeeInitialAccountRequest initialAccount; + + @Size(max = 200, message = "付款对象名称不能超过200个字符") + private String displayName; + + @Size(max = 18, message = "统一社会信用代码不能超过18个字符") + private String supplierCreditCode; + + @Pattern(regexp = "(?i)ACTIVE|INACTIVE", message = "状态必须为ACTIVE或INACTIVE") + private String status; +} diff --git a/src/main/java/com/finance/system/dto/PayeeUserDto.java b/src/main/java/com/finance/system/dto/PayeeUserDto.java new file mode 100644 index 0000000..e51233d --- /dev/null +++ b/src/main/java/com/finance/system/dto/PayeeUserDto.java @@ -0,0 +1,11 @@ +package com.finance.system.dto; + +import lombok.Builder; +import lombok.Value; + +@Value +@Builder +public class PayeeUserDto { + String openId; + String realName; +} diff --git a/src/main/java/com/finance/system/dto/PaymentDetailDto.java b/src/main/java/com/finance/system/dto/PaymentDetailDto.java index 31bcf97..9f0d242 100644 --- a/src/main/java/com/finance/system/dto/PaymentDetailDto.java +++ b/src/main/java/com/finance/system/dto/PaymentDetailDto.java @@ -1,5 +1,6 @@ package com.finance.system.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,6 +12,7 @@ import java.util.List; @Builder @NoArgsConstructor @AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) public class PaymentDetailDto { private Long id; private String applicationNo; @@ -24,7 +26,9 @@ public class PaymentDetailDto { private String bankName; private String branchName; private String bankAccountMask; - private String accountName; private List paymentHistory; private List approvalRecords; -} \ No newline at end of file + private List availableActions; + private Boolean canVerify; + private Boolean canReject; +} diff --git a/src/main/java/com/finance/system/dto/PaymentRecordDto.java b/src/main/java/com/finance/system/dto/PaymentRecordDto.java index d4f0bcf..9545f7c 100644 --- a/src/main/java/com/finance/system/dto/PaymentRecordDto.java +++ b/src/main/java/com/finance/system/dto/PaymentRecordDto.java @@ -1,18 +1,22 @@ package com.finance.system.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.time.LocalDateTime; +import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) public class PaymentRecordDto { private Long id; + private Long applicationId; private String paymentNo; private BigDecimal paymentAmount; private BigDecimal totalAmount; @@ -24,4 +28,7 @@ public class PaymentRecordDto { private String operatorName; private LocalDateTime paymentTime; private String remark; + private List availableActions; + private Boolean canVerify; + private Boolean canReject; } diff --git a/src/main/java/com/finance/system/dto/PaymentReviewRequest.java b/src/main/java/com/finance/system/dto/PaymentReviewRequest.java new file mode 100644 index 0000000..e19aec2 --- /dev/null +++ b/src/main/java/com/finance/system/dto/PaymentReviewRequest.java @@ -0,0 +1,15 @@ +package com.finance.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +@Data +public class PaymentReviewRequest { + @NotNull + private Long paymentId; + + @Pattern(regexp = "[A-Z0-9_]{1,80}") + private String rejectionCode; +} diff --git a/src/main/java/com/finance/system/dto/PaymentTaskDto.java b/src/main/java/com/finance/system/dto/PaymentTaskDto.java index fa1b122..b68e29d 100644 --- a/src/main/java/com/finance/system/dto/PaymentTaskDto.java +++ b/src/main/java/com/finance/system/dto/PaymentTaskDto.java @@ -1,5 +1,6 @@ package com.finance.system.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -12,8 +13,10 @@ import java.util.List; @Builder @NoArgsConstructor @AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) public class PaymentTaskDto { private Long id; + private Long applicationId; private String applicationNo; private String title; private String payeeName; @@ -29,4 +32,7 @@ public class PaymentTaskDto { private String bankAccountMask; private LocalDateTime submitTime; private LocalDateTime createdAt; -} \ No newline at end of file + private List availableActions; + private Boolean canVerify; + private Boolean canReject; +} diff --git a/src/main/java/com/finance/system/dto/ReimApplicationDetail.java b/src/main/java/com/finance/system/dto/ReimApplicationDetail.java index c55d685..741e954 100644 --- a/src/main/java/com/finance/system/dto/ReimApplicationDetail.java +++ b/src/main/java/com/finance/system/dto/ReimApplicationDetail.java @@ -1,5 +1,7 @@ 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; @@ -14,6 +16,7 @@ import java.util.Map; @Builder @NoArgsConstructor @AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) public class ReimApplicationDetail { private Long id; private String applicationNo; @@ -42,6 +45,7 @@ public class ReimApplicationDetail { private LocalDate sourceDocDate; private String sourceStatus; private String payeeName; + @JsonIgnore private Long payeeBankId; private String bankName; private String bankAccountMask; @@ -56,6 +60,7 @@ public class ReimApplicationDetail { private List approvalRecords; private List payments; private FormSnapshot formSnapshot; + private List availableActions; @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class FormSnapshot { diff --git a/src/main/java/com/finance/system/dto/ReimApplicationSummary.java b/src/main/java/com/finance/system/dto/ReimApplicationSummary.java index c4d6fb8..e6ed21b 100644 --- a/src/main/java/com/finance/system/dto/ReimApplicationSummary.java +++ b/src/main/java/com/finance/system/dto/ReimApplicationSummary.java @@ -1,5 +1,6 @@ package com.finance.system.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,6 +12,7 @@ import java.time.LocalDateTime; @Builder @NoArgsConstructor @AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) public class ReimApplicationSummary { private Long id; private String applicationNo; @@ -31,4 +33,5 @@ public class ReimApplicationSummary { private String returnReason; private LocalDateTime submitTime; private LocalDateTime createdAt; -} \ No newline at end of file + private java.util.List availableActions; +} diff --git a/src/main/java/com/finance/system/dto/TransferApprovalRequest.java b/src/main/java/com/finance/system/dto/TransferApprovalRequest.java new file mode 100644 index 0000000..c40f563 --- /dev/null +++ b/src/main/java/com/finance/system/dto/TransferApprovalRequest.java @@ -0,0 +1,14 @@ +package com.finance.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; + +@Data +public class TransferApprovalRequest { + @NotNull + private Long applicationId; + @NotNull + private Long targetApproverId; + private String comment; +} diff --git a/src/main/java/com/finance/system/dto/TravelApplicationDto.java b/src/main/java/com/finance/system/dto/TravelApplicationDto.java new file mode 100644 index 0000000..5c09217 --- /dev/null +++ b/src/main/java/com/finance/system/dto/TravelApplicationDto.java @@ -0,0 +1,31 @@ +package com.finance.system.dto; + +import lombok.Builder; +import lombok.Value; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +@Value +@Builder +public class TravelApplicationDto { + Long id; + String travelRequestNo; + String approvalInstanceId; + String applicant; + String applicantCode; + List travelerCodes; + List travelers; + String entity; + String department; + String destination; + String purpose; + LocalDate startDate; + LocalDate endDate; + BigDecimal estimate; + String status; + String approvalSystem; + LocalDateTime syncedAt; +} diff --git a/src/main/java/com/finance/system/dto/UserProfile.java b/src/main/java/com/finance/system/dto/UserProfile.java index 89471ab..7967049 100644 --- a/src/main/java/com/finance/system/dto/UserProfile.java +++ b/src/main/java/com/finance/system/dto/UserProfile.java @@ -15,6 +15,7 @@ public class UserProfile { private Long id; private String employeeNo; private String realName; + private String feishuOpenId; private String avatarUrl; private String email; private String departmentName; diff --git a/src/main/java/com/finance/system/entity/FeishuTravelApplication.java b/src/main/java/com/finance/system/entity/FeishuTravelApplication.java new file mode 100644 index 0000000..70057e4 --- /dev/null +++ b/src/main/java/com/finance/system/entity/FeishuTravelApplication.java @@ -0,0 +1,48 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "int_feishu_travel_application") +public class FeishuTravelApplication { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "tenant_id", nullable = false, length = 64) private String tenantId; + @Column(name = "travel_request_no", nullable = false, length = 50) private String travelRequestNo; + @Column(name = "approval_instance_id", nullable = false, length = 100) private String approvalInstanceId; + @Column(name = "applicant_user_id", nullable = false) private Long applicantUserId; + @Column(name = "applicant_name", nullable = false, length = 200) private String applicantName; + @Column(name = "applicant_code", length = 50) private String applicantCode; + @Column(name = "traveler_codes", columnDefinition = "TEXT") private String travelerCodes; + @Column(name = "traveler_names", columnDefinition = "TEXT") private String travelerNames; + @Column(name = "legal_entity", length = 200) private String legalEntity; + @Column(name = "department", length = 200) private String department; + @Column(length = 500) private String destination; + @Column(length = 1000) private String purpose; + @Column(name = "start_date") private LocalDate startDate; + @Column(name = "end_date") private LocalDate endDate; + @Column(name = "estimated_amount", precision = 18, scale = 2) private BigDecimal estimatedAmount; + @Column(nullable = false, length = 50) private String status; + @Column(name = "approval_system", nullable = false, length = 50) private String approvalSystem; + @Column(name = "source_payload", columnDefinition = "MEDIUMTEXT") private String sourcePayload; + @Column(name = "synced_at", nullable = false) private LocalDateTime syncedAt; + @Column(name = "created_at", nullable = false) private LocalDateTime createdAt; + @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/finance/system/entity/FileStorageCleanupTask.java b/src/main/java/com/finance/system/entity/FileStorageCleanupTask.java new file mode 100644 index 0000000..0f6c1a2 --- /dev/null +++ b/src/main/java/com/finance/system/entity/FileStorageCleanupTask.java @@ -0,0 +1,79 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import java.time.LocalDateTime; +import java.time.ZoneId; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_file_storage_cleanup_task") +public class FileStorageCleanupTask { + private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai"); + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "attachment_id") + private Long attachmentId; + + @Column(name = "storage_provider", length = 30, nullable = false) + private String storageProvider; + + @Column(name = "storage_object_key", length = 500, nullable = false) + private String storageObjectKey; + + @Column(name = "cleanup_reason", length = 100, nullable = false) + private String cleanupReason; + + @Column(name = "task_status", length = 20, nullable = false) + private String taskStatus; + + @Column(name = "attempt_count", nullable = false) + private Integer attemptCount; + + @Column(name = "next_attempt_at", nullable = false) + private LocalDateTime nextAttemptAt; + + @Column(name = "last_error", length = 500) + private String lastError; + + @Column(name = "completed_at") + private LocalDateTime completedAt; + + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + LocalDateTime now = LocalDateTime.now(SHANGHAI); + if (taskStatus == null) taskStatus = "PENDING"; + if (attemptCount == null) attemptCount = 0; + if (nextAttemptAt == null) nextAttemptAt = now; + if (createdAt == null) createdAt = now; + updatedAt = now; + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(SHANGHAI); + } +} diff --git a/src/main/java/com/finance/system/entity/IntFeishuApproval.java b/src/main/java/com/finance/system/entity/IntFeishuApproval.java index d5466dd..ce5210e 100644 --- a/src/main/java/com/finance/system/entity/IntFeishuApproval.java +++ b/src/main/java/com/finance/system/entity/IntFeishuApproval.java @@ -18,20 +18,6 @@ import java.time.LocalDateTime; @Table(name = "int_feishu_approval") public class IntFeishuApproval { - /** Compatibility constructor retained for existing service callers. */ - public IntFeishuApproval(Long id, Long applicationId, String feishuInstanceCode, - String feishuApprovalCode, String status, String callbackData, - LocalDateTime syncedAt, LocalDateTime createdAt) { - this.id = id; - this.applicationId = applicationId; - this.feishuInstanceCode = feishuInstanceCode; - this.feishuApprovalCode = feishuApprovalCode; - this.status = status; - this.callbackData = callbackData; - this.syncedAt = syncedAt; - this.createdAt = createdAt; - } - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -52,10 +38,6 @@ public class IntFeishuApproval { @Column(name = "status", length = 30) private String status = "PENDING"; - /** 回调数据(原始JSON) */ - @Column(name = "callback_data", columnDefinition = "TEXT") - private String callbackData; - /** 最后同步时间 */ @Column(name = "synced_at") private LocalDateTime syncedAt; diff --git a/src/main/java/com/finance/system/entity/ReimApplication.java b/src/main/java/com/finance/system/entity/ReimApplication.java index 5f80c59..602259c 100644 --- a/src/main/java/com/finance/system/entity/ReimApplication.java +++ b/src/main/java/com/finance/system/entity/ReimApplication.java @@ -25,6 +25,9 @@ public class ReimApplication { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(name = "tenant_id", length = 64, nullable = false) + private String tenantId; + @Column(name = "application_no", length = 50, nullable = false, unique = true) private String applicationNo; @@ -64,6 +67,12 @@ public class ReimApplication { @Column(name = "receipt_status", length = 30) private String receiptStatus; + @Column(name = "received_by") + private Long receivedBy; + + @Column(name = "received_at") + private LocalDateTime receivedAt; + @Column(name = "payment_status", length = 30) private String paymentStatus; diff --git a/src/main/java/com/finance/system/entity/ReimApprovalRecord.java b/src/main/java/com/finance/system/entity/ReimApprovalRecord.java index 4c51c5f..9c2386a 100644 --- a/src/main/java/com/finance/system/entity/ReimApprovalRecord.java +++ b/src/main/java/com/finance/system/entity/ReimApprovalRecord.java @@ -35,9 +35,6 @@ public class ReimApprovalRecord { @Column(columnDefinition = "TEXT") private String comment; - @Column(length = 500) - private String signature; - @Column(name = "action_time") private LocalDateTime actionTime; diff --git a/src/main/java/com/finance/system/entity/ReimAttachment.java b/src/main/java/com/finance/system/entity/ReimAttachment.java index 7cbbca3..96f11b9 100644 --- a/src/main/java/com/finance/system/entity/ReimAttachment.java +++ b/src/main/java/com/finance/system/entity/ReimAttachment.java @@ -37,6 +37,12 @@ public class ReimAttachment { @Column(name = "file_url", length = 500) private String fileUrl; + @Column(name = "storage_provider", length = 30) + private String storageProvider; + + @Column(name = "storage_object_key", length = 500) + private String storageObjectKey; + @Column(name = "file_size") private Long fileSize; @@ -52,7 +58,7 @@ public class ReimAttachment { @Column(name = "form_fingerprint", length = 64, nullable = false) private String formFingerprint; - @Column(name = "feishu_file_code", length = 500, nullable = false) + @Column(name = "feishu_file_code", length = 500) private String feishuFileCode; @Column(name = "upload_status", length = 30, nullable = false) diff --git a/src/main/java/com/finance/system/entity/ReimInvoice.java b/src/main/java/com/finance/system/entity/ReimInvoice.java index dda21fc..2abec91 100644 --- a/src/main/java/com/finance/system/entity/ReimInvoice.java +++ b/src/main/java/com/finance/system/entity/ReimInvoice.java @@ -43,9 +43,6 @@ public class ReimInvoice { @Column(precision = 18, scale = 2) private BigDecimal amount; - @Column(name = "tax_amount", precision = 18, scale = 2) - private BigDecimal taxAmount; - @Column(name = "seller_name", length = 500) private String sellerName; @@ -55,9 +52,6 @@ public class ReimInvoice { @Column(name = "file_url", length = 500) private String fileUrl; - @Column(name = "ocr_result", columnDefinition = "TEXT") - private String ocrResult; - @Column(name = "verify_status", length = 30) private String verifyStatus; diff --git a/src/main/java/com/finance/system/entity/ReimPayment.java b/src/main/java/com/finance/system/entity/ReimPayment.java index aa30665..32eab83 100644 --- a/src/main/java/com/finance/system/entity/ReimPayment.java +++ b/src/main/java/com/finance/system/entity/ReimPayment.java @@ -1,10 +1,12 @@ package com.finance.system.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.ToString; import java.math.BigDecimal; import java.time.LocalDateTime; @@ -21,6 +23,9 @@ public class ReimPayment { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(name = "tenant_id", length = 64, nullable = false) + private String tenantId; + @Column(name = "payment_no", length = 50, nullable = false, unique = true) private String paymentNo; @@ -49,6 +54,8 @@ public class ReimPayment { private String paymentMethod; @Column(name = "bank_account_no", length = 100) + @JsonIgnore + @ToString.Exclude private String bankAccountNo; @Column(name = "bank_account_name", length = 200) @@ -60,12 +67,27 @@ public class ReimPayment { @Column(name = "operator_id", nullable = false) private Long operatorId; + @Column(name = "maker_id", nullable = false) + private Long makerId; + + @Column(name = "checker_id") + private Long checkerId; + @Column(name = "payment_status", length = 30) private String paymentStatus; @Column(name = "payment_time") private LocalDateTime paymentTime; + @Column(name = "verified_at") + private LocalDateTime verifiedAt; + + @Column(name = "rejected_at") + private LocalDateTime rejectedAt; + + @Column(name = "rejection_code", length = 80) + private String rejectionCode; + @Column(name = "idempotency_key", length = 100, unique = true) private String idempotencyKey; diff --git a/src/main/java/com/finance/system/entity/SysApiAccessLog.java b/src/main/java/com/finance/system/entity/SysApiAccessLog.java index afdf4a8..9b39dad 100644 --- a/src/main/java/com/finance/system/entity/SysApiAccessLog.java +++ b/src/main/java/com/finance/system/entity/SysApiAccessLog.java @@ -7,6 +7,7 @@ import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDateTime; +import java.time.ZoneOffset; @Data @Builder @@ -22,12 +23,30 @@ public class SysApiAccessLog { @Column(name = "request_id", length = 64) private String requestId; + @Column(name = "client_request_id", length = 64) + private String clientRequestId; + + @Column(name = "trace_id", length = 32) + private String traceId; + + @Column(name = "span_id", length = 16) + private String spanId; + + @Column(name = "tenant_id", length = 64) + private String tenantId; + + @Column(name = "organization_id", nullable = false) + private Long organizationId; + @Column(name = "http_method", nullable = false, length = 16) private String httpMethod; @Column(name = "request_path", nullable = false, length = 500) private String requestPath; + @Column(name = "request_route", length = 500) + private String requestRoute; + @Column(name = "query_string", length = 1000) private String queryString; @@ -55,13 +74,19 @@ public class SysApiAccessLog { @Column(name = "error_message", length = 1000) private String errorMessage; + @Column(nullable = false, length = 16) + private String outcome; + + @Column(name = "error_code", length = 80) + private String errorCode; + @Column(name = "created_at", nullable = false) private LocalDateTime createdAt; @PrePersist protected void onCreate() { if (createdAt == null) { - createdAt = LocalDateTime.now(); + createdAt = LocalDateTime.now(ZoneOffset.UTC); } } } diff --git a/src/main/java/com/finance/system/entity/SysBankAccount.java b/src/main/java/com/finance/system/entity/SysBankAccount.java index 866f619..4ebdfdf 100644 --- a/src/main/java/com/finance/system/entity/SysBankAccount.java +++ b/src/main/java/com/finance/system/entity/SysBankAccount.java @@ -1,10 +1,12 @@ package com.finance.system.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.ToString; import java.math.BigDecimal; import java.time.LocalDateTime; @@ -21,23 +23,39 @@ public class SysBankAccount { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column(name = "user_id", nullable = false) + @Column(name = "user_id") private Long userId; + @Column(name = "payee_id") + private Long payeeId; + @Column(name = "bank_name", length = 200, nullable = false) private String bankName; @Column(name = "branch_name", length = 200) private String branchName; - @Column(name = "account_no", length = 100, nullable = false) + /** Transitional legacy column. New writes always leave it null. */ + @Column(name = "account_no", length = 100) + @JsonIgnore + @ToString.Exclude private String accountNo; + @Column(name = "account_no_ciphertext", columnDefinition = "TEXT") + @JsonIgnore + @ToString.Exclude + private String accountNoCiphertext; + @Column(name = "account_no_mask", length = 50) private String accountNoMask; - @Column(name = "account_name", length = 200, nullable = false) - private String accountName; + @Column(name = "account_fingerprint", length = 64) + @JsonIgnore + @ToString.Exclude + private String accountFingerprint; + + @Column(name = "encryption_key_version", length = 32) + private String encryptionKeyVersion; @Column(name = "is_default") private Boolean isDefault; diff --git a/src/main/java/com/finance/system/entity/SysBudget.java b/src/main/java/com/finance/system/entity/SysBudget.java deleted file mode 100644 index ccebaa6..0000000 --- a/src/main/java/com/finance/system/entity/SysBudget.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.finance.system.entity; - -import javax.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -@Entity -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Table(name = "sys_budget") -public class SysBudget { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column(name = "dept_id", nullable = false) - private Long deptId; - - @Column(name = "expense_type_id", nullable = false) - private Long expenseTypeId; - - @Column(name = "fiscal_year", nullable = false) - private Integer fiscalYear; - - @Column(name = "fiscal_month") - private Integer fiscalMonth; - - @Column(name = "total_amount", nullable = false, precision = 18, scale = 2) - private BigDecimal totalAmount; - - @Column(name = "used_amount", nullable = false, precision = 18, scale = 2) - private BigDecimal usedAmount; - - @Column(name = "frozen_amount", nullable = false, precision = 18, scale = 2) - private BigDecimal frozenAmount; - - @Column(length = 20) - private String status; - - @Column(name = "created_at") - private LocalDateTime createdAt; - - @Column(name = "updated_at") - private LocalDateTime updatedAt; - - @PrePersist - protected void onCreate() { - createdAt = LocalDateTime.now(); - updatedAt = LocalDateTime.now(); - } - - @PreUpdate - protected void onUpdate() { - updatedAt = LocalDateTime.now(); - } -} diff --git a/src/main/java/com/finance/system/entity/SysExpenseType.java b/src/main/java/com/finance/system/entity/SysExpenseType.java index 1cc9211..0f5c105 100644 --- a/src/main/java/com/finance/system/entity/SysExpenseType.java +++ b/src/main/java/com/finance/system/entity/SysExpenseType.java @@ -38,9 +38,6 @@ public class SysExpenseType { @Column(length = 20) private String status; - @Column(name = "kingdee_form_id", length = 100) - private String kingdeeFormId; - @Column(name = "created_at") private LocalDateTime createdAt; diff --git a/src/main/java/com/finance/system/entity/SysIntegrationConfig.java b/src/main/java/com/finance/system/entity/SysIntegrationConfig.java index 4c8d823..f559e5c 100644 --- a/src/main/java/com/finance/system/entity/SysIntegrationConfig.java +++ b/src/main/java/com/finance/system/entity/SysIntegrationConfig.java @@ -10,9 +10,11 @@ import java.time.LocalDateTime; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity -@Table(name = "sys_integration_config", uniqueConstraints = @UniqueConstraint(columnNames = {"provider", "config_key"})) +@Table(name = "sys_integration_config", uniqueConstraints = @UniqueConstraint( + columnNames = {"tenant_id", "provider", "config_key"})) public class SysIntegrationConfig { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(name = "tenant_id", nullable = false, length = 64) private String tenantId; @Column(nullable = false, length = 20) private String provider; @Column(name = "config_key", nullable = false, length = 80) private String configKey; @Column(name = "config_value", length = 2000) private String configValue; diff --git a/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java b/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java index 3cf6808..eaba09a 100644 --- a/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java +++ b/src/main/java/com/finance/system/entity/SysKingdeeSyncConfig.java @@ -20,17 +20,21 @@ import java.time.LocalDateTime; @NoArgsConstructor @AllArgsConstructor @Entity -@Table(name = "sys_kingdee_sync_config") +@Table(name = "sys_kingdee_sync_config", uniqueConstraints = @javax.persistence.UniqueConstraint( + columnNames = {"tenant_id", "target_table_name"})) public class SysKingdeeSyncConfig { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(name = "tenant_id", nullable = false, length = 64) + private String tenantId; + @Column(name = "config_name", nullable = false, length = 200) private String configName; @Column(name = "form_id", nullable = false, length = 120) private String formId; - @Column(name = "target_table_name", nullable = false, unique = true, length = 63) + @Column(name = "target_table_name", nullable = false, length = 63) private String targetTableName; @Column(name = "target_table_comment", length = 500) private String targetTableComment; diff --git a/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java b/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java index fbeeb79..3a55c87 100644 --- a/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java +++ b/src/main/java/com/finance/system/entity/SysKingdeeSyncRun.java @@ -24,7 +24,9 @@ import java.time.LocalDateTime; public class SysKingdeeSyncRun { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(name = "tenant_id", nullable = false, length = 64) private String tenantId; @Column(name = "config_id", nullable = false) private Long configId; + @Column(name = "initiated_by") private Long initiatedBy; @Column(nullable = false, length = 20) private String status; @Column(name = "filter_string", length = 4000) private String filterString; @Column(name = "fetched_count", nullable = false) private Integer fetchedCount; diff --git a/src/main/java/com/finance/system/entity/SysPayee.java b/src/main/java/com/finance/system/entity/SysPayee.java new file mode 100644 index 0000000..192115d --- /dev/null +++ b/src/main/java/com/finance/system/entity/SysPayee.java @@ -0,0 +1,70 @@ +package com.finance.system.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "sys_payee") +public class SysPayee { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "tenant_id", nullable = false, length = 64) + private String tenantId; + + @Column(name = "organization_id", nullable = false) + private Long organizationId; + + @Column(name = "payee_type", nullable = false, length = 20) + private String payeeType; + + @Column(name = "display_name", nullable = false, length = 200) + private String displayName; + + @Column(name = "employee_user_id") + private Long employeeUserId; + + @Column(name = "employee_open_id", length = 128) + private String employeeOpenId; + + @Column(name = "supplier_credit_code", length = 18) + private String supplierCreditCode; + + @Column(nullable = false, length = 20) + private String status; + + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; + + @PrePersist + void createTimestamps() { + LocalDateTime now = LocalDateTime.now(); + createdAt = now; + updatedAt = now; + } + + @PreUpdate + void updateTimestamp() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/finance/system/entity/SysPermission.java b/src/main/java/com/finance/system/entity/SysPermission.java index 1005ed8..91e89ef 100644 --- a/src/main/java/com/finance/system/entity/SysPermission.java +++ b/src/main/java/com/finance/system/entity/SysPermission.java @@ -26,17 +26,31 @@ public class SysPermission { private String permissionType; @Column(name = "parent_code", length = 120) private String parentCode; + @Column(name = "permission_layer", nullable = false, length = 20) + private String permissionLayer; + @Column(name = "sort_order", nullable = false) + private Integer sortOrder; @Column(length = 200) private String resource; @Column(name = "default_access", length = 20) private String defaultAccess; + @Column(nullable = false) + private Boolean delegable; + @Column(name = "risk_level", nullable = false, length = 16) + private String riskLevel; @Column(name = "created_at") private LocalDateTime createdAt; @Column(name = "updated_at") private LocalDateTime updatedAt; @PrePersist - protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } + protected void onCreate() { + if (delegable == null) delegable = true; + if (riskLevel == null) riskLevel = "NORMAL"; + if (permissionLayer == null) permissionLayer = "COMPAT"; + if (sortOrder == null) sortOrder = 0; + createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); + } @PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); } } diff --git a/src/main/java/com/finance/system/entity/SysRole.java b/src/main/java/com/finance/system/entity/SysRole.java index 2b82e24..e1031f1 100644 --- a/src/main/java/com/finance/system/entity/SysRole.java +++ b/src/main/java/com/finance/system/entity/SysRole.java @@ -29,13 +29,19 @@ public class SysRole { private String status; @Column(name = "built_in", nullable = false) private Boolean builtIn; + /** 10=normal, 80=administrator, 100=super administrator. */ + @Column(name = "privilege_tier", nullable = false) + private Integer privilegeTier; @Column(name = "created_at") private LocalDateTime createdAt; @Column(name = "updated_at") private LocalDateTime updatedAt; @PrePersist - protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } + protected void onCreate() { + if (privilegeTier == null) privilegeTier = 10; + createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); + } @PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); } } diff --git a/src/main/java/com/finance/system/entity/SysUser.java b/src/main/java/com/finance/system/entity/SysUser.java index a9f9fda..a21f461 100644 --- a/src/main/java/com/finance/system/entity/SysUser.java +++ b/src/main/java/com/finance/system/entity/SysUser.java @@ -1,10 +1,12 @@ package com.finance.system.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.ToString; import java.time.LocalDateTime; @@ -33,6 +35,11 @@ public class SysUser { @Column(name = "real_name", length = 100, nullable = false) private String realName; + @Column(name = "identity_number", length = 18) + @JsonIgnore + @ToString.Exclude + private String identityNumber; + @Column(name = "avatar_url", length = 500) private String avatarUrl; @@ -42,6 +49,14 @@ public class SysUser { @Column(length = 20) private String mobile; + @Builder.Default + @Column(name = "tenant_id", nullable = false, length = 64) + private String tenantId = "default"; + + @Builder.Default + @Column(name = "organization_id", nullable = false) + private Long organizationId = 1L; + @Column(name = "department_id") private Long departmentId; @@ -79,6 +94,7 @@ public class SysUser { @PrePersist protected void onCreate() { + if (tenantId == null || tenantId.trim().isEmpty()) tenantId = "default"; createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); } diff --git a/src/main/java/com/finance/system/entity/SysUserKingdeeAccount.java b/src/main/java/com/finance/system/entity/SysUserKingdeeAccount.java index 498cf13..c0377e0 100644 --- a/src/main/java/com/finance/system/entity/SysUserKingdeeAccount.java +++ b/src/main/java/com/finance/system/entity/SysUserKingdeeAccount.java @@ -13,14 +13,21 @@ import java.time.LocalDateTime; @NoArgsConstructor @AllArgsConstructor @Entity -@Table(name = "sys_user_kingdee_account") +@Table(name = "sys_user_kingdee_account", uniqueConstraints = @UniqueConstraint( + columnNames = {"tenant_id", "kingdee_username"})) public class SysUserKingdeeAccount { @Id @Column(name = "user_id") private Long userId; - @Column(name = "kingdee_username", nullable = false, length = 120, unique = true) + @Column(name = "employee_open_id", length = 128) + private String employeeOpenId; + + @Column(name = "tenant_id", nullable = false, length = 64) + private String tenantId; + + @Column(name = "kingdee_username", nullable = false, length = 120) private String kingdeeUsername; /** Encrypted with IntegrationConfigCrypto; never log or return to clients. */ diff --git a/src/main/java/com/finance/system/enums/UserType.java b/src/main/java/com/finance/system/enums/UserType.java deleted file mode 100644 index ffbdd87..0000000 --- a/src/main/java/com/finance/system/enums/UserType.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.finance.system.enums; - -public enum UserType { - EMPLOYEE, - FINANCE, - ADMIN -} \ No newline at end of file diff --git a/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java b/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java index b64604b..98ca582 100644 --- a/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/finance/system/exception/GlobalExceptionHandler.java @@ -6,6 +6,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.validation.FieldError; +import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @@ -69,6 +70,12 @@ public class GlobalExceptionHandler { .body(ApiResponse.error(400, "参数校验失败", errors)); } + @ExceptionHandler(BindException.class) + public ResponseEntity> handleBind(BindException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(400, "查询参数格式不正确")); + } + @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity> handleUnreadableBody(HttpMessageNotReadableException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) @@ -77,7 +84,7 @@ public class GlobalExceptionHandler { @ExceptionHandler(DataIntegrityViolationException.class) public ResponseEntity> handleDataIntegrityViolation(DataIntegrityViolationException e) { - log.warn("Database constraint conflict"); + log.warn("数据库约束冲突"); return ResponseEntity.status(HttpStatus.CONFLICT) .body(ApiResponse.error(409, "数据冲突,请刷新后重试")); } @@ -90,7 +97,7 @@ public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity> handleGeneral(Exception e) { - log.error("Unexpected error", e); + log.error("发生未预期的错误", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ApiResponse.error(500, "服务器内部错误")); } diff --git a/src/main/java/com/finance/system/finance/audit/FinanceAuditEvents.java b/src/main/java/com/finance/system/finance/audit/FinanceAuditEvents.java new file mode 100644 index 0000000..4eec822 --- /dev/null +++ b/src/main/java/com/finance/system/finance/audit/FinanceAuditEvents.java @@ -0,0 +1,65 @@ +package com.finance.system.finance.audit; + +import com.finance.system.audit.AuditEventCommand; +import com.finance.system.audit.AuditPort; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Instant; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class FinanceAuditEvents { + private final AuditPort auditPort; + + @Value("${observability.tenant-id:default}") + private String tenantId; + + public void business(String action, Long actorId, String resourceType, Object resourceId, + String statusCode, BigDecimal amount, Map extraChanges) { + Map changes = new LinkedHashMap<>(); + if (statusCode != null) changes.put("statusCode", statusCode); + if (amount != null) changes.put("amountMinor", amount.movePointRight(2) + .setScale(0, RoundingMode.UNNECESSARY).longValueExact()); + if (extraChanges != null) changes.putAll(extraChanges); + emit("BUSINESS", action, "SUCCESS", null, actorId, resourceType, resourceId, changes, + Collections.emptyMap()); + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void sodDenied(Long actorId, String resourceType, Object resourceId, + String operationCode, String relatedDuty) { + Map attributes = new LinkedHashMap<>(); + attributes.put("operationCode", operationCode); + attributes.put("relatedDuty", relatedDuty); + emit("SECURITY", "finance.sod.denied", "DENIED", "SOD_CONFLICT", actorId, + resourceType, resourceId, Collections.emptyMap(), attributes); + } + + private void emit(String category, String action, String outcome, String reasonCode, + Long actorId, String resourceType, Object resourceId, + Map changes, Map attributes) { + auditPort.emit(AuditEventCommand.builder() + .eventId(UUID.randomUUID().toString().replace("-", "")) + .schemaVersion(1).eventTime(Instant.now()) + .tenantId(safeTenant()).category(category).action(action).outcome(outcome) + .reasonCode(reasonCode).actorType("USER").actorId(actorId) + .resourceType(resourceType).resourceId(String.valueOf(resourceId)) + .requestId(MDC.get("request_id")).traceId(MDC.get("trace_id")).spanId(MDC.get("span_id")) + .source("WEB").changes(changes).attributes(attributes).build()); + } + + private String safeTenant() { + return tenantId != null && tenantId.matches("[A-Za-z0-9._-]{1,64}") ? tenantId : "default"; + } +} diff --git a/src/main/java/com/finance/system/finance/audit/FinanceAuditSchemaContributor.java b/src/main/java/com/finance/system/finance/audit/FinanceAuditSchemaContributor.java new file mode 100644 index 0000000..3b5f9df --- /dev/null +++ b/src/main/java/com/finance/system/finance/audit/FinanceAuditSchemaContributor.java @@ -0,0 +1,79 @@ +package com.finance.system.finance.audit; + +import com.finance.system.audit.AuditEventSchemaContributor; +import com.finance.system.audit.AuditEventSchemaRegistry; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collection; + +import static com.finance.system.audit.AuditEventSchemaRegistry.code; +import static com.finance.system.audit.AuditEventSchemaRegistry.codeList; +import static com.finance.system.audit.AuditEventSchemaRegistry.fields; +import static com.finance.system.audit.AuditEventSchemaRegistry.integer; +import static com.finance.system.audit.AuditEventSchemaRegistry.none; +import static com.finance.system.audit.AuditEventSchemaRegistry.schema; + +@Component +public class FinanceAuditSchemaContributor implements AuditEventSchemaContributor { + @Override + public Collection schemas() { + return Arrays.asList( + schema("BUSINESS", "reimbursement.application.create", 1, + fields("statusCode", code(40), "amountMinor", integer(0, 999999999999L)), none()), + schema("BUSINESS", "reimbursement.application.update", 1, + fields("statusCode", code(40), "amountMinor", integer(0, 999999999999L), + "changedFieldCodes", codeList(64, 80)), none()), + schema("BUSINESS", "reimbursement.application.submit", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "reimbursement.application.delete", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "reimbursement.attachment.upload", 1, none(), none()), + schema("BUSINESS", "reimbursement.attachment.delete", 1, none(), none()), + schema("BUSINESS", "finance.approval.approve", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "finance.approval.reject", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "finance.approval.transfer", 1, + fields("statusCode", code(40), "targetActorId", integer(1, Long.MAX_VALUE)), none()), + schema("BUSINESS", "finance.receipt.receive", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "finance.payment.register", 1, + fields("statusCode", code(40), "amountMinor", integer(1, 999999999999L)), none()), + schema("BUSINESS", "finance.payment.verify", 1, + fields("statusCode", code(40), "amountMinor", integer(1, 999999999999L)), none()), + schema("BUSINESS", "finance.payment.reject", 1, + fields("statusCode", code(40), "rejectionCode", code(80)), none()), + payeeMutationSchema("payee.subject.create"), + payeeMutationSchema("payee.subject.update"), + payeeMutationSchema("payee.subject.deactivate"), + payeeMutationSchema("payee.account.create"), + payeeMutationSchema("payee.account.update"), + payeeMutationSchema("payee.account.set-default"), + payeeMutationSchema("payee.account.deactivate"), + schema("BUSINESS", "business.config.legal-entity.create", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.cost-center.create", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.payment-method.create", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.payment-account.create", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.master.status-change", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.budget-subject.create", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.budget-subject.status-change", 1, + fields("statusCode", code(40)), none()), + schema("BUSINESS", "business.config.budget-adjustment.request", 1, + fields("statusCode", code(40), "amountMinor", integer(1, 999999999999L)), none()), + schema("SECURITY", "finance.sod.denied", 1, none(), + fields("operationCode", code(80), "relatedDuty", code(80))) + ); + } + + private AuditEventSchemaRegistry.Schema payeeMutationSchema(String action) { + return schema("BUSINESS", action, 1, + fields("statusCode", code(40), "changedFields", codeList(16, 80)), none()); + } +} diff --git a/src/main/java/com/finance/system/finance/rules/FinancialBusinessRules.java b/src/main/java/com/finance/system/finance/rules/FinancialBusinessRules.java new file mode 100644 index 0000000..8c4b2ad --- /dev/null +++ b/src/main/java/com/finance/system/finance/rules/FinancialBusinessRules.java @@ -0,0 +1,58 @@ +package com.finance.system.finance.rules; + +import com.finance.system.exception.BadRequestException; +import java.math.BigDecimal; + +/** Application mirrors of the financial database CHECK constraints. */ +public final class FinancialBusinessRules { + private FinancialBusinessRules() { } + + public static void payee(String type, Long employeeUserId, String supplierCreditCode) { + boolean employee = "EMPLOYEE".equals(type); + boolean supplier = "SUPPLIER".equals(type); + require(employee || supplier, "付款对象类型不正确"); + require(employee ? employeeUserId != null && supplierCreditCode == null + : employeeUserId == null && supplierCreditCode != null, + "付款对象类型与员工、供应商身份必须匹配且互斥"); + } + + public static void currency(Integer decimalPlaces, BigDecimal exchangeRate) { + require(decimalPlaces != null && decimalPlaces >= 0 && decimalPlaces <= 8, + "币种小数位必须介于0和8"); + require(exchangeRate != null && exchangeRate.signum() > 0, "汇率必须大于0"); + } + + public static void budget(Integer fiscalYear, BigDecimal total, BigDecimal occupied, BigDecimal used) { + fiscalYear(fiscalYear); + amounts(total, occupied, used); + } + + public static void subject(Integer level) { + require(level != null && (level == 1 || level == 2), "预算科目层级必须为1或2"); + } + + public static void ledger(Integer fiscalYear, BigDecimal limit, BigDecimal occupied, BigDecimal executed) { + fiscalYear(fiscalYear); + amounts(limit, occupied, executed); + } + + public static void adjustment(String direction, BigDecimal amount) { + require("INCREASE".equals(direction) || "DECREASE".equals(direction), "调整方向不正确"); + require(amount != null && amount.signum() > 0, "调整额必须大于0"); + } + + public static void fiscalYear(Integer year) { + require(year != null && year >= 2000 && year <= 2100, "年度必须介于2000和2100"); + } + + private static void amounts(BigDecimal total, BigDecimal occupied, BigDecimal used) { + require(total != null && occupied != null && used != null, "预算金额不能为空"); + require(total.signum() >= 0 && occupied.signum() >= 0 && used.signum() >= 0, + "预算金额不能为负数"); + require(occupied.add(used).compareTo(total) <= 0, "预算额度不能低于已占用与已执行金额之和"); + } + + private static void require(boolean valid, String message) { + if (!valid) throw new BadRequestException(message); + } +} diff --git a/src/main/java/com/finance/system/integration/audit/IntegrationAuditEvents.java b/src/main/java/com/finance/system/integration/audit/IntegrationAuditEvents.java new file mode 100644 index 0000000..f1799ed --- /dev/null +++ b/src/main/java/com/finance/system/integration/audit/IntegrationAuditEvents.java @@ -0,0 +1,102 @@ +package com.finance.system.integration.audit; + +import com.finance.system.audit.AuditEventCommand; +import com.finance.system.audit.AuditPort; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +/** Emits only stable codes and identifiers; configuration values and exception text are forbidden. */ +@Component +@RequiredArgsConstructor +public class IntegrationAuditEvents { + private final AuditPort auditPort; + + public void configUpdated(String tenantId, Long actorId, String provider, java.util.Collection fields) { + Map changes = new LinkedHashMap<>(); + changes.put("statusCode", "UPDATED"); + changes.put("changedFieldCodes", fields); + emit(tenantId, actorId, provider, "integration.config.update", "SUCCESS", null, + changes, Collections.emptyMap()); + } + + public void configTested(String tenantId, Long actorId, String provider, String statusCode) { + Map changes = Collections.singletonMap("statusCode", statusCode); + Map attributes = Collections.singletonMap("providerCode", provider); + String outcome = "SUCCESS".equals(statusCode) ? "SUCCESS" : "FAILURE"; + emit(tenantId, actorId, provider, "integration.config.test", outcome, statusCode, + changes, attributes); + } + + public void management(String tenantId, Long actorId, String action, String resourceType, + Object resourceId, String statusCode, java.util.Collection changedFields) { + Map changes = new LinkedHashMap<>(); + changes.put("statusCode", statusCode); + if (changedFields != null && !changedFields.isEmpty()) { + changes.put("changedFieldCodes", changedFields); + } + emit(tenantId, actorId, String.valueOf(resourceId), action, "SUCCESS", null, + changes, Collections.emptyMap(), resourceType); + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void failed(String tenantId, Long actorId, String action, String resourceType, + Object resourceId, String reasonCode) { + emit(tenantId, actorId, String.valueOf(resourceId), action, "FAILURE", reasonCode, + Collections.singletonMap("statusCode", reasonCode), + Collections.emptyMap(), resourceType); + } + + public void scheduled(String tenantId, Long actorId, String action, String taskCode, + String runId, String statusCode, + java.util.Collection changedFields) { + Map changes = new LinkedHashMap<>(); + changes.put("statusCode", statusCode); + if (changedFields != null && !changedFields.isEmpty()) { + changes.put("changedFieldCodes", changedFields); + } + Map attributes = new LinkedHashMap<>(); + attributes.put("taskCode", taskCode); + if (runId != null) attributes.put("runId", runId); + emit(tenantId, actorId, runId == null ? taskCode : runId, action, "SUCCESS", null, + changes, attributes, runId == null ? "SCHEDULED_TASK" : "SCHEDULED_TASK_RUN"); + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void scheduledFailed(String tenantId, Long actorId, String action, String taskCode, + String runId, String reasonCode) { + Map attributes = new LinkedHashMap<>(); + attributes.put("taskCode", taskCode); + if (runId != null) attributes.put("runId", runId); + emit(tenantId, actorId, runId == null ? taskCode : runId, action, "FAILURE", reasonCode, + Collections.singletonMap("statusCode", reasonCode), attributes, + runId == null ? "SCHEDULED_TASK" : "SCHEDULED_TASK_RUN"); + } + + private void emit(String tenantId, Long actorId, String provider, String action, String outcome, + String reasonCode, Map changes, Map attributes) { + emit(tenantId, actorId, provider, action, outcome, reasonCode, changes, attributes, + "SYS_INTEGRATION_CONFIG"); + } + + private void emit(String tenantId, Long actorId, String resourceId, String action, String outcome, + String reasonCode, Map changes, Map attributes, + String resourceType) { + auditPort.emit(AuditEventCommand.builder() + .eventId(UUID.randomUUID().toString().replace("-", "")) + .schemaVersion(1).eventTime(Instant.now()).tenantId(tenantId) + .category("INTEGRATION").action(action).outcome(outcome).reasonCode(reasonCode) + .actorType(actorId == null ? "SYSTEM" : "USER").actorId(actorId).targetType(resourceType) + .targetId(resourceId).resourceType(resourceType).resourceId(resourceId) + .requestId(MDC.get("request_id")).traceId(MDC.get("trace_id")).spanId(MDC.get("span_id")) + .source(actorId == null ? "SYSTEM" : "WEB").changes(changes).attributes(attributes).build()); + } +} diff --git a/src/main/java/com/finance/system/integration/audit/IntegrationAuditSchemaContributor.java b/src/main/java/com/finance/system/integration/audit/IntegrationAuditSchemaContributor.java new file mode 100644 index 0000000..b004de2 --- /dev/null +++ b/src/main/java/com/finance/system/integration/audit/IntegrationAuditSchemaContributor.java @@ -0,0 +1,50 @@ +package com.finance.system.integration.audit; + +import com.finance.system.audit.AuditEventSchemaContributor; +import com.finance.system.audit.AuditEventSchemaRegistry; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collection; + +import static com.finance.system.audit.AuditEventSchemaRegistry.code; +import static com.finance.system.audit.AuditEventSchemaRegistry.codeList; +import static com.finance.system.audit.AuditEventSchemaRegistry.fields; +import static com.finance.system.audit.AuditEventSchemaRegistry.none; +import static com.finance.system.audit.AuditEventSchemaRegistry.schema; + +@Component +public class IntegrationAuditSchemaContributor implements AuditEventSchemaContributor { + @Override + public Collection schemas() { + return Arrays.asList( + schema("INTEGRATION", "integration.config.update", 1, + fields("statusCode", code(40), "changedFieldCodes", codeList(32, 80)), none()), + schema("INTEGRATION", "integration.config.test", 1, + fields("statusCode", code(40)), fields("providerCode", code(20))), + management("integration.feishu.directory.sync-trigger"), + management("integration.feishu.approval.sync"), + management("integration.kingdee.account.bind"), + management("integration.kingdee.account.unbind"), + management("integration.kingdee.account.test"), + management("integration.kingdee.sync-config.create"), + management("integration.kingdee.sync-config.update"), + management("integration.kingdee.sync-config.delete"), + management("integration.kingdee.sync.trigger"), + management("integration.kingdee.sync.result"), + scheduled("integration.schedule.update"), + scheduled("integration.schedule.execute") + ); + } + + private AuditEventSchemaRegistry.Schema management(String action) { + return schema("INTEGRATION", action, 1, + fields("statusCode", code(80), "changedFieldCodes", codeList(64, 80)), none()); + } + + private AuditEventSchemaRegistry.Schema scheduled(String action) { + return schema("INTEGRATION", action, 1, + fields("statusCode", code(80), "changedFieldCodes", codeList(64, 80)), + fields("taskCode", code(64), "runId", code(64))); + } +} diff --git a/src/main/java/com/finance/system/migration/BankAccountLegacyBackfill.java b/src/main/java/com/finance/system/migration/BankAccountLegacyBackfill.java new file mode 100644 index 0000000..7d23a98 --- /dev/null +++ b/src/main/java/com/finance/system/migration/BankAccountLegacyBackfill.java @@ -0,0 +1,70 @@ +package com.finance.system.migration; + +import com.finance.system.security.finance.BankAccountProtection; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** Explicit, non-destructive backfill of encrypted values for legacy plaintext rows. */ +@Slf4j +@Component +@ConditionalOnProperty(name = "app.bank-account.legacy-backfill-enabled", havingValue = "true") +public class BankAccountLegacyBackfill implements ApplicationRunner { + private final JdbcTemplate jdbc; + private final BankAccountProtection protection; + + public BankAccountLegacyBackfill(JdbcTemplate jdbc, BankAccountProtection protection) { + this.jdbc = jdbc; + this.protection = protection; + } + + @Override + @Transactional + public void run(ApplicationArguments args) { + protection.assertConfigured(); + List rows = jdbc.query("SELECT id,account_no FROM sys_bank_account " + + "WHERE account_no IS NOT NULL AND account_no_ciphertext IS NULL FOR UPDATE", + (result, rowNum) -> new LegacyRow(result.getLong("id"), result.getString("account_no"))); + for (LegacyRow row : rows) { + BankAccountProtection.ProtectedValue value = protection.protect(normalize(row.accountNo)); + int updated = jdbc.update("UPDATE sys_bank_account SET account_no_ciphertext=?," + + "account_no_mask=?,account_fingerprint=?,encryption_key_version=?," + + "updated_at=CURRENT_TIMESTAMP(6) WHERE id=? AND account_no=? " + + "AND account_no_ciphertext IS NULL", + value.getCiphertext(), value.getMask(), value.getFingerprint(), value.getKeyVersion(), + row.id, row.accountNo); + if (updated != 1) throw new IllegalStateException("BANK_ACCOUNT_LEGACY_BACKFILL_CONFLICT"); + } + Integer remaining = jdbc.queryForObject("SELECT COUNT(*) FROM sys_bank_account " + + "WHERE account_no IS NOT NULL AND account_no_ciphertext IS NULL", Integer.class); + if (remaining == null || remaining != 0) { + throw new IllegalStateException("BANK_ACCOUNT_LEGACY_BACKFILL_INCOMPLETE"); + } + log.info("银行账号历史密文无损回填完成: backfilledRows={}", rows.size()); + } + + private String normalize(String value) { + if (value == null) throw new IllegalStateException("BANK_ACCOUNT_LEGACY_VALUE_MISSING"); + String normalized = value.trim().replaceAll("[\\s-]+", "").toUpperCase(java.util.Locale.ROOT); + if (!normalized.matches("[A-Z0-9]{6,100}")) { + throw new IllegalStateException("BANK_ACCOUNT_LEGACY_VALUE_INVALID"); + } + return normalized; + } + + private static final class LegacyRow { + private final long id; + private final String accountNo; + + private LegacyRow(long id, String accountNo) { + this.id = id; + this.accountNo = accountNo; + } + } +} diff --git a/src/main/java/com/finance/system/migration/MigrationManifest.java b/src/main/java/com/finance/system/migration/MigrationManifest.java new file mode 100644 index 0000000..1213355 --- /dev/null +++ b/src/main/java/com/finance/system/migration/MigrationManifest.java @@ -0,0 +1,151 @@ +package com.finance.system.migration; + +import com.finance.system.migration.MigrationScriptParser.MigrationPlan; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Ordered, closed manifest of canonical migration files. */ +public final class MigrationManifest { + private static final Pattern FILE_NAME = Pattern.compile( + "^(V(\\d{8})_(\\d{2}))__([a-z0-9][a-z0-9_]*)\\.sql$"); + + private MigrationManifest() { + } + + public static List load(Path manifestPath) throws IOException { + Path manifest = manifestPath.toAbsolutePath().normalize(); + if (!Files.isRegularFile(manifest)) { + throw new IllegalArgumentException("MIGRATION_MANIFEST_MISSING:" + manifest); + } + Path directory = manifest.getParent(); + List entries = new ArrayList<>(); + Set ids = new HashSet<>(); + long previousVersion = -1L; + for (String raw : Files.readAllLines(manifest, StandardCharsets.UTF_8)) { + String fileName = raw.trim(); + if (fileName.isEmpty() || fileName.startsWith("#")) continue; + if (fileName.indexOf('/') >= 0 || fileName.indexOf('\\') >= 0) { + throw new IllegalArgumentException("MIGRATION_MANIFEST_FILE_NAME_INVALID:" + fileName); + } + Matcher matcher = FILE_NAME.matcher(fileName); + if (!matcher.matches()) { + throw new IllegalArgumentException("MIGRATION_FILE_NAME_INVALID:" + fileName); + } + String migrationId = fileName.substring(0, fileName.length() - 4); + long version = Long.parseLong(matcher.group(2) + matcher.group(3)); + if (!ids.add(migrationId)) { + throw new IllegalArgumentException("MIGRATION_ID_DUPLICATE:" + migrationId); + } + if (version <= previousVersion) { + throw new IllegalArgumentException("MIGRATION_MANIFEST_ORDER_INVALID:" + migrationId); + } + previousVersion = version; + Path script = directory.resolve(fileName).normalize(); + if (!script.getParent().equals(directory) || !Files.isRegularFile(script)) { + throw new IllegalArgumentException("MIGRATION_FILE_MISSING:" + fileName); + } + String source = MySqlMigrationRunner.readNormalized(script); + entries.add(new Entry(migrationId, fileName, version, script, + MySqlMigrationRunner.checksum(source), MigrationScriptParser.parse(source))); + } + if (entries.isEmpty()) throw new IllegalArgumentException("MIGRATION_MANIFEST_EMPTY"); + rejectUnlistedScripts(directory, entries); + return Collections.unmodifiableList(entries); + } + + private static void rejectUnlistedScripts(Path directory, List entries) throws IOException { + Set listed = new HashSet<>(); + for (Entry entry : entries) listed.add(entry.fileName); + try (DirectoryStream stream = Files.newDirectoryStream(directory, "V*.sql")) { + for (Path path : stream) { + if (FILE_NAME.matcher(path.getFileName().toString()).matches() + && !listed.contains(path.getFileName().toString())) { + throw new IllegalArgumentException("MIGRATION_FILE_UNLISTED:" + path.getFileName()); + } + } + } + } + + public static void validateHistory(List entries, Map histories) { + boolean foundIncomplete = false; + for (Entry entry : entries) { + History history = histories.get(entry.migrationId); + if (history == null) { + foundIncomplete = true; + continue; + } + MigrationStateMachine.Action action = MigrationStateMachine.decide( + history.checksum, history.status, entry.checksum); + if (foundIncomplete && action == MigrationStateMachine.Action.NO_OP) { + throw new IllegalStateException("MIGRATION_PREDECESSOR_NOT_APPLIED:" + entry.migrationId); + } + if (action == MigrationStateMachine.Action.RESUME) { + if (foundIncomplete) { + throw new IllegalStateException("MIGRATION_PREDECESSOR_NOT_APPLIED:" + entry.migrationId); + } + foundIncomplete = true; + } + } + } + + public static Map histories(History... histories) { + Map result = new LinkedHashMap<>(); + for (History history : histories) result.put(history.migrationId, history); + return result; + } + + public static final class Entry { + private final String migrationId; + private final String fileName; + private final long version; + private final Path script; + private final String checksum; + private final MigrationPlan plan; + + Entry(String migrationId, String fileName, long version, Path script, + String checksum, MigrationPlan plan) { + this.migrationId = migrationId; + this.fileName = fileName; + this.version = version; + this.script = script; + this.checksum = checksum; + this.plan = plan; + } + + public String getMigrationId() { return migrationId; } + public String getFileName() { return fileName; } + public long getVersion() { return version; } + public Path getScript() { return script; } + public String getChecksum() { return checksum; } + public MigrationPlan getPlan() { return plan; } + } + + public static final class History { + private final String migrationId; + private final String checksum; + private final String status; + + public History(String migrationId, String checksum, String status) { + this.migrationId = migrationId; + this.checksum = checksum; + this.status = status; + } + + public String getMigrationId() { return migrationId; } + public String getChecksum() { return checksum; } + public String getStatus() { return status; } + } +} diff --git a/src/main/java/com/finance/system/migration/MigrationScriptParser.java b/src/main/java/com/finance/system/migration/MigrationScriptParser.java new file mode 100644 index 0000000..a4bbf41 --- /dev/null +++ b/src/main/java/com/finance/system/migration/MigrationScriptParser.java @@ -0,0 +1,187 @@ +package com.finance.system.migration; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Parses MySQL scripts for JDBC execution, including mysql-client DELIMITER + * directives and the repository's restart/assert directives. + */ +public final class MigrationScriptParser { + private MigrationScriptParser() { + } + + public static MigrationPlan parse(String source) { + if (source == null) throw new IllegalArgumentException("MIGRATION_SCRIPT_REQUIRED"); + List steps = new ArrayList<>(); + List preconditions = new ArrayList<>(); + List assertions = new ArrayList<>(); + StringBuilder pending = new StringBuilder(); + String delimiter = ";"; + String guard = null; + + String normalized = source.replace("\r\n", "\n").replace('\r', '\n'); + for (String rawLine : normalized.split("\n", -1)) { + String trimmed = rawLine.trim(); + if (trimmed.startsWith("-- @guard ")) { + ensureEmpty(pending, "MIGRATION_GUARD_POSITION_INVALID"); + guard = withoutTrailingSemicolon(trimmed.substring("-- @guard ".length()).trim()); + continue; + } + if (trimmed.startsWith("-- @precondition ")) { + ensureEmpty(pending, "MIGRATION_PRECONDITION_POSITION_INVALID"); + preconditions.add(parseAssertion(trimmed.substring("-- @precondition ".length()).trim(), + "MIGRATION_PRECONDITION_DIRECTIVE_INVALID")); + continue; + } + if (trimmed.startsWith("-- @assert ")) { + ensureEmpty(pending, "MIGRATION_ASSERT_POSITION_INVALID"); + assertions.add(parseAssertion(trimmed.substring("-- @assert ".length()).trim(), + "MIGRATION_ASSERT_DIRECTIVE_INVALID")); + continue; + } + if (trimmed.regionMatches(true, 0, "DELIMITER ", 0, "DELIMITER ".length())) { + ensureEmpty(pending, "MIGRATION_DELIMITER_POSITION_INVALID"); + delimiter = trimmed.substring("DELIMITER ".length()).trim(); + if (delimiter.isEmpty()) throw new IllegalArgumentException("MIGRATION_DELIMITER_INVALID"); + continue; + } + if (trimmed.isEmpty() || trimmed.startsWith("-- ") || "--".equals(trimmed)) continue; + + pending.append(rawLine).append('\n'); + if (";".equals(delimiter)) { + guard = splitSemicolonStatements(pending, guard, steps); + } else if (endsWithDelimiter(pending, delimiter)) { + String sql = pending.substring(0, pending.length() - delimiter.length()).trim(); + if (!sql.isEmpty()) steps.add(new SqlStep(sql, guard)); + pending.setLength(0); + guard = null; + } + } + if (pending.toString().trim().length() != 0) { + throw new IllegalArgumentException("MIGRATION_STATEMENT_UNTERMINATED"); + } + if (guard != null) throw new IllegalArgumentException("MIGRATION_GUARD_WITHOUT_STATEMENT"); + return new MigrationPlan(steps, preconditions, assertions); + } + + private static Assertion parseAssertion(String directive, String invalidError) { + int split = directive.indexOf("::"); + if (split <= 0 || split == directive.length() - 2) { + throw new IllegalArgumentException(invalidError); + } + return new Assertion(directive.substring(0, split).trim(), + withoutTrailingSemicolon(directive.substring(split + 2).trim())); + } + + private static String splitSemicolonStatements(StringBuilder pending, String guard, + List steps) { + boolean single = false; + boolean doubledQuote; + int start = 0; + for (int i = 0; i < pending.length(); i++) { + char current = pending.charAt(i); + if (current == '\'') { + doubledQuote = single && i + 1 < pending.length() && pending.charAt(i + 1) == '\''; + if (doubledQuote) { + i++; + continue; + } + single = !single; + } + if (current == ';' && !single) { + String sql = pending.substring(start, i).trim(); + if (!sql.isEmpty()) { + steps.add(new SqlStep(sql, guard)); + guard = null; + } + start = i + 1; + } + } + if (start > 0) pending.delete(0, start); + return guard; + } + + private static boolean endsWithDelimiter(StringBuilder pending, String delimiter) { + int end = pending.length(); + while (end > 0 && Character.isWhitespace(pending.charAt(end - 1))) end--; + if (end < delimiter.length()) return false; + for (int i = 0; i < delimiter.length(); i++) { + if (pending.charAt(end - delimiter.length() + i) != delimiter.charAt(i)) return false; + } + if (end != pending.length()) pending.delete(end, pending.length()); + return true; + } + + private static String withoutTrailingSemicolon(String value) { + return value.endsWith(";") ? value.substring(0, value.length() - 1).trim() : value; + } + + private static void ensureEmpty(StringBuilder pending, String error) { + if (pending.toString().trim().length() != 0) throw new IllegalArgumentException(error); + } + + public static final class MigrationPlan { + private final List steps; + private final List preconditions; + private final List assertions; + + MigrationPlan(List steps, List preconditions, List assertions) { + this.steps = Collections.unmodifiableList(new ArrayList<>(steps)); + this.preconditions = Collections.unmodifiableList(new ArrayList<>(preconditions)); + this.assertions = Collections.unmodifiableList(new ArrayList<>(assertions)); + } + + public List getSteps() { + return steps; + } + + public List getAssertions() { + return assertions; + } + + public List getPreconditions() { + return preconditions; + } + } + + public static final class SqlStep { + private final String sql; + private final String guardSql; + + SqlStep(String sql, String guardSql) { + this.sql = sql; + this.guardSql = guardSql; + } + + public String getSql() { + return sql; + } + + public String getGuardSql() { + return guardSql; + } + } + + public static final class Assertion { + private final String code; + private final String query; + + Assertion(String code, String query) { + if (!code.matches("[A-Z0-9_]{1,80}")) { + throw new IllegalArgumentException("MIGRATION_ASSERT_CODE_INVALID"); + } + this.code = code; + this.query = query; + } + + public String getCode() { + return code; + } + + public String getQuery() { + return query; + } + } +} diff --git a/src/main/java/com/finance/system/migration/MigrationStateMachine.java b/src/main/java/com/finance/system/migration/MigrationStateMachine.java new file mode 100644 index 0000000..aa9636a --- /dev/null +++ b/src/main/java/com/finance/system/migration/MigrationStateMachine.java @@ -0,0 +1,26 @@ +package com.finance.system.migration; + +import java.util.Locale; + +/** Pure decision table for restartable migration history handling. */ +public final class MigrationStateMachine { + private MigrationStateMachine() { + } + + public enum Action { + START, + RESUME, + NO_OP + } + + public static Action decide(String storedChecksum, String storedStatus, String requestedChecksum) { + if (storedChecksum == null && storedStatus == null) return Action.START; + if (storedChecksum == null || !storedChecksum.equals(requestedChecksum)) { + throw new IllegalStateException("MIGRATION_CHECKSUM_MISMATCH"); + } + String status = storedStatus == null ? "" : storedStatus.toUpperCase(Locale.ROOT); + if ("APPLIED".equals(status)) return Action.NO_OP; + if ("RUNNING".equals(status)) return Action.RESUME; + throw new IllegalStateException("MIGRATION_HISTORY_STATUS_INVALID:" + status); + } +} diff --git a/src/main/java/com/finance/system/migration/MySqlMigrationRunner.java b/src/main/java/com/finance/system/migration/MySqlMigrationRunner.java new file mode 100644 index 0000000..bd370eb --- /dev/null +++ b/src/main/java/com/finance/system/migration/MySqlMigrationRunner.java @@ -0,0 +1,887 @@ +package com.finance.system.migration; + +import com.finance.system.migration.MigrationScriptParser.Assertion; +import com.finance.system.migration.MigrationScriptParser.MigrationPlan; +import com.finance.system.migration.MigrationScriptParser.SqlStep; +import com.finance.system.migration.MigrationManifest.Entry; +import com.finance.system.migration.MigrationManifest.History; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** Standalone, single-connection, restartable migration runner for MySQL 8.4 LTS. */ +public final class MySqlMigrationRunner { + private static final String LOCK_NAME = "finance-system-schema-migration"; + private static final String V13_MIGRATION_ID = + "V20261009_13__feishu_approval_definition_route_preview"; + private static final String V13_ROUTE_TOKEN_GENERATED_ASSERTION = + "MIGRATION_ASSERT_V13_ROUTE_TOKEN_GENERATED"; + private static final String V19_MIGRATION_ID = + "V20261009_19__menu_tree_derived_authorization"; + private static final String V20261017_01_MIGRATION_ID = + "V20261017_01__payee_subject_travel_applications"; + private static final String V20261017_02_MIGRATION_ID = + "V20261017_02__collapse_home_and_payment_pages"; + private static final String V20261017_03_MIGRATION_ID = + "V20261017_03__business_configuration"; + private static final String V20261017_03_CONTROLS_ASSERTION = + "MIGRATION_ASSERT_V20261017_03_CONTROLS"; + private static final String V20261017_03_CATALOG_PRECONDITION = + "MIGRATION_PRECONDITION_V20261017_03_CATALOG"; + private static final String V20261017_03_CATALOG_PRECONDITION_LEGACY = + "SELECT COUNT(*)=1 FROM authz_permission_catalog_version WHERE id=1 AND version=5"; + private static final String V20261017_03_CATALOG_PRECONDITION_RESUME = + "SELECT COUNT(*)=1 FROM authz_permission_catalog_version WHERE id=1 AND version IN (5,6)"; + private static final String V20261017_03_DIALOG_SCOPE_LEGACY = + "permission_code LIKE 'dialog.%.editor.%' AND permission_layer='DIALOG_FIELD'"; + private static final String V20261017_03_DIALOG_SCOPE_SAFE = + "parent_code IN ('dialog.legal-entities.editor','dialog.cost-centers.editor'," + + "'dialog.currencies.editor','dialog.budgets.editor'," + + "'dialog.payment-methods.editor','dialog.payment-accounts.editor') " + + "AND permission_layer='DIALOG_FIELD'"; + private static final String V20261017_03_TABLE_PREFIX = "CREATE TABLE biz_"; + private static final String V20261017_03_PERMISSION_INSERT_PREFIX = + "INSERT INTO sys_permission(permission_code,permission_name,permission_type,parent_code,permission_layer,"; + private static final String V20261017_01_PERMISSION_INSERT_PREFIX = + "INSERT INTO sys_permission(permission_code,permission_name,permission_type,parent_code,permission_layer,"; + private static final String V20261017_01_SENSITIVE_COLUMNS = + "sort_order,resource,default_access,sensitive,field_sensitivity,created_at,updated_at)"; + private static final String V20261017_01_SENSITIVE_COLUMNS_SAFE = + "sort_order,resource,default_access,delegable,risk_level,created_at,updated_at)"; + private static final String V20261017_01_SENSITIVE_UPDATE = + "sensitive=VALUES(sensitive)"; + private static final String V20261017_01_SENSITIVE_UPDATE_SAFE = + "delegable=VALUES(delegable)"; + private static final String V20261017_01_FIELD_SENSITIVITY_UPDATE = + "field_sensitivity=VALUES(field_sensitivity)"; + private static final String V20261017_01_FIELD_SENSITIVITY_UPDATE_SAFE = + "risk_level=VALUES(risk_level)"; + private static final String V20261017_01_NON_DELEGABLE_NORMAL_VALUE = + "'READ',FALSE,'NORMAL'"; + private static final String V20261017_01_DELEGABLE_NORMAL_VALUE = + "'READ',TRUE,'NORMAL'"; + private static final String V20261017_01_ROLE_PERMISSION_INSERT_PREFIX = + "INSERT INTO sys_role_permission(role_id,permission_id,access_level)"; + private static final String V20261017_01_ACCESS_PRESERVE_EDIT_SAFE = + "ON DUPLICATE KEY UPDATE access_level=IF(" + + "sys_role_permission.access_level='EDIT','EDIT','READ')"; + private static final String V20261017_01_ACCESS_UPGRADE_OR_VALUES_SAFE = + "ON DUPLICATE KEY UPDATE access_level=IF(" + + "sys_role_permission.access_level='EDIT' OR " + + "VALUES(access_level)='EDIT','EDIT','READ')"; + private static final String V19_MAPPING_INSERT_PREFIX = + "INSERT INTO authz_permission_policy_map(permission_id,policy_id,min_access_level,mapping_type)"; + private static final String V19_LEGACY_MAPPING_JOIN = + ") x JOIN sys_permission pm ON pm.permission_code=x.pc " + + "JOIN authz_policy ap ON ap.policy_code=x.ac"; + private static final String V19_COLLATION_SAFE_MAPPING_JOIN = + ") x JOIN sys_permission pm ON pm.permission_code=" + + "(CONVERT(x.pc USING utf8mb4) COLLATE utf8mb4_bin) " + + "JOIN authz_policy ap ON ap.policy_code=" + + "(CONVERT(x.ac USING ascii) COLLATE ascii_bin)"; + private static final String V19_ROLE_PERMISSION_INSERT_PREFIX = + "INSERT INTO sys_role_permission(role_id,permission_id,access_level)"; + private static final String V19_ACCESS_UPGRADE_OR_VALUES = + "ON DUPLICATE KEY UPDATE access_level=IF(access_level='EDIT' OR " + + "VALUES(access_level)='EDIT','EDIT','READ')"; + private static final String V19_ACCESS_UPGRADE_OR_VALUES_SAFE = + "ON DUPLICATE KEY UPDATE access_level=sys_role_permission.access_level"; + private static final String V19_ACCESS_PRESERVE_EDIT = + "ON DUPLICATE KEY UPDATE access_level=IF(access_level='EDIT','EDIT','READ')"; + private static final String V19_ACCESS_PRESERVE_EDIT_SAFE = + "ON DUPLICATE KEY UPDATE access_level=sys_role_permission.access_level"; + private static final String V19_ACCESS_PRESERVE_CURRENT = + "ON DUPLICATE KEY UPDATE access_level=access_level"; + private static final String V19_ACCESS_PRESERVE_CURRENT_SAFE = + "ON DUPLICATE KEY UPDATE access_level=sys_role_permission.access_level"; + private static final String V19_ACCESS_FORCE_EDIT = + "ON DUPLICATE KEY UPDATE access_level='EDIT'"; + private static final String V19_ACCESS_FORCE_EDIT_SAFE = + "ON DUPLICATE KEY UPDATE access_level=sys_role_permission.access_level"; + private static final String V19_DERIVED_UPDATE_LEGACY = + "UPDATE authz_role_policy rp SET rp.assignment_source='DERIVED'\n" + + " WHERE rp.assignment_source<>'SYSTEM' AND EXISTS (\n" + + " SELECT 1 FROM authz_permission_policy_map m JOIN sys_role_permission srp\n" + + " ON srp.permission_id=m.permission_id AND srp.role_id=rp.role_id\n" + + " WHERE m.policy_id=rp.policy_id AND m.mapping_type='BUSINESS'\n" + + " AND ((m.min_access_level='READ' AND srp.access_level IN ('READ','EDIT')) OR " + + "(m.min_access_level='EDIT' AND srp.access_level='EDIT')))"; + private static final String V19_DERIVED_UPDATE_SAFE = + "UPDATE authz_role_policy rp JOIN (\n" + + " SELECT DISTINCT srp.role_id,m.policy_id\n" + + " FROM authz_permission_policy_map m JOIN sys_role_permission srp\n" + + " ON srp.permission_id=m.permission_id\n" + + " WHERE m.mapping_type='BUSINESS'\n" + + " AND ((m.min_access_level='READ' AND srp.access_level IN ('READ','EDIT')) OR " + + "(m.min_access_level='EDIT' AND srp.access_level='EDIT'))\n" + + ") explained ON explained.role_id=rp.role_id AND explained.policy_id=rp.policy_id\n" + + " SET rp.assignment_source='DERIVED'\n" + + " WHERE rp.assignment_source<>'SYSTEM'"; + private static final String V19_DERIVED_ASSERTION_CODE = + "MIGRATION_ASSERT_V19_DERIVED_EXPLAINED"; + private static final String V19_DERIVED_ASSERTION_LEGACY = + "SELECT COUNT(*)=0 FROM authz_role_policy rp WHERE rp.assignment_source='DERIVED' " + + "AND NOT EXISTS (SELECT 1 FROM authz_permission_policy_map m JOIN " + + "sys_role_permission srp ON srp.permission_id=m.permission_id AND " + + "srp.role_id=rp.role_id WHERE m.policy_id=rp.policy_id AND " + + "m.mapping_type='BUSINESS' AND ((m.min_access_level='READ' AND " + + "srp.access_level IN ('READ','EDIT')) OR (m.min_access_level='EDIT' AND " + + "srp.access_level='EDIT')))"; + private static final String V19_DERIVED_ASSERTION_SAFE = + "SELECT COUNT(*)=0 FROM authz_role_policy rp LEFT JOIN (" + + "SELECT DISTINCT srp.role_id,m.policy_id FROM authz_permission_policy_map m " + + "JOIN sys_role_permission srp ON srp.permission_id=m.permission_id " + + "WHERE m.mapping_type='BUSINESS' AND ((m.min_access_level='READ' AND " + + "srp.access_level IN ('READ','EDIT')) OR (m.min_access_level='EDIT' AND " + + "srp.access_level='EDIT'))) explained ON explained.role_id=rp.role_id AND " + + "explained.policy_id=rp.policy_id WHERE rp.assignment_source='DERIVED' " + + "AND explained.role_id IS NULL"; + private static final String LEGACY_DATABASE_USE = "USE `finance_system`"; + private static final String REHEARSAL_SCHEMA_PREFIX = "finance_system_v19_mysql57_probe_"; + private static final Set LEGACY_USE_MIGRATIONS = new LinkedHashSet(); + + static { + LEGACY_USE_MIGRATIONS.add("V20261009_01__audit_observability_foundation"); + LEGACY_USE_MIGRATIONS.add("V20261009_02__fine_grained_authorization"); + LEGACY_USE_MIGRATIONS.add("V20261009_03__finance_domain_authorization_audit"); + } + + private MySqlMigrationRunner() { + } + + public static void main(String[] args) throws Exception { + Arguments parsed = Arguments.parse(args); + List entries = MigrationManifest.load(Paths.get(parsed.manifest)); + validateRehearsalPlan(entries, parsed.rehearsalSchema); + for (Entry entry : entries) { + validateCompatiblePlan(entry.getMigrationId(), entry.getPlan().getSteps()); + validateCompatiblePreconditions(entry.getMigrationId(), entry.getPlan().getPreconditions()); + validateCompatibleAssertions(entry.getMigrationId(), entry.getPlan().getAssertions()); + } + if (parsed.mode == Mode.DRY_RUN) { + for (Entry entry : entries) { + System.out.println("迁移验证通过 VALID " + entry.getMigrationId() + " checksum=" + entry.getChecksum() + + " steps=" + entry.getPlan().getSteps().size() + + " preconditions=" + entry.getPlan().getPreconditions().size() + + " assertions=" + entry.getPlan().getAssertions().size()); + } + return; + } + String password = System.getenv(parsed.passwordEnvironment); + if (password == null) throw new IllegalArgumentException("MIGRATION_PASSWORD_ENV_MISSING"); + + try (Connection connection = DriverManager.getConnection(parsed.url, parsed.user, password)) { + connection.setAutoCommit(true); + validateRehearsalConnection(connection, parsed.rehearsalSchema); + acquireLock(connection, parsed.lockTimeoutSeconds); + try { + Map histories = historyTableExists(connection) + ? readHistories(connection, entries) : new LinkedHashMap(); + MigrationManifest.validateHistory(entries, histories); + if (parsed.mode == Mode.PREFLIGHT) { + System.out.println("迁移预检通过,共 " + entries.size() + " 个文件"); + return; + } + ensureHistoryTable(connection); + for (Entry entry : entries) { + run(connection, entry.getMigrationId(), entry.getChecksum(), entry.getPlan(), + parsed.rehearsalSchema); + } + } finally { + releaseLock(connection); + } + } + } + + static void run(Connection connection, String migrationId, String checksum, + MigrationPlan plan) throws SQLException { + run(connection, migrationId, checksum, plan, null); + } + + private static void run(Connection connection, String migrationId, String checksum, + MigrationPlan plan, String rehearsalSchema) throws SQLException { + validateCompatiblePlan(migrationId, plan.getSteps()); + validateCompatiblePreconditions(migrationId, plan.getPreconditions()); + validateCompatibleAssertions(migrationId, plan.getAssertions()); + ensureHistoryTable(connection); + History history = readHistory(connection, migrationId); + MigrationStateMachine.Action action = MigrationStateMachine.decide( + history == null ? null : history.getChecksum(), + history == null ? null : history.getStatus(), checksum); + if (action == MigrationStateMachine.Action.NO_OP) { + System.out.println("迁移已执行且校验和一致: " + migrationId); + return; + } + for (Assertion precondition : plan.getPreconditions()) { + if (!scalarTrue(connection, compatiblePreconditionQuery(migrationId, precondition, action))) { + throw new IllegalStateException("MIGRATION_PRECONDITION_FAILED:" + precondition.getCode()); + } + } + markRunning(connection, migrationId, checksum, action); + for (SqlStep step : plan.getSteps()) { + if (step.getGuardSql() != null && scalarTrue(connection, step.getGuardSql())) continue; + try (Statement statement = connection.createStatement()) { + statement.execute(compatibleStepSql(migrationId, step.getSql(), rehearsalSchema)); + } + } + for (Assertion assertion : plan.getAssertions()) { + if (!scalarTrue(connection, compatibleAssertionQuery(migrationId, assertion)) + && !compatibleAssertionPassed(connection, migrationId, assertion.getCode())) { + throw new IllegalStateException("MIGRATION_ASSERTION_FAILED:" + assertion.getCode()); + } + } + int affected; + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE sys_schema_migration SET status='APPLIED', applied_at=UTC_TIMESTAMP(6) " + + "WHERE migration_id=? AND checksum=? AND status='RUNNING'")) { + statement.setString(1, migrationId); + statement.setString(2, checksum); + affected = statement.executeUpdate(); + } + if (affected != 1) throw new IllegalStateException("MIGRATION_HISTORY_FINALIZE_AFFECTED_ROWS:" + affected); + System.out.println("迁移已执行: " + migrationId + " checksum=" + checksum); + } + + private static void acquireLock(Connection connection, int timeoutSeconds) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT GET_LOCK(?,?)")) { + statement.setString(1, LOCK_NAME); + statement.setInt(2, timeoutSeconds); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 1) { + throw new IllegalStateException("MIGRATION_LOCK_NOT_ACQUIRED"); + } + } + } + } + + private static void releaseLock(Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT RELEASE_LOCK(?)")) { + statement.setString(1, LOCK_NAME); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 1) { + throw new IllegalStateException("MIGRATION_LOCK_RELEASE_FAILED"); + } + } + } + } + + private static void ensureHistoryTable(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("CREATE TABLE IF NOT EXISTS sys_schema_migration (" + + "migration_id VARCHAR(120) CHARACTER SET ascii COLLATE ascii_bin NOT NULL," + + "checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL," + + "status VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL," + + "started_at DATETIME(6) NOT NULL,applied_at DATETIME(6),PRIMARY KEY(migration_id)) " + + "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + } + } + + private static History readHistory(Connection connection, String migrationId) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT checksum,status FROM sys_schema_migration WHERE migration_id=?")) { + statement.setString(1, migrationId); + try (ResultSet result = statement.executeQuery()) { + return result.next() ? new History(migrationId, result.getString(1), result.getString(2)) : null; + } + } + } + + private static boolean historyTableExists(Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() " + + "AND table_name='sys_schema_migration'")) { + try (ResultSet result = statement.executeQuery()) { + return result.next() && result.getInt(1) == 1; + } + } + } + + private static Map readHistories(Connection connection, List entries) + throws SQLException { + Map result = new LinkedHashMap<>(); + for (Entry entry : entries) { + History history = readHistory(connection, entry.getMigrationId()); + if (history != null) result.put(entry.getMigrationId(), history); + } + return result; + } + + private static void markRunning(Connection connection, String migrationId, String checksum, + MigrationStateMachine.Action action) throws SQLException { + if (action == MigrationStateMachine.Action.RESUME) return; + try (PreparedStatement statement = connection.prepareStatement( + "INSERT INTO sys_schema_migration(migration_id,checksum,status,started_at) " + + "VALUES(?,?,'RUNNING',UTC_TIMESTAMP(6))")) { + statement.setString(1, migrationId); + statement.setString(2, checksum); + if (statement.executeUpdate() != 1) { + throw new IllegalStateException("MIGRATION_HISTORY_START_FAILED"); + } + } + } + + private static boolean scalarTrue(Connection connection, String query) throws SQLException { + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(query)) { + if (!result.next()) throw new IllegalStateException("MIGRATION_SCALAR_QUERY_EMPTY"); + return result.getBoolean(1) && !result.wasNull(); + } + } + + private static boolean compatibleAssertionPassed(Connection connection, String migrationId, + String assertionCode) throws SQLException { + if (!isV13GeneratedExpressionCompatibilityAssertion(migrationId, assertionCode)) return false; + try (PreparedStatement statement = connection.prepareStatement( + "SELECT column_name,column_type,is_nullable,column_default,extra," + + "character_set_name,collation_name,generation_expression " + + "FROM information_schema.columns WHERE table_schema=DATABASE() " + + "AND table_name='reim_route_preview_token' " + + "AND column_name IN ('active_application_id','active_user_id')")) { + int matched = 0; + boolean applicationSeen = false; + boolean userSeen = false; + try (ResultSet result = statement.executeQuery()) { + while (result.next()) { + String columnName = result.getString("column_name"); + if (!v13RouteTokenGeneratedColumnMatches( + columnName, + result.getString("column_type"), + result.getString("is_nullable"), + result.getString("column_default"), + result.getString("extra"), + result.getString("character_set_name"), + result.getString("collation_name"), + result.getString("generation_expression"))) { + return false; + } + if ("active_application_id".equals(columnName)) { + if (applicationSeen) return false; + applicationSeen = true; + } else if ("active_user_id".equals(columnName)) { + if (userSeen) return false; + userSeen = true; + } else { + return false; + } + matched++; + } + } + return matched == 2 && applicationSeen && userSeen; + } + } + + /** Keeps recorded migration bytes/checksums immutable while narrowly adapting + * exact legacy statements whose server-version compatibility issue surfaced + * after a RUNNING history row had already been written. */ + static String compatibleStepSql(String migrationId, String sql) { + return compatibleStepSql(migrationId, sql, null); + } + + static String compatibleStepSql(String migrationId, String sql, String rehearsalSchema) { + if (rehearsalSchema != null && isUseStatement(sql)) { + if (!LEGACY_USE_MIGRATIONS.contains(migrationId) || !LEGACY_DATABASE_USE.equals(sql)) { + throw new IllegalStateException("MIGRATION_REHEARSAL_USE_SHAPE_INVALID"); + } + return "USE `" + rehearsalSchema + "`"; + } + if (V20261017_01_MIGRATION_ID.equals(migrationId) + && sql.startsWith(V20261017_01_PERMISSION_INSERT_PREFIX)) { + String compatible = replaceUnique(sql, V20261017_01_SENSITIVE_COLUMNS, + V20261017_01_SENSITIVE_COLUMNS_SAFE, + "MIGRATION_V20261017_01_SENSITIVE_COLUMNS_COMPAT_SHAPE_INVALID"); + compatible = replaceUnique(compatible, V20261017_01_SENSITIVE_UPDATE, + V20261017_01_SENSITIVE_UPDATE_SAFE, + "MIGRATION_V20261017_01_SENSITIVE_UPDATE_COMPAT_SHAPE_INVALID"); + compatible = replaceUnique(compatible, V20261017_01_FIELD_SENSITIVITY_UPDATE, + V20261017_01_FIELD_SENSITIVITY_UPDATE_SAFE, + "MIGRATION_V20261017_01_RISK_UPDATE_COMPAT_SHAPE_INVALID"); + if (countOccurrences(compatible, V20261017_01_NON_DELEGABLE_NORMAL_VALUE) != 2) { + throw new IllegalStateException( + "MIGRATION_V20261017_01_DELEGABLE_VALUES_COMPAT_SHAPE_INVALID"); + } + return compatible.replace(V20261017_01_NON_DELEGABLE_NORMAL_VALUE, + V20261017_01_DELEGABLE_NORMAL_VALUE); + } + if (V20261017_01_MIGRATION_ID.equals(migrationId) + && sql.startsWith(V20261017_01_ROLE_PERMISSION_INSERT_PREFIX)) { + if (countOccurrences(sql, V19_ACCESS_PRESERVE_EDIT) == 1) { + return sql.replace(V19_ACCESS_PRESERVE_EDIT, + V20261017_01_ACCESS_PRESERVE_EDIT_SAFE); + } + if (countOccurrences(sql, V19_ACCESS_UPGRADE_OR_VALUES) == 1) { + return sql.replace(V19_ACCESS_UPGRADE_OR_VALUES, + V20261017_01_ACCESS_UPGRADE_OR_VALUES_SAFE); + } + throw new IllegalStateException( + "MIGRATION_V20261017_01_ROLE_PERMISSION_COMPAT_SHAPE_INVALID"); + } + if (V20261017_02_MIGRATION_ID.equals(migrationId) + && sql.startsWith(V20261017_01_ROLE_PERMISSION_INSERT_PREFIX)) { + if (countOccurrences(sql, V19_ACCESS_PRESERVE_EDIT) == 1) { + return sql.replace(V19_ACCESS_PRESERVE_EDIT, + V20261017_01_ACCESS_PRESERVE_EDIT_SAFE); + } + if (countOccurrences(sql, V19_ACCESS_FORCE_EDIT) == 1) { + return sql; + } + throw new IllegalStateException( + "MIGRATION_V20261017_02_ROLE_PERMISSION_COMPAT_SHAPE_INVALID"); + } + if (V20261017_03_MIGRATION_ID.equals(migrationId)) { + if (sql.startsWith(V20261017_03_TABLE_PREFIX)) { + return replaceUnique(sql, "CREATE TABLE ", "CREATE TABLE IF NOT EXISTS ", + "MIGRATION_V20261017_03_TABLE_COMPAT_SHAPE_INVALID"); + } + if (sql.startsWith(V20261017_03_PERMISSION_INSERT_PREFIX)) { + return replaceUnique(sql, "INSERT INTO sys_permission", "INSERT IGNORE INTO sys_permission", + "MIGRATION_V20261017_03_PERMISSION_COMPAT_SHAPE_INVALID"); + } + return sql; + } + if (!V19_MIGRATION_ID.equals(migrationId)) { + return sql; + } + if (sql.startsWith(V19_MAPPING_INSERT_PREFIX)) { + return replaceUnique(sql, V19_LEGACY_MAPPING_JOIN, + V19_COLLATION_SAFE_MAPPING_JOIN, + "MIGRATION_V19_MAPPING_COLLATION_COMPAT_SHAPE_INVALID"); + } + if (sql.startsWith("UPDATE authz_role_policy rp SET rp.assignment_source='DERIVED'")) { + if (!V19_DERIVED_UPDATE_LEGACY.equals(sql)) { + throw new IllegalStateException("MIGRATION_V19_DERIVED_SCOPE_COMPAT_SHAPE_INVALID"); + } + return V19_DERIVED_UPDATE_SAFE; + } + if (!sql.startsWith(V19_ROLE_PERMISSION_INSERT_PREFIX)) { + return sql; + } + if (countOccurrences(sql, V19_ACCESS_UPGRADE_OR_VALUES) == 1) { + return sql.replace(V19_ACCESS_UPGRADE_OR_VALUES, V19_ACCESS_UPGRADE_OR_VALUES_SAFE); + } + if (countOccurrences(sql, V19_ACCESS_PRESERVE_EDIT) == 1) { + return sql.replace(V19_ACCESS_PRESERVE_EDIT, V19_ACCESS_PRESERVE_EDIT_SAFE); + } + if (countOccurrences(sql, V19_ACCESS_PRESERVE_CURRENT) == 1) { + return sql.replace(V19_ACCESS_PRESERVE_CURRENT, V19_ACCESS_PRESERVE_CURRENT_SAFE); + } + if (countOccurrences(sql, V19_ACCESS_FORCE_EDIT) == 1) { + return sql.replace(V19_ACCESS_FORCE_EDIT, V19_ACCESS_FORCE_EDIT_SAFE); + } + throw new IllegalStateException("MIGRATION_V19_ROLE_PERMISSION_COMPAT_SHAPE_INVALID"); + } + + static void validateCompatiblePlan(String migrationId, List steps) { + if (V20261017_01_MIGRATION_ID.equals(migrationId)) { + int compatiblePermissionInserts = 0; + int rolePermissionInserts = 0; + int preserveEdit = 0; + int upgradeOrValues = 0; + for (SqlStep step : steps) { + String sql = step.getSql(); + if (sql.startsWith(V20261017_01_PERMISSION_INSERT_PREFIX)) { + compatiblePermissionInserts++; + if (countOccurrences(sql, V20261017_01_SENSITIVE_COLUMNS) != 1 + || countOccurrences(sql, V20261017_01_SENSITIVE_UPDATE) != 1 + || countOccurrences(sql, V20261017_01_FIELD_SENSITIVITY_UPDATE) != 1 + || countOccurrences(sql, V20261017_01_NON_DELEGABLE_NORMAL_VALUE) != 2) { + throw new IllegalStateException( + "MIGRATION_V20261017_01_SENSITIVE_COMPAT_SHAPE_INVALID"); + } + } + if (sql.startsWith(V20261017_01_ROLE_PERMISSION_INSERT_PREFIX)) { + rolePermissionInserts++; + if (countOccurrences(sql, V19_ACCESS_PRESERVE_EDIT) == 1) { + preserveEdit++; + } else if (countOccurrences(sql, V19_ACCESS_UPGRADE_OR_VALUES) == 1) { + upgradeOrValues++; + } else { + throw new IllegalStateException( + "MIGRATION_V20261017_01_ROLE_PERMISSION_COMPAT_SHAPE_INVALID"); + } + } + } + if (compatiblePermissionInserts != 1 || rolePermissionInserts != 3 + || preserveEdit != 2 || upgradeOrValues != 1) { + throw new IllegalStateException("MIGRATION_V20261017_01_COMPAT_PLAN_INVALID"); + } + return; + } + if (V20261017_02_MIGRATION_ID.equals(migrationId)) { + int rolePermissionInserts = 0; + int preserveEdit = 0; + int forceEdit = 0; + for (SqlStep step : steps) { + String sql = step.getSql(); + if (!sql.startsWith(V20261017_01_ROLE_PERMISSION_INSERT_PREFIX)) continue; + rolePermissionInserts++; + if (countOccurrences(sql, V19_ACCESS_PRESERVE_EDIT) == 1) { + preserveEdit++; + } else if (countOccurrences(sql, V19_ACCESS_FORCE_EDIT) == 1) { + forceEdit++; + } else { + throw new IllegalStateException( + "MIGRATION_V20261017_02_ROLE_PERMISSION_COMPAT_SHAPE_INVALID"); + } + } + if (rolePermissionInserts != 5 || preserveEdit != 4 || forceEdit != 1) { + throw new IllegalStateException("MIGRATION_V20261017_02_COMPAT_PLAN_INVALID"); + } + return; + } + if (V20261017_03_MIGRATION_ID.equals(migrationId)) { + int tables = 0; + int permissionInserts = 0; + for (SqlStep step : steps) { + String sql = step.getSql(); + if (sql.startsWith(V20261017_03_TABLE_PREFIX)) { + tables++; + if (countOccurrences(sql, "CREATE TABLE ") != 1) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_TABLE_COMPAT_SHAPE_INVALID"); + } + } + if (sql.startsWith(V20261017_03_PERMISSION_INSERT_PREFIX)) { + permissionInserts++; + if (countOccurrences(sql, "INSERT INTO sys_permission") != 1) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_PERMISSION_COMPAT_SHAPE_INVALID"); + } + } + } + if (tables != 6 || permissionInserts != 6) { + throw new IllegalStateException("MIGRATION_V20261017_03_COMPAT_PLAN_INVALID"); + } + return; + } + if (!V19_MIGRATION_ID.equals(migrationId)) return; + int mapping = 0; + int rolePermission = 0; + int upgradeOrValues = 0; + int preserveEdit = 0; + int preserveCurrent = 0; + int forceEdit = 0; + int derivedUpdate = 0; + for (SqlStep step : steps) { + String sql = step.getSql(); + if (sql.startsWith(V19_MAPPING_INSERT_PREFIX)) { + mapping++; + if (countOccurrences(sql, V19_LEGACY_MAPPING_JOIN) != 1) { + throw new IllegalStateException("MIGRATION_V19_MAPPING_COLLATION_COMPAT_SHAPE_INVALID"); + } + } + if (sql.startsWith("UPDATE authz_role_policy rp SET rp.assignment_source='DERIVED'")) { + derivedUpdate++; + if (!V19_DERIVED_UPDATE_LEGACY.equals(sql)) { + throw new IllegalStateException("MIGRATION_V19_DERIVED_SCOPE_COMPAT_SHAPE_INVALID"); + } + } + if (!sql.startsWith(V19_ROLE_PERMISSION_INSERT_PREFIX)) continue; + rolePermission++; + if (countOccurrences(sql, V19_ACCESS_UPGRADE_OR_VALUES) == 1) upgradeOrValues++; + else if (countOccurrences(sql, V19_ACCESS_PRESERVE_EDIT) == 1) preserveEdit++; + else if (countOccurrences(sql, V19_ACCESS_PRESERVE_CURRENT) == 1) preserveCurrent++; + else if (countOccurrences(sql, V19_ACCESS_FORCE_EDIT) == 1) forceEdit++; + else throw new IllegalStateException("MIGRATION_V19_ROLE_PERMISSION_COMPAT_SHAPE_INVALID"); + } + if (mapping != 1 || derivedUpdate != 1 || rolePermission != 11 || upgradeOrValues != 1 + || preserveEdit != 4 || preserveCurrent != 2 || forceEdit != 4) { + throw new IllegalStateException("MIGRATION_V19_COMPAT_PLAN_INVALID"); + } + } + + static void validateCompatibleAssertions(String migrationId, List assertions) { + if (V20261017_03_MIGRATION_ID.equals(migrationId)) { + int controls = 0; + for (Assertion assertion : assertions) { + if (!V20261017_03_CONTROLS_ASSERTION.equals(assertion.getCode())) continue; + controls++; + if (countOccurrences(assertion.getQuery(), V20261017_03_DIALOG_SCOPE_LEGACY) != 1) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_CONTROLS_ASSERTION_COMPAT_SHAPE_INVALID"); + } + } + if (controls != 1) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_CONTROLS_ASSERTION_COMPAT_PLAN_INVALID"); + } + return; + } + if (!V19_MIGRATION_ID.equals(migrationId)) return; + int derived = 0; + for (Assertion assertion : assertions) { + if (!V19_DERIVED_ASSERTION_CODE.equals(assertion.getCode())) continue; + derived++; + if (!V19_DERIVED_ASSERTION_LEGACY.equals(assertion.getQuery())) { + throw new IllegalStateException("MIGRATION_V19_DERIVED_ASSERTION_COMPAT_SHAPE_INVALID"); + } + } + if (derived != 1) { + throw new IllegalStateException("MIGRATION_V19_DERIVED_ASSERTION_COMPAT_PLAN_INVALID"); + } + } + + static void validateCompatiblePreconditions(String migrationId, List preconditions) { + if (!V20261017_03_MIGRATION_ID.equals(migrationId)) return; + int catalog = 0; + for (Assertion precondition : preconditions) { + if (!V20261017_03_CATALOG_PRECONDITION.equals(precondition.getCode())) continue; + catalog++; + if (!V20261017_03_CATALOG_PRECONDITION_LEGACY.equals(precondition.getQuery())) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_CATALOG_PRECONDITION_COMPAT_SHAPE_INVALID"); + } + } + if (catalog != 1) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_CATALOG_PRECONDITION_COMPAT_PLAN_INVALID"); + } + } + + static String compatiblePreconditionQuery(String migrationId, Assertion precondition, + MigrationStateMachine.Action action) { + if (!V20261017_03_MIGRATION_ID.equals(migrationId) + || !V20261017_03_CATALOG_PRECONDITION.equals(precondition.getCode())) { + return precondition.getQuery(); + } + if (!V20261017_03_CATALOG_PRECONDITION_LEGACY.equals(precondition.getQuery())) { + throw new IllegalStateException( + "MIGRATION_V20261017_03_CATALOG_PRECONDITION_COMPAT_SHAPE_INVALID"); + } + return action == MigrationStateMachine.Action.RESUME + ? V20261017_03_CATALOG_PRECONDITION_RESUME : precondition.getQuery(); + } + + static String compatibleAssertionQuery(String migrationId, Assertion assertion) { + if (V20261017_03_MIGRATION_ID.equals(migrationId) + && V20261017_03_CONTROLS_ASSERTION.equals(assertion.getCode())) { + return replaceUnique(assertion.getQuery(), V20261017_03_DIALOG_SCOPE_LEGACY, + V20261017_03_DIALOG_SCOPE_SAFE, + "MIGRATION_V20261017_03_CONTROLS_ASSERTION_COMPAT_SHAPE_INVALID"); + } + if (!V19_MIGRATION_ID.equals(migrationId) + || !V19_DERIVED_ASSERTION_CODE.equals(assertion.getCode())) { + return assertion.getQuery(); + } + if (!V19_DERIVED_ASSERTION_LEGACY.equals(assertion.getQuery())) { + throw new IllegalStateException("MIGRATION_V19_DERIVED_ASSERTION_COMPAT_SHAPE_INVALID"); + } + return V19_DERIVED_ASSERTION_SAFE; + } + + private static String replaceUnique(String sql, String legacy, String replacement, String error) { + int first = sql.indexOf(legacy); + if (first < 0 || first != sql.lastIndexOf(legacy)) { + throw new IllegalStateException(error); + } + return sql.substring(0, first) + replacement + sql.substring(first + legacy.length()); + } + + private static int countOccurrences(String value, String token) { + int count = 0; + int offset = 0; + while ((offset = value.indexOf(token, offset)) >= 0) { + count++; + offset += token.length(); + } + return count; + } + + static void validateRehearsalPlan(List entries, String rehearsalSchema) { + if (rehearsalSchema == null) return; + validateRehearsalSchemaName(rehearsalSchema); + Set observed = new LinkedHashSet<>(); + for (Entry entry : entries) { + int useCount = 0; + for (SqlStep step : entry.getPlan().getSteps()) { + if (!isUseStatement(step.getSql())) continue; + useCount++; + compatibleStepSql(entry.getMigrationId(), step.getSql(), rehearsalSchema); + } + boolean expected = LEGACY_USE_MIGRATIONS.contains(entry.getMigrationId()); + if ((expected && useCount != 1) || (!expected && useCount != 0)) { + throw new IllegalStateException("MIGRATION_REHEARSAL_USE_COUNT_INVALID"); + } + if (expected) observed.add(entry.getMigrationId()); + } + if (!observed.equals(LEGACY_USE_MIGRATIONS)) { + throw new IllegalStateException("MIGRATION_REHEARSAL_USE_PLAN_INVALID"); + } + } + + static void validateRehearsalSchemaName(String rehearsalSchema) { + if (rehearsalSchema == null + || !rehearsalSchema.matches(REHEARSAL_SCHEMA_PREFIX + "[a-z0-9_]{1,64}")) { + throw new IllegalArgumentException("MIGRATION_REHEARSAL_SCHEMA_INVALID"); + } + } + + static void validateRehearsalIdentity(String rehearsalSchema, String observedDatabase) { + if (rehearsalSchema == null) return; + validateRehearsalSchemaName(rehearsalSchema); + if (!rehearsalSchema.equals(observedDatabase)) { + throw new IllegalStateException("MIGRATION_REHEARSAL_DATABASE_MISMATCH"); + } + } + + private static void validateRehearsalConnection(Connection connection, String rehearsalSchema) + throws SQLException { + if (rehearsalSchema == null) return; + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT DATABASE()")) { + if (!rows.next()) throw new IllegalStateException("MIGRATION_REHEARSAL_DATABASE_MISMATCH"); + String observed = rows.getString(1); + if (rows.next()) throw new IllegalStateException("MIGRATION_REHEARSAL_DATABASE_MISMATCH"); + validateRehearsalIdentity(rehearsalSchema, observed); + } + } + + private static boolean isUseStatement(String sql) { + return sql != null && sql.trim().toUpperCase(Locale.ROOT).startsWith("USE "); + } + + static boolean isV13GeneratedExpressionCompatibilityAssertion(String migrationId, + String assertionCode) { + return V13_MIGRATION_ID.equals(migrationId) + && V13_ROUTE_TOKEN_GENERATED_ASSERTION.equals(assertionCode); + } + + static boolean v13RouteTokenGeneratedColumnMatches(String columnName, String columnType, + String nullable, String defaultValue, + String extra, String characterSet, + String collation, + String generationExpression) { + String expectedValueColumn; + if ("active_application_id".equals(columnName)) { + expectedValueColumn = "application_id"; + } else if ("active_user_id".equals(columnName)) { + expectedValueColumn = "user_id"; + } else { + return false; + } + if (!"bigint(20)".equals(columnType) + || !"YES".equals(nullable) + || defaultValue != null + || extra == null + || !"STORED GENERATED".equals(extra.toUpperCase(Locale.ROOT)) + || characterSet != null + || collation != null + || generationExpression == null) { + return false; + } + String normalized = generationExpression.replace("`", "") + .replaceAll("\\s+", "") + .toLowerCase(Locale.ROOT); + String isNullOperator = "if((consumed_atisnull)," + expectedValueColumn + ",null)"; + String isNullFunction = "if(isnull(consumed_at)," + expectedValueColumn + ",null)"; + return isNullOperator.equals(normalized) || isNullFunction.equals(normalized); + } + + static String readNormalized(Path path) throws IOException { + return normalize(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + } + + private static String normalize(String source) { + String normalized = source.replace("\r\n", "\n").replace('\r', '\n'); + return normalized.startsWith("\ufeff") ? normalized.substring(1) : normalized; + } + + static String checksum(String source) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(normalize(source).getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(64); + for (byte current : digest) result.append(String.format("%02x", current & 0xff)); + return result.toString(); + } catch (Exception e) { + throw new IllegalStateException("MIGRATION_CHECKSUM_UNAVAILABLE", e); + } + } + + private enum Mode { APPLY, PREFLIGHT, DRY_RUN } + + private static final class Arguments { + private final String url; + private final String user; + private final String passwordEnvironment; + private final String manifest; + private final Mode mode; + private final int lockTimeoutSeconds; + private final String rehearsalSchema; + + private Arguments(Map values) { + rejectUnknown(values); + this.manifest = required(values, "manifest"); + this.mode = parseMode(values.getOrDefault("mode", "apply")); + this.url = mode == Mode.DRY_RUN ? values.get("url") : required(values, "url"); + this.user = mode == Mode.DRY_RUN ? values.get("user") : required(values, "user"); + this.passwordEnvironment = mode == Mode.DRY_RUN + ? values.getOrDefault("password-env", "DB_PASSWORD") : required(values, "password-env"); + this.lockTimeoutSeconds = Integer.parseInt(values.getOrDefault("lock-timeout-seconds", "60")); + if (lockTimeoutSeconds < 0 || lockTimeoutSeconds > 3600) { + throw new IllegalArgumentException("MIGRATION_LOCK_TIMEOUT_INVALID"); + } + this.rehearsalSchema = values.get("rehearsal-schema"); + if (rehearsalSchema != null) { + if (mode == Mode.DRY_RUN) { + throw new IllegalArgumentException("MIGRATION_REHEARSAL_MODE_INVALID"); + } + validateRehearsalSchemaName(rehearsalSchema); + } + } + + private static Arguments parse(String[] args) { + Map values = new LinkedHashMap<>(); + for (String arg : args) { + if (!arg.startsWith("--") || arg.indexOf('=') < 3) { + throw new IllegalArgumentException("MIGRATION_ARGUMENT_INVALID:" + arg); + } + int split = arg.indexOf('='); + values.put(arg.substring(2, split), arg.substring(split + 1)); + } + return new Arguments(values); + } + + private static Mode parseMode(String value) { + String normalized = value == null ? "" : value.trim().replace('-', '_').toUpperCase(); + try { + return Mode.valueOf(normalized); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("MIGRATION_MODE_INVALID:" + value); + } + } + + private static void rejectUnknown(Map values) { + for (String key : values.keySet()) { + if (!("url".equals(key) || "user".equals(key) || "password-env".equals(key) + || "manifest".equals(key) || "mode".equals(key) + || "lock-timeout-seconds".equals(key) + || "rehearsal-schema".equals(key))) { + throw new IllegalArgumentException("MIGRATION_ARGUMENT_UNKNOWN:" + key); + } + } + } + + private static String required(Map values, String key) { + String value = values.get(key); + if (value == null || value.trim().isEmpty()) { + throw new IllegalArgumentException("MIGRATION_ARGUMENT_REQUIRED:" + key); + } + return value; + } + } +} diff --git a/src/main/java/com/finance/system/migration/TenantBackfillTool.java b/src/main/java/com/finance/system/migration/TenantBackfillTool.java new file mode 100644 index 0000000..125eb61 --- /dev/null +++ b/src/main/java/com/finance/system/migration/TenantBackfillTool.java @@ -0,0 +1,267 @@ +package com.finance.system.migration; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** Explicit, transactional tenant backfill. It never derives or defaults ownership. */ +public final class TenantBackfillTool { + private static final String LOCK_NAME = "finance-system-tenant-backfill"; + private static final Pattern TENANT = Pattern.compile("[A-Za-z0-9._-]{1,64}"); + private static final Pattern STRING_KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}"); + private static final Map TABLES = tableSpecs(); + + private TenantBackfillTool() { + } + + public static void main(String[] args) throws Exception { + Arguments arguments = Arguments.parse(args); + List mappings = parseMappings(Paths.get(arguments.mapping)); + String password = System.getenv(arguments.passwordEnvironment); + if (password == null) throw new IllegalArgumentException("TENANT_BACKFILL_PASSWORD_ENV_MISSING"); + try (Connection connection = DriverManager.getConnection(arguments.url, arguments.user, password)) { + connection.setAutoCommit(false); + acquireLock(connection, arguments.lockTimeoutSeconds); + try { + validateSchema(connection); + validateCoverage(connection, mappings); + if (arguments.dryRun) { + connection.rollback(); + System.out.println("租户数据回填试运行验证通过 TENANT_BACKFILL_DRY_RUN_OK"); + return; + } + apply(connection, mappings); + assertZeroNulls(connection); + connection.commit(); + System.out.println("租户数据回填已执行 TENANT_BACKFILL_APPLIED rows=" + mappings.size()); + } catch (Exception e) { + connection.rollback(); + throw e; + } finally { + releaseLock(connection); + } + } + } + + static List parseMappings(Path mappingPath) throws Exception { + Path path = mappingPath.toAbsolutePath().normalize(); + if (!Files.isRegularFile(path)) throw new IllegalArgumentException("TENANT_BACKFILL_MAPPING_MISSING"); + List lines = Files.readAllLines(path, StandardCharsets.UTF_8); + if (lines.isEmpty() || !"table,record_id,tenant_id".equals(stripBom(lines.get(0)).trim())) { + throw new IllegalArgumentException("TENANT_BACKFILL_MAPPING_HEADER_INVALID"); + } + List result = new ArrayList<>(); + Set unique = new LinkedHashSet<>(); + for (int i = 1; i < lines.size(); i++) { + String line = lines.get(i).trim(); + if (line.isEmpty() || line.startsWith("#")) continue; + String[] fields = line.split(",", -1); + if (fields.length != 3) throw new IllegalArgumentException("TENANT_BACKFILL_MAPPING_ROW_INVALID:" + (i + 1)); + String table = fields[0].trim(); + String key = fields[1].trim(); + String tenant = fields[2].trim(); + TableSpec spec = TABLES.get(table); + if (spec == null) throw new IllegalArgumentException("TENANT_BACKFILL_TABLE_NOT_ALLOWED:" + table); + if (!TENANT.matcher(tenant).matches()) throw new IllegalArgumentException("TENANT_BACKFILL_TENANT_INVALID:" + (i + 1)); + if (!spec.validKey(key)) throw new IllegalArgumentException("TENANT_BACKFILL_RECORD_ID_INVALID:" + (i + 1)); + if (!unique.add(table + "\u0000" + key)) throw new IllegalArgumentException("TENANT_BACKFILL_MAPPING_DUPLICATE:" + table + ":" + key); + result.add(new Mapping(spec, key, tenant)); + } + return Collections.unmodifiableList(result); + } + + private static void validateSchema(Connection connection) throws SQLException { + for (TableSpec spec : TABLES.values()) { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() " + + "AND table_name=? AND column_name IN (?, 'tenant_id')")) { + statement.setString(1, spec.table); + statement.setString(2, spec.keyColumn); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 2) { + throw new IllegalStateException("TENANT_BACKFILL_SCHEMA_MISSING:" + spec.table); + } + } + } + } + } + + private static void validateCoverage(Connection connection, List mappings) throws SQLException { + Map> byTable = new LinkedHashMap<>(); + for (String table : TABLES.keySet()) byTable.put(table, new ArrayList()); + for (Mapping mapping : mappings) byTable.get(mapping.spec.table).add(mapping); + for (TableSpec spec : TABLES.values()) { + long nullRows = scalarCount(connection, "SELECT COUNT(*) FROM " + spec.table + " WHERE tenant_id IS NULL"); + List tableMappings = byTable.get(spec.table); + System.out.println("租户数据回填计数 TENANT_BACKFILL_COUNT table=" + spec.table + " nullRows=" + nullRows + + " mappingRows=" + tableMappings.size()); + if (nullRows != tableMappings.size()) { + throw new IllegalStateException("TENANT_BACKFILL_MAPPING_COVERAGE_MISMATCH:" + spec.table); + } + for (Mapping mapping : tableMappings) { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT COUNT(*) FROM " + spec.table + " WHERE " + spec.keyColumn + "=? AND tenant_id IS NULL")) { + spec.bind(statement, 1, mapping.recordId); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getLong(1) != 1L) { + throw new IllegalStateException("TENANT_BACKFILL_RECORD_NOT_NULL_OR_MISSING:" + + spec.table + ":" + mapping.recordId); + } + } + } + } + } + } + + private static void apply(Connection connection, List mappings) throws SQLException { + for (Mapping mapping : mappings) { + TableSpec spec = mapping.spec; + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE " + spec.table + " SET tenant_id=? WHERE " + spec.keyColumn + "=? AND tenant_id IS NULL")) { + statement.setString(1, mapping.tenantId); + spec.bind(statement, 2, mapping.recordId); + int affected = statement.executeUpdate(); + if (affected != 1) throw new IllegalStateException("TENANT_BACKFILL_AFFECTED_ROWS:" + + spec.table + ":" + mapping.recordId + ":" + affected); + } + } + } + + private static void assertZeroNulls(Connection connection) throws SQLException { + for (TableSpec spec : TABLES.values()) { + if (scalarCount(connection, "SELECT COUNT(*) FROM " + spec.table + " WHERE tenant_id IS NULL") != 0L) { + throw new IllegalStateException("TENANT_BACKFILL_POSTFLIGHT_NULLS:" + spec.table); + } + } + } + + private static long scalarCount(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + if (!result.next()) throw new IllegalStateException("TENANT_BACKFILL_COUNT_EMPTY"); + return result.getLong(1); + } + } + + private static void acquireLock(Connection connection, int timeout) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT GET_LOCK(?,?)")) { + statement.setString(1, LOCK_NAME); statement.setInt(2, timeout); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 1) throw new IllegalStateException("TENANT_BACKFILL_LOCK_NOT_ACQUIRED"); + } + } + } + + private static void releaseLock(Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT RELEASE_LOCK(?)")) { + statement.setString(1, LOCK_NAME); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 1) throw new IllegalStateException("TENANT_BACKFILL_LOCK_RELEASE_FAILED"); + } + } + } + + private static String stripBom(String value) { + return value.startsWith("\ufeff") ? value.substring(1) : value; + } + + private static Map tableSpecs() { + Map result = new LinkedHashMap<>(); + for (TableSpec spec : Arrays.asList( + new TableSpec("reim_application", "id", true), + new TableSpec("reim_payment", "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), + new TableSpec("sys_kingdee_sync_run", "id", true), + new TableSpec("sys_scheduled_task", "task_code", false), + new TableSpec("feishu_directory_state", "id", true), + new TableSpec("feishu_directory_sync_run", "run_id", false))) result.put(spec.table, spec); + return Collections.unmodifiableMap(result); + } + + static final class Mapping { + final TableSpec spec; + final String recordId; + final String tenantId; + Mapping(TableSpec spec, String recordId, String tenantId) { + this.spec = spec; this.recordId = recordId; this.tenantId = tenantId; + } + } + + static final class TableSpec { + final String table; + final String keyColumn; + final boolean numeric; + TableSpec(String table, String keyColumn, boolean numeric) { + this.table = table; this.keyColumn = keyColumn; this.numeric = numeric; + } + boolean validKey(String value) { + if (numeric) { + try { return Long.parseLong(value) >= 0L; } catch (NumberFormatException e) { return false; } + } + return STRING_KEY.matcher(value).matches(); + } + void bind(PreparedStatement statement, int index, String value) throws SQLException { + if (numeric) statement.setLong(index, Long.parseLong(value)); else statement.setString(index, value); + } + } + + private static final class Arguments { + final String url; + final String user; + final String passwordEnvironment; + final String mapping; + final boolean dryRun; + final int lockTimeoutSeconds; + + private Arguments(Map values) { + for (String key : values.keySet()) { + if (!("url".equals(key) || "user".equals(key) || "password-env".equals(key) + || "mapping".equals(key) || "dry-run".equals(key) || "lock-timeout-seconds".equals(key))) { + throw new IllegalArgumentException("TENANT_BACKFILL_ARGUMENT_UNKNOWN:" + key); + } + } + url = required(values, "url"); user = required(values, "user"); + passwordEnvironment = required(values, "password-env"); mapping = required(values, "mapping"); + String dryRunValue = values.getOrDefault("dry-run", "true"); + if (!("true".equalsIgnoreCase(dryRunValue) || "false".equalsIgnoreCase(dryRunValue))) { + throw new IllegalArgumentException("TENANT_BACKFILL_DRY_RUN_INVALID:" + dryRunValue); + } + dryRun = Boolean.parseBoolean(dryRunValue); + lockTimeoutSeconds = Integer.parseInt(values.getOrDefault("lock-timeout-seconds", "60")); + if (lockTimeoutSeconds < 0 || lockTimeoutSeconds > 3600) throw new IllegalArgumentException("TENANT_BACKFILL_LOCK_TIMEOUT_INVALID"); + } + + static Arguments parse(String[] args) { + Map values = new LinkedHashMap<>(); + for (String arg : args) { + int split = arg.indexOf('='); + if (!arg.startsWith("--") || split < 3) throw new IllegalArgumentException("TENANT_BACKFILL_ARGUMENT_INVALID:" + arg); + values.put(arg.substring(2, split), arg.substring(split + 1)); + } + return new Arguments(values); + } + + static String required(Map values, String key) { + String value = values.get(key); + if (value == null || value.trim().isEmpty()) throw new IllegalArgumentException("TENANT_BACKFILL_ARGUMENT_REQUIRED:" + key); + return value; + } + } +} diff --git a/src/main/java/com/finance/system/migration/V19BoundRolePermissionRecovery.java b/src/main/java/com/finance/system/migration/V19BoundRolePermissionRecovery.java new file mode 100644 index 0000000..a983581 --- /dev/null +++ b/src/main/java/com/finance/system/migration/V19BoundRolePermissionRecovery.java @@ -0,0 +1,823 @@ +package com.finance.system.migration; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Database-bound, plan-hash-gated execution path for the V19 recovery. */ +final class V19BoundRolePermissionRecovery { + private static final String LOCK_NAME = "finance-system-schema-migration"; + private static final int EXPECTED_CHANGED_COUNT = 10; + private static final Pattern SEEDED_PERMISSION = Pattern.compile( + "(?:^|,)\\s*\\(\\s*'((?:''|[^'])+)'\\s*,", Pattern.DOTALL); + + private V19BoundRolePermissionRecovery() { + } + + public static void main(String[] args) throws Exception { + Arguments parsed = Arguments.parse(args); + Path snapshotRoot = Paths.get(parsed.snapshotDirectory).toAbsolutePath().normalize(); + SnapshotMetadata snapshot = loadSnapshot(snapshotRoot); + Set v19PermissionCodes = loadExpectedV19PermissionCodes(Paths.get(parsed.v19Script)); + Endpoint endpoint = Endpoint.parse(parsed.url); + Path planPath = Paths.get(parsed.planPath).toAbsolutePath().normalize(); + String approvedPlan = parsed.apply ? readApprovedPlan(planPath, parsed.expectedPlanHash) : null; + String password = System.getenv(parsed.passwordEnvironment); + if (password == null) throw new IllegalArgumentException("MIGRATION_PASSWORD_ENV_MISSING"); + + Execution execution; + try (Connection connection = DriverManager.getConnection(parsed.url, parsed.user, password)) { + acquireLock(connection, parsed.lockTimeoutSeconds); + try { + JdbcStore store = new JdbcStore(connection); + store.requireExactRunningHistory(); + execution = execute(store, snapshot, endpoint, v19PermissionCodes, + parsed.apply, approvedPlan, parsed.expectedPlanHash); + } finally { + releaseLock(connection); + } + } + boolean planWritten = false; + if (!parsed.apply && !Files.exists(planPath)) { + writeImmutablePlan(planPath, execution.plan.content); + planWritten = true; + } + System.out.println("V19 角色权限恢复" + (parsed.apply ? "已执行" : "已验证") + + ": baseline=" + execution.result.baselineCount + + " addedByV19=" + execution.result.added.size() + + " restored=" + execution.result.changes.size() + + " planFile=" + planPath + + " planFileWritten=" + planWritten + + " evidenceSha256=" + execution.plan.hash + + " manifestSha256=" + snapshot.verified.manifestHash + + " rolePermissionSha256=" + snapshot.verified.rolePermissionHash); + } + + static SnapshotMetadata loadSnapshot(Path root) throws IOException { + V19RolePermissionRecovery.Snapshot verified = V19RolePermissionRecovery.loadAndVerifySnapshot( + root, V19RolePermissionRecovery.APPROVED_MANIFEST_HASH, + V19RolePermissionRecovery.APPROVED_ROLE_PERMISSION_HASH); + return new SnapshotMetadata(verified, + parseIdCode(root.resolve("roles.tsv"), "id\trole_code\tstatus"), + parseIdCode(root.resolve("policy_metadata.tsv"), + "id\tpolicy_code\teffect\tdata_scope\tscope_parameter\tprotected_policy\tdelegable\trisk_level\tenabled"), + parseIdCode(root.resolve("permission_catalog.tsv"), + "id\tpermission_code\tpermission_type\tparent_code\tpermission_layer\tsort_order\tresource\tdefault_access\tdelegable\trisk_level"), + parseHistory(root.resolve("migration_history.tsv"))); + } + + static Set loadExpectedV19PermissionCodes(Path script) throws IOException { + String source = MySqlMigrationRunner.readNormalized(script.toAbsolutePath().normalize()); + if (!V19RolePermissionRecovery.V19_CHECKSUM.equals(MySqlMigrationRunner.checksum(source))) { + throw new IllegalStateException("V19_RECOVERY_SCRIPT_CHECKSUM_MISMATCH"); + } + List statements = new ArrayList<>(); + for (MigrationScriptParser.SqlStep step : MigrationScriptParser.parse(source).getSteps()) { + if (step.getSql().startsWith("INSERT INTO sys_permission(permission_code,")) { + statements.add(step.getSql()); + } + } + if (statements.size() != 1) throw new IllegalStateException("V19_RECOVERY_PERMISSION_SEED_SHAPE_INVALID"); + String statement = statements.get(0); + int valuesAt = statement.indexOf(" VALUES"); + int duplicateAt = statement.indexOf("ON DUPLICATE KEY UPDATE"); + if (valuesAt < 0 || duplicateAt <= valuesAt) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_SEED_SHAPE_INVALID"); + } + Set result = new LinkedHashSet<>(); + Matcher matcher = SEEDED_PERMISSION.matcher(statement.substring(valuesAt + 7, duplicateAt)); + while (matcher.find()) { + String code = matcher.group(1).replace("''", "'"); + if (!code.matches("[A-Za-z0-9:._-]{1,160}") || !result.add(code)) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_SEED_INVALID"); + } + } + if (result.isEmpty()) throw new IllegalStateException("V19_RECOVERY_PERMISSION_SEED_EMPTY"); + return Collections.unmodifiableSet(result); + } + + private static Map parseIdCode(Path file, String expectedHeader) throws IOException { + List lines = Files.readAllLines(file, StandardCharsets.UTF_8); + if (lines.isEmpty() || !expectedHeader.equals(stripBom(lines.get(0)))) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_METADATA_HEADER_INVALID:" + file.getFileName()); + } + Map result = new LinkedHashMap<>(); + for (int index = 1; index < lines.size(); index++) { + if (lines.get(index).trim().isEmpty()) continue; + String[] parts = lines.get(index).split("\\t", -1); + if (parts.length < 2 || parts[1].trim().isEmpty()) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_METADATA_ROW_INVALID:" + file.getFileName()); + } + long id = positiveId(parts[0], "V19_RECOVERY_SNAPSHOT_METADATA_ROW_INVALID"); + if (result.put(id, parts[1]) != null) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_METADATA_DUPLICATE:" + file.getFileName()); + } + } + if (result.isEmpty()) throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_METADATA_EMPTY:" + file.getFileName()); + return Collections.unmodifiableMap(result); + } + + private static Map parseHistory(Path file) throws IOException { + List lines = Files.readAllLines(file, StandardCharsets.UTF_8); + if (lines.isEmpty() || !"migration_id\tchecksum\tstatus\tstarted_at\tapplied_at".equals(stripBom(lines.get(0)))) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_HEADER_INVALID"); + } + Map result = new LinkedHashMap<>(); + for (int index = 1; index < lines.size(); index++) { + if (lines.get(index).trim().isEmpty()) continue; + String[] parts = lines.get(index).split("\\t", -1); + if (parts.length != 5 || !parts[0].matches("V[0-9]{8}_[0-9]{2}__[A-Za-z0-9_]+") + || !parts[1].matches("[0-9a-fA-F]{64}")) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_ROW_INVALID"); + } + if (result.put(parts[0], new HistoryRow(parts[1].toLowerCase(Locale.ROOT), parts[2])) != null) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_DUPLICATE"); + } + } + return Collections.unmodifiableMap(result); + } + + static Execution execute(Store store, SnapshotMetadata snapshot, Endpoint endpoint, + Set v19PermissionCodes, boolean apply, + String approvedPlan, String expectedPlanHash) throws Exception { + boolean transactionStarted = false; + try { + if (apply) { + store.begin(); + transactionStarted = true; + } + TargetIdentity target = store.loadTargetIdentity(endpoint); + validateTarget(snapshot, target, v19PermissionCodes); + Set allowedNewPermissionIds = allowedNewPermissionIds( + snapshot, target, v19PermissionCodes); + Map current = store.loadCurrent(apply); + Map allowed = store.loadAllowedV19Added(); + Set allowedPreexistingAncestors = + allowedPreexistingAncestorKeys(snapshot, target, current, allowedNewPermissionIds); + RecoveryResult before = analyze(snapshot.verified.rolePermissions, current, allowed, + allowedNewPermissionIds, allowedPreexistingAncestors, + snapshot.permissions.keySet()); + RecoveryPlan plan = buildPlan(snapshot, target, before); + if (!apply) return new Execution(before, plan); + if (expectedPlanHash == null || !expectedPlanHash.equals(plan.hash) + || approvedPlan == null || !approvedPlan.equals(plan.content)) { + throw new IllegalStateException("V19_RECOVERY_PLAN_MISMATCH"); + } + store.restoreChanges(before.changes); + RecoveryResult after = analyze(snapshot.verified.rolePermissions, store.loadCurrent(true), allowed, + allowedNewPermissionIds, allowedPreexistingAncestors, + snapshot.permissions.keySet()); + if (!after.changes.isEmpty()) throw new IllegalStateException("V19_RECOVERY_POSTCONDITION_FAILED"); + store.commit(); + return new Execution(before, plan); + } catch (Exception failure) { + if (transactionStarted) store.rollback(); + throw failure; + } + } + + static void validateTarget(SnapshotMetadata snapshot, TargetIdentity target, + Set v19PermissionCodes) { + if (!target.endpoint.database.equals(target.observedDatabase)) { + throw new IllegalStateException("V19_RECOVERY_DATABASE_IDENTITY_MISMATCH"); + } + if (!snapshot.roles.equals(target.roles)) throw new IllegalStateException("V19_RECOVERY_ROLE_METADATA_MISMATCH"); + if (!snapshot.policies.equals(target.policies)) throw new IllegalStateException("V19_RECOVERY_POLICY_METADATA_MISMATCH"); + for (Map.Entry expected : snapshot.permissions.entrySet()) { + if (!expected.getValue().equals(target.permissions.get(expected.getKey()))) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_METADATA_MISMATCH"); + } + } + Set expectedNewCodes = new LinkedHashSet<>(v19PermissionCodes); + expectedNewCodes.removeAll(new LinkedHashSet<>(snapshot.permissions.values())); + Set actualNewCodes = new LinkedHashSet<>(); + for (Map.Entry current : target.permissions.entrySet()) { + if (!snapshot.permissions.containsKey(current.getKey())) actualNewCodes.add(current.getValue()); + } + if (actualNewCodes.size() != target.permissions.size() - snapshot.permissions.size() + || !actualNewCodes.equals(expectedNewCodes)) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_CATALOG_DIFF_INVALID"); + } + validatePermissionTree(target); + if (snapshot.history.size() != 18 || target.history.size() != 19) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_METADATA_COUNT_INVALID"); + } + for (Map.Entry expected : snapshot.history.entrySet()) { + HistoryRow current = target.history.get(expected.getKey()); + if (current == null || !expected.getValue().checksum.equals(current.checksum) + || !"APPLIED".equals(expected.getValue().status) || !"APPLIED".equals(current.status)) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_METADATA_MISMATCH"); + } + } + HistoryRow v19 = target.history.get(V19RolePermissionRecovery.V19_ID); + if (v19 == null || !V19RolePermissionRecovery.V19_CHECKSUM.equals(v19.checksum) + || !"RUNNING".equals(v19.status)) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_STATE_INVALID"); + } + } + + private static Set allowedNewPermissionIds(SnapshotMetadata snapshot, + TargetIdentity target, + Set v19PermissionCodes) { + Set result = new LinkedHashSet<>(); + for (Map.Entry permission : target.permissions.entrySet()) { + if (!snapshot.permissions.containsKey(permission.getKey()) + && v19PermissionCodes.contains(permission.getValue())) { + result.add(permission.getKey()); + } + } + return result; + } + + private static void validatePermissionTree(TargetIdentity target) { + Set codes = new LinkedHashSet<>(target.permissions.values()); + if (codes.size() != target.permissions.size() + || !target.permissionParents.keySet().equals(codes)) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_TREE_METADATA_INVALID"); + } + for (String code : codes) { + Set visited = new LinkedHashSet<>(); + String cursor = code; + while (cursor != null) { + if (!visited.add(cursor)) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_TREE_CYCLE"); + } + String parent = target.permissionParents.get(cursor); + if (parent != null && !codes.contains(parent)) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_TREE_ORPHAN"); + } + cursor = parent; + } + } + } + + private static Set allowedPreexistingAncestorKeys( + SnapshotMetadata snapshot, TargetIdentity target, + Map current, + Set allowedNewPermissionIds) { + Map idsByCode = new HashMap<>(); + for (Map.Entry entry : target.permissions.entrySet()) { + if (idsByCode.put(entry.getValue(), entry.getKey()) != null) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_TREE_METADATA_INVALID"); + } + } + Set result = new LinkedHashSet<>(); + for (V19RolePermissionRecovery.RolePermissionKey key : current.keySet()) { + if (!allowedNewPermissionIds.contains(key.permissionId)) continue; + String cursor = target.permissionParents.get(target.permissions.get(key.permissionId)); + while (cursor != null) { + Long ancestorId = idsByCode.get(cursor); + if (ancestorId == null) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_TREE_ORPHAN"); + } + if (snapshot.permissions.containsKey(ancestorId)) { + result.add(new V19RolePermissionRecovery.RolePermissionKey(key.roleId, ancestorId)); + } + cursor = target.permissionParents.get(cursor); + } + } + return result; + } + + static RecoveryResult analyze(Map baseline, + Map current, + Map allowed, + Set allowedNewPermissionIds, + Set allowedPreexistingAncestors, + Set preexistingPermissionIds) { + List changes = new ArrayList<>(); + for (Map.Entry entry : baseline.entrySet()) { + String observed = current.get(entry.getKey()); + if (observed == null) throw new IllegalStateException("V19_RECOVERY_BASELINE_ROW_MISSING"); + if (!entry.getValue().equals(observed)) { + if (!"READ".equals(entry.getValue()) || !"EDIT".equals(observed)) { + throw new IllegalStateException("V19_RECOVERY_BASELINE_DIFF_UNEXPECTED"); + } + changes.add(new Change(entry.getKey(), entry.getValue(), observed)); + } + } + List added = new ArrayList<>(); + for (Map.Entry entry : current.entrySet()) { + if (baseline.containsKey(entry.getKey())) continue; + String expected = allowed.get(entry.getKey()); + boolean preexistingPermission = preexistingPermissionIds.contains(entry.getKey().permissionId); + boolean mappedExact = !preexistingPermission + && expected != null && expected.equals(entry.getValue()); + boolean v19CatalogRow = !preexistingPermission + && allowedNewPermissionIds.contains(entry.getKey().permissionId) + && ("READ".equals(entry.getValue()) || "EDIT".equals(entry.getValue())); + boolean provenAncestor = preexistingPermission + && "READ".equals(entry.getValue()) + && allowedPreexistingAncestors.contains(entry.getKey()); + if (!mappedExact && !v19CatalogRow && !provenAncestor) { + throw new IllegalStateException("V19_RECOVERY_ADDED_ROW_UNEXPECTED"); + } + added.add(new Added(entry.getKey(), entry.getValue())); + } + if (changes.size() != 0 && changes.size() != EXPECTED_CHANGED_COUNT) { + throw new IllegalStateException("V19_RECOVERY_BASELINE_DIFF_COUNT_INVALID:" + changes.size()); + } + Collections.sort(changes, Change.ORDER); + Collections.sort(added, Added.ORDER); + return new RecoveryResult(baseline.size(), changes, added); + } + + static RecoveryPlan buildPlan(SnapshotMetadata snapshot, TargetIdentity target, RecoveryResult result) { + StringBuilder text = new StringBuilder(); + text.append("V19_ROLE_PERMISSION_RECOVERY_PLAN\t1\n") + .append("v19Checksum\t").append(V19RolePermissionRecovery.V19_CHECKSUM).append('\n') + .append("snapshotManifestSha256\t").append(snapshot.verified.manifestHash).append('\n') + .append("snapshotRolePermissionsSha256\t").append(snapshot.verified.rolePermissionHash).append('\n') + .append("jdbcHost\t").append(target.endpoint.host).append('\n') + .append("jdbcPort\t").append(target.endpoint.port).append('\n') + .append("jdbcDatabase\t").append(target.endpoint.database).append('\n') + .append("observedDatabase\t").append(target.observedDatabase).append('\n') + .append("serverUuid\t").append(target.serverUuid).append('\n') + .append("rolesSha256\t").append(hashIdCode(target.roles)).append('\n') + .append("policiesSha256\t").append(hashIdCode(target.policies)).append('\n') + .append("permissionsSha256\t").append(hashIdCode(target.permissions)).append('\n') + .append("permissionTreeSha256\t").append(hashStringMap(target.permissionParents)).append('\n') + .append("historySha256\t").append(hashHistory(target.history)).append('\n') + .append("changeCount\t").append(result.changes.size()).append('\n') + .append("addedCount\t").append(result.added.size()).append('\n'); + for (Map.Entry permission : target.permissions.entrySet()) { + if (!snapshot.permissions.containsKey(permission.getKey())) { + text.append("NEW_PERMISSION\t").append(permission.getKey()).append('\t') + .append(permission.getValue()).append('\n'); + } + } + for (Change change : result.changes) { + text.append("CHANGE\t").append(change.key.roleId).append('\t') + .append(change.key.permissionId).append('\t').append(change.from) + .append('\t').append(change.to).append('\n'); + } + for (Added entry : result.added) { + text.append("ADDED\t").append(entry.key.roleId).append('\t') + .append(entry.key.permissionId).append('\t').append(entry.access).append('\n'); + } + return new RecoveryPlan(text.toString()); + } + + static void writeImmutablePlan(Path path, String content) throws IOException { + byte[] expected = content.getBytes(StandardCharsets.UTF_8); + if (Files.exists(path)) { + if (!Files.isRegularFile(path) || !Arrays.equals(Files.readAllBytes(path), expected)) { + throw new IllegalStateException("V19_RECOVERY_PLAN_FILE_IMMUTABLE_MISMATCH"); + } + return; + } + if (path.getParent() == null || !Files.isDirectory(path.getParent())) { + throw new IllegalStateException("V19_RECOVERY_PLAN_DIRECTORY_INVALID"); + } + Files.write(path, expected, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); + } + + private static String readApprovedPlan(Path path, String expectedHash) throws IOException { + if (expectedHash == null || !expectedHash.matches("[0-9a-f]{64}") || !Files.isRegularFile(path)) { + throw new IllegalStateException("V19_RECOVERY_EXPECTED_PLAN_REQUIRED"); + } + byte[] bytes = Files.readAllBytes(path); + if (!expectedHash.equals(sha256(bytes))) { + throw new IllegalStateException("V19_RECOVERY_PLAN_FILE_HASH_MISMATCH"); + } + return new String(bytes, StandardCharsets.UTF_8); + } + + interface Store { + void begin() throws Exception; + TargetIdentity loadTargetIdentity(Endpoint endpoint) throws Exception; + Map loadCurrent(boolean forUpdate) throws Exception; + Map loadAllowedV19Added() throws Exception; + void restoreChanges(List changes) throws Exception; + void commit() throws Exception; + void rollback() throws Exception; + } + + private static final class JdbcStore implements Store { + private final Connection connection; + + private JdbcStore(Connection connection) { this.connection = connection; } + + private void requireExactRunningHistory() throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT checksum,status FROM sys_schema_migration WHERE migration_id=?")) { + statement.setString(1, V19RolePermissionRecovery.V19_ID); + try (ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + V19RolePermissionRecovery.requireExactRunningHistory(null, null, 0); + return; + } + String checksum = rows.getString(1); + String status = rows.getString(2); + V19RolePermissionRecovery.requireExactRunningHistory(checksum, status, rows.next() ? 2 : 1); + } + } + } + + @Override public void begin() throws SQLException { connection.setAutoCommit(false); } + + @Override + public TargetIdentity loadTargetIdentity(Endpoint endpoint) throws SQLException { + String database; + String serverUuid; + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT DATABASE(),@@server_uuid")) { + if (!rows.next()) throw new IllegalStateException("V19_RECOVERY_DATABASE_IDENTITY_MISSING"); + database = rows.getString(1); + serverUuid = rows.getString(2); + if (rows.next()) throw new IllegalStateException("V19_RECOVERY_DATABASE_IDENTITY_INVALID"); + } + if (database == null || serverUuid == null || !serverUuid.matches("[0-9a-fA-F-]{36}")) { + throw new IllegalStateException("V19_RECOVERY_DATABASE_IDENTITY_INVALID"); + } + return new TargetIdentity(endpoint, database, serverUuid.toLowerCase(Locale.ROOT), + loadIdCode("SELECT id,role_code FROM sys_role ORDER BY id"), + loadIdCode("SELECT id,policy_code FROM authz_policy ORDER BY id"), + loadIdCode("SELECT id,permission_code FROM sys_permission ORDER BY id"), + loadPermissionParents(), loadHistory()); + } + + private Map loadIdCode(String sql) throws SQLException { + Map result = new LinkedHashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery(sql)) { + while (rows.next()) { + if (result.put(rows.getLong(1), rows.getString(2)) != null) { + throw new IllegalStateException("V19_RECOVERY_TARGET_METADATA_DUPLICATE"); + } + } + } + return result; + } + + private Map loadPermissionParents() throws SQLException { + Map result = new LinkedHashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery( + "SELECT permission_code,parent_code FROM sys_permission ORDER BY permission_code")) { + while (rows.next()) { + if (result.put(rows.getString(1), rows.getString(2)) != null) { + throw new IllegalStateException("V19_RECOVERY_PERMISSION_TREE_METADATA_INVALID"); + } + } + } + return result; + } + + private Map loadHistory() throws SQLException { + Map result = new LinkedHashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery( + "SELECT migration_id,checksum,status FROM sys_schema_migration ORDER BY migration_id")) { + while (rows.next()) { + if (result.put(rows.getString(1), new HistoryRow( + rows.getString(2).toLowerCase(Locale.ROOT), rows.getString(3))) != null) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_DUPLICATE"); + } + } + } + return result; + } + + @Override + public Map loadCurrent(boolean forUpdate) + throws SQLException { + String sql = "SELECT role_id,permission_id,access_level FROM sys_role_permission " + + "ORDER BY role_id,permission_id" + (forUpdate ? " FOR UPDATE" : ""); + Map result = new LinkedHashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery(sql)) { + while (rows.next()) { + V19RolePermissionRecovery.RolePermissionKey key = + new V19RolePermissionRecovery.RolePermissionKey(rows.getLong(1), rows.getLong(2)); + if (result.put(key, rows.getString(3)) != null) { + throw new IllegalStateException("V19_RECOVERY_CURRENT_DUPLICATE"); + } + } + } + return result; + } + + @Override + public Map loadAllowedV19Added() + throws SQLException { + Map result = new HashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery( + "SELECT DISTINCT rp.role_id,m.permission_id,m.min_access_level " + + "FROM authz_role_policy rp JOIN authz_permission_policy_map m ON m.policy_id=rp.policy_id")) { + while (rows.next()) { + V19RolePermissionRecovery.RolePermissionKey key = + new V19RolePermissionRecovery.RolePermissionKey(rows.getLong(1), rows.getLong(2)); + String prior = result.put(key, rows.getString(3)); + if (prior != null && !prior.equals(rows.getString(3))) { + throw new IllegalStateException("V19_RECOVERY_ALLOWED_ROW_AMBIGUOUS"); + } + } + } + return result; + } + + @Override + public void restoreChanges(List changes) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE sys_role_permission SET access_level=? " + + "WHERE role_id=? AND permission_id=? AND access_level=?")) { + for (Change change : changes) { + statement.setString(1, change.from); + statement.setLong(2, change.key.roleId); + statement.setLong(3, change.key.permissionId); + statement.setString(4, change.to); + statement.addBatch(); + } + int[] counts = statement.executeBatch(); + if (counts.length != changes.size()) throw new IllegalStateException("V19_RECOVERY_UPDATE_COUNT_INVALID"); + for (int count : counts) { + if (count != 1) throw new IllegalStateException("V19_RECOVERY_UPDATE_COUNT_INVALID"); + } + } + } + + @Override public void commit() throws SQLException { connection.commit(); } + @Override public void rollback() throws SQLException { connection.rollback(); } + } + + static final class Endpoint { + final String host; + final int port; + final String database; + + Endpoint(String host, int port, String database) { + this.host = host; + this.port = port; + this.database = database; + } + + static Endpoint parse(String url) { + try { + if (url == null || !url.startsWith("jdbc:mysql://")) throw new IllegalArgumentException(); + URI uri = URI.create(url.substring("jdbc:".length())); + String path = uri.getPath(); + if (uri.getHost() == null || uri.getRawUserInfo() != null + || path == null || !path.matches("/[A-Za-z0-9_$-]+")) { + throw new IllegalArgumentException(); + } + return new Endpoint(uri.getHost().toLowerCase(Locale.ROOT), + uri.getPort() < 0 ? 3306 : uri.getPort(), path.substring(1)); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("V19_RECOVERY_JDBC_ENDPOINT_INVALID"); + } + } + } + + static final class SnapshotMetadata { + final V19RolePermissionRecovery.Snapshot verified; + final Map roles; + final Map policies; + final Map permissions; + final Map history; + + SnapshotMetadata(V19RolePermissionRecovery.Snapshot verified, Map roles, + Map policies, Map permissions, + Map history) { + this.verified = verified; + this.roles = roles; + this.policies = policies; + this.permissions = permissions; + this.history = history; + } + } + + static final class TargetIdentity { + final Endpoint endpoint; + final String observedDatabase; + final String serverUuid; + final Map roles; + final Map policies; + final Map permissions; + final Map permissionParents; + final Map history; + + TargetIdentity(Endpoint endpoint, String observedDatabase, String serverUuid, + Map roles, Map policies, + Map permissions, Map permissionParents, + Map history) { + this.endpoint = endpoint; + this.observedDatabase = observedDatabase; + this.serverUuid = serverUuid; + this.roles = roles; + this.policies = policies; + this.permissions = permissions; + this.permissionParents = permissionParents; + this.history = history; + } + } + + static final class HistoryRow { + final String checksum; + final String status; + + HistoryRow(String checksum, String status) { this.checksum = checksum; this.status = status; } + } + + static final class Change { + static final Comparator ORDER = Comparator + .comparingLong((Change value) -> value.key.roleId) + .thenComparingLong(value -> value.key.permissionId); + final V19RolePermissionRecovery.RolePermissionKey key; + final String from; + final String to; + + Change(V19RolePermissionRecovery.RolePermissionKey key, String from, String to) { + this.key = key; this.from = from; this.to = to; + } + } + + static final class Added { + static final Comparator ORDER = Comparator + .comparingLong((Added value) -> value.key.roleId) + .thenComparingLong(value -> value.key.permissionId); + final V19RolePermissionRecovery.RolePermissionKey key; + final String access; + + Added(V19RolePermissionRecovery.RolePermissionKey key, String access) { + this.key = key; this.access = access; + } + } + + static final class RecoveryResult { + final int baselineCount; + final List changes; + final List added; + + RecoveryResult(int baselineCount, List changes, List added) { + this.baselineCount = baselineCount; + this.changes = Collections.unmodifiableList(new ArrayList<>(changes)); + this.added = Collections.unmodifiableList(new ArrayList<>(added)); + } + } + + static final class RecoveryPlan { + final String content; + final String hash; + + RecoveryPlan(String content) { + this.content = content; + this.hash = sha256(content.getBytes(StandardCharsets.UTF_8)); + } + } + + static final class Execution { + final RecoveryResult result; + final RecoveryPlan plan; + + Execution(RecoveryResult result, RecoveryPlan plan) { this.result = result; this.plan = plan; } + } + + private static final class Arguments { + final String url; + final String user; + final String passwordEnvironment; + final String snapshotDirectory; + final String v19Script; + final String planPath; + final String expectedPlanHash; + final boolean apply; + final int lockTimeoutSeconds; + + private Arguments(Map values) { + Set allowed = new LinkedHashSet<>(Arrays.asList("url", "user", "password-env", + "snapshot", "v19-script", "plan", "expected-plan-hash", "mode", "lock-timeout-seconds")); + for (String key : values.keySet()) { + if (!allowed.contains(key)) throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_UNKNOWN:" + key); + } + url = required(values, "url"); + user = required(values, "user"); + passwordEnvironment = values.getOrDefault("password-env", "DB_PASSWORD"); + snapshotDirectory = required(values, "snapshot"); + v19Script = required(values, "v19-script"); + planPath = required(values, "plan"); + String mode = values.getOrDefault("mode", "validate"); + if (!"validate".equals(mode) && !"apply".equals(mode)) throw new IllegalArgumentException("V19_RECOVERY_MODE_INVALID"); + apply = "apply".equals(mode); + String hash = values.get("expected-plan-hash"); + if (apply && (hash == null || !hash.toLowerCase(Locale.ROOT).matches("[0-9a-f]{64}"))) { + throw new IllegalArgumentException("V19_RECOVERY_EXPECTED_PLAN_REQUIRED"); + } + if (!apply && hash != null) throw new IllegalArgumentException("V19_RECOVERY_EXPECTED_PLAN_NOT_ALLOWED"); + expectedPlanHash = hash == null ? null : hash.toLowerCase(Locale.ROOT); + lockTimeoutSeconds = Integer.parseInt(values.getOrDefault("lock-timeout-seconds", "60")); + if (lockTimeoutSeconds < 0 || lockTimeoutSeconds > 3600) { + throw new IllegalArgumentException("V19_RECOVERY_LOCK_TIMEOUT_INVALID"); + } + } + + static Arguments parse(String[] args) { + Map values = new LinkedHashMap<>(); + for (String arg : args) { + if (!arg.startsWith("--") || arg.indexOf('=') < 3) throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_INVALID"); + int split = arg.indexOf('='); + if (values.put(arg.substring(2, split), arg.substring(split + 1)) != null) { + throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_DUPLICATE"); + } + } + return new Arguments(values); + } + + private static String required(Map values, String key) { + String value = values.get(key); + if (value == null || value.trim().isEmpty()) throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_REQUIRED:" + key); + return value; + } + } + + private static long positiveId(String value, String error) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0) throw new NumberFormatException(); + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalStateException(error); + } + } + + private static String stripBom(String value) { return value.startsWith("\ufeff") ? value.substring(1) : value; } + + private static String hashIdCode(Map values) { + StringBuilder text = new StringBuilder(); + List keys = new ArrayList<>(values.keySet()); + Collections.sort(keys); + for (Long key : keys) text.append(key).append('\t').append(values.get(key)).append('\n'); + return sha256(text.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static String hashHistory(Map values) { + StringBuilder text = new StringBuilder(); + List keys = new ArrayList<>(values.keySet()); + Collections.sort(keys); + for (String key : keys) { + HistoryRow row = values.get(key); + text.append(key).append('\t').append(row.checksum).append('\t').append(row.status).append('\n'); + } + return sha256(text.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static String hashStringMap(Map values) { + StringBuilder text = new StringBuilder(); + List keys = new ArrayList<>(values.keySet()); + Collections.sort(keys); + for (String key : keys) { + text.append(key).append('\t').append(values.get(key) == null ? "" : values.get(key)).append('\n'); + } + return sha256(text.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(64); + for (byte value : digest) result.append(String.format("%02x", value & 0xff)); + return result.toString(); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("V19_RECOVERY_HASH_UNAVAILABLE", impossible); + } + } + + private static void acquireLock(Connection connection, int timeoutSeconds) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT GET_LOCK(?,?)")) { + statement.setString(1, LOCK_NAME); + statement.setInt(2, timeoutSeconds); + try (ResultSet rows = statement.executeQuery()) { + if (!rows.next() || rows.getInt(1) != 1) throw new IllegalStateException("MIGRATION_LOCK_NOT_ACQUIRED"); + } + } + } + + private static void releaseLock(Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT RELEASE_LOCK(?)")) { + statement.setString(1, LOCK_NAME); + try (ResultSet rows = statement.executeQuery()) { + if (!rows.next() || rows.getInt(1) != 1) throw new IllegalStateException("MIGRATION_LOCK_RELEASE_FAILED"); + } + } + } +} diff --git a/src/main/java/com/finance/system/migration/V19RolePermissionRecovery.java b/src/main/java/com/finance/system/migration/V19RolePermissionRecovery.java new file mode 100644 index 0000000..74505c7 --- /dev/null +++ b/src/main/java/com/finance/system/migration/V19RolePermissionRecovery.java @@ -0,0 +1,431 @@ +package com.finance.system.migration; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * One-purpose recovery for the reviewed V19 RUNNING state. Validation restores only + * pre-existing role-permission access levels from the pinned pre-apply snapshot; + * V19-added rows, canonical policies, schema history and all other data are left + * untouched. + */ +public final class V19RolePermissionRecovery { + static final String V19_ID = "V20261009_19__menu_tree_derived_authorization"; + static final String V19_CHECKSUM = + "9a38146e6f5060d670fa088ebb9cd0315e50b64515dae83d9cd347d46c1cddb5"; + static final String APPROVED_MANIFEST_HASH = + "c607325e43217c2117234c3c29bf53f9917c5cb90d4a8465184064b7fea96712"; + static final String APPROVED_ROLE_PERMISSION_HASH = + "acaa335e95e5964bb25450cf0a4f513e183610a63a7eb73943b7310467c8651f"; + private static final String LOCK_NAME = "finance-system-schema-migration"; + private static final Set EXPECTED_SNAPSHOT_FILES = Collections.unmodifiableSet( + new LinkedHashSet<>(Arrays.asList( + "effective_role_policy.tsv", "migration_history.tsv", "permission_catalog.tsv", + "policy_metadata.tsv", "policy_version.tsv", "profile_versions.tsv", + "relevant_table_shapes.tsv", "role_permissions.tsv", "role_policy_sets.tsv", + "roles.tsv", "v19_pre_shape.tsv"))); + + private V19RolePermissionRecovery() { + } + + public static void main(String[] args) throws Exception { + V19BoundRolePermissionRecovery.main(args); + } + + static Snapshot loadAndVerifySnapshot(Path directory, String expectedManifestHash, + String expectedRolePermissionHash) throws IOException { + Path root = directory.toAbsolutePath().normalize(); + Path manifest = root.resolve("SHA256SUMS.tsv"); + if (!Files.isRegularFile(manifest) + || !sha256(manifest).equals(expectedManifestHash.toLowerCase(Locale.ROOT))) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_MANIFEST_HASH_MISMATCH"); + } + Map entries = new LinkedHashMap<>(); + for (String line : Files.readAllLines(manifest, StandardCharsets.UTF_8)) { + String normalized = stripBom(line); + if (normalized.trim().isEmpty()) continue; + String[] parts = normalized.split("\\t", -1); + if (parts.length != 3 || !parts[0].matches("[A-Za-z0-9_.-]+")) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_MANIFEST_INVALID"); + } + ManifestEntry previous = entries.put(parts[0], + new ManifestEntry(Long.parseLong(parts[1]), parts[2].toLowerCase(Locale.ROOT))); + if (previous != null) throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_MANIFEST_DUPLICATE"); + } + if (!entries.keySet().equals(EXPECTED_SNAPSHOT_FILES)) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_MANIFEST_CONTENT_INVALID"); + } + for (Map.Entry entry : entries.entrySet()) { + Path file = root.resolve(entry.getKey()).normalize(); + if (!file.getParent().equals(root) || !Files.isRegularFile(file) + || Files.size(file) != entry.getValue().length + || !sha256(file).equals(entry.getValue().checksum)) { + throw new IllegalStateException("V19_RECOVERY_SNAPSHOT_FILE_MISMATCH:" + entry.getKey()); + } + } + Path rolePermissions = root.resolve("role_permissions.tsv"); + String roleHash = sha256(rolePermissions); + if (!roleHash.equals(expectedRolePermissionHash.toLowerCase(Locale.ROOT))) { + throw new IllegalStateException("V19_RECOVERY_ROLE_PERMISSION_HASH_MISMATCH"); + } + return new Snapshot(expectedManifestHash.toLowerCase(Locale.ROOT), roleHash, + parseRolePermissions(rolePermissions)); + } + + private static Map parseRolePermissions(Path file) throws IOException { + List lines = Files.readAllLines(file, StandardCharsets.UTF_8); + if (lines.isEmpty() || !"role_id\tpermission_id\taccess_level".equals(stripBom(lines.get(0)))) { + throw new IllegalStateException("V19_RECOVERY_ROLE_PERMISSION_HEADER_INVALID"); + } + Map result = new LinkedHashMap<>(); + for (int index = 1; index < lines.size(); index++) { + if (lines.get(index).trim().isEmpty()) continue; + String[] parts = lines.get(index).split("\\t", -1); + if (parts.length != 3) throw new IllegalStateException("V19_RECOVERY_ROLE_PERMISSION_ROW_INVALID"); + long roleId = Long.parseLong(parts[0]); + long permissionId = Long.parseLong(parts[1]); + String access = parts[2]; + if (roleId <= 0 || permissionId <= 0 || !isAccess(access)) { + throw new IllegalStateException("V19_RECOVERY_ROLE_PERMISSION_ROW_INVALID"); + } + if (result.put(new RolePermissionKey(roleId, permissionId), access) != null) { + throw new IllegalStateException("V19_RECOVERY_ROLE_PERMISSION_DUPLICATE"); + } + } + if (result.isEmpty()) throw new IllegalStateException("V19_RECOVERY_ROLE_PERMISSION_EMPTY"); + return Collections.unmodifiableMap(result); + } + + static RecoveryResult recover(RecoveryStore store, Map baseline, + boolean apply) throws Exception { + boolean transactionStarted = false; + try { + if (apply) { + store.begin(); + transactionStarted = true; + } + Map current = store.loadCurrent(apply); + Map allowedAdded = store.loadAllowedV19Added(); + RecoveryResult before = analyze(baseline, current, allowedAdded); + if (!apply || before.changedCount == 0) { + if (transactionStarted) store.commit(); + return before; + } + store.restoreBaseline(baseline); + RecoveryResult after = analyze(baseline, store.loadCurrent(true), allowedAdded); + if (after.changedCount != 0) { + throw new IllegalStateException("V19_RECOVERY_POSTCONDITION_FAILED"); + } + store.commit(); + return before; + } catch (Exception failure) { + if (transactionStarted) store.rollback(); + throw failure; + } + } + + static RecoveryResult analyze(Map baseline, + Map current, + Map allowedAdded) { + int changed = 0; + for (Map.Entry entry : baseline.entrySet()) { + String observed = current.get(entry.getKey()); + if (observed == null) throw new IllegalStateException("V19_RECOVERY_BASELINE_ROW_MISSING"); + if (!entry.getValue().equals(observed)) { + if (!"READ".equals(entry.getValue()) || !"EDIT".equals(observed)) { + throw new IllegalStateException("V19_RECOVERY_BASELINE_DIFF_UNEXPECTED"); + } + changed++; + } + } + if (changed != 0 && changed != 10) { + throw new IllegalStateException("V19_RECOVERY_BASELINE_DIFF_COUNT_INVALID:" + changed); + } + int added = 0; + for (Map.Entry entry : current.entrySet()) { + if (baseline.containsKey(entry.getKey())) continue; + String expected = allowedAdded.get(entry.getKey()); + if (expected == null || !expected.equals(entry.getValue())) { + throw new IllegalStateException("V19_RECOVERY_ADDED_ROW_UNEXPECTED"); + } + added++; + } + return new RecoveryResult(baseline.size(), added, changed); + } + + private static boolean isAccess(String value) { + return "HIDDEN".equals(value) || "READ".equals(value) || "EDIT".equals(value); + } + + private static String stripBom(String value) { + return value.startsWith("\ufeff") ? value.substring(1) : value; + } + + private static String sha256(Path path) throws IOException { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path)); + StringBuilder result = new StringBuilder(64); + for (byte current : digest) result.append(String.format("%02x", current & 0xff)); + return result.toString(); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IllegalStateException("V19_RECOVERY_HASH_UNAVAILABLE", e); + } + } + + private static void acquireLock(Connection connection, int timeoutSeconds) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT GET_LOCK(?,?)")) { + statement.setString(1, LOCK_NAME); + statement.setInt(2, timeoutSeconds); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 1) { + throw new IllegalStateException("MIGRATION_LOCK_NOT_ACQUIRED"); + } + } + } + } + + private static void releaseLock(Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("SELECT RELEASE_LOCK(?)")) { + statement.setString(1, LOCK_NAME); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || result.getInt(1) != 1) { + throw new IllegalStateException("MIGRATION_LOCK_RELEASE_FAILED"); + } + } + } + } + + interface RecoveryStore { + void begin() throws Exception; + Map loadCurrent(boolean forUpdate) throws Exception; + Map loadAllowedV19Added() throws Exception; + void restoreBaseline(Map baseline) throws Exception; + void commit() throws Exception; + void rollback() throws Exception; + } + + private static final class JdbcRecoveryStore implements RecoveryStore { + private final Connection connection; + + private JdbcRecoveryStore(Connection connection) { + this.connection = connection; + } + + private void requireExactRunningHistory() throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT checksum,status FROM sys_schema_migration WHERE migration_id=?")) { + statement.setString(1, V19_ID); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + V19RolePermissionRecovery.requireExactRunningHistory(null, null, 0); + return; + } + String checksum = result.getString(1); + String status = result.getString(2); + V19RolePermissionRecovery.requireExactRunningHistory( + checksum, status, result.next() ? 2 : 1); + } + } + } + + @Override + public void begin() throws SQLException { + connection.setAutoCommit(false); + } + + @Override + public Map loadCurrent(boolean forUpdate) throws SQLException { + String sql = "SELECT role_id,permission_id,access_level FROM sys_role_permission " + + "ORDER BY role_id,permission_id" + (forUpdate ? " FOR UPDATE" : ""); + Map result = new LinkedHashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery(sql)) { + while (rows.next()) { + RolePermissionKey key = new RolePermissionKey(rows.getLong(1), rows.getLong(2)); + if (result.put(key, rows.getString(3)) != null) { + throw new IllegalStateException("V19_RECOVERY_CURRENT_DUPLICATE"); + } + } + } + return result; + } + + @Override + public Map loadAllowedV19Added() throws SQLException { + Map result = new HashMap<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery( + "SELECT DISTINCT rp.role_id,m.permission_id,m.min_access_level " + + "FROM authz_role_policy rp JOIN authz_permission_policy_map m " + + "ON m.policy_id=rp.policy_id")) { + while (rows.next()) { + RolePermissionKey key = new RolePermissionKey(rows.getLong(1), rows.getLong(2)); + String prior = result.put(key, rows.getString(3)); + if (prior != null && !prior.equals(rows.getString(3))) { + throw new IllegalStateException("V19_RECOVERY_ALLOWED_ROW_AMBIGUOUS"); + } + } + } + return result; + } + + @Override + public void restoreBaseline(Map baseline) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE sys_role_permission SET access_level=? WHERE role_id=? AND permission_id=?")) { + for (Map.Entry entry : baseline.entrySet()) { + statement.setString(1, entry.getValue()); + statement.setLong(2, entry.getKey().roleId); + statement.setLong(3, entry.getKey().permissionId); + statement.addBatch(); + } + statement.executeBatch(); + } + } + + @Override + public void commit() throws SQLException { + connection.commit(); + } + + @Override + public void rollback() throws SQLException { + connection.rollback(); + } + } + + static void requireExactRunningHistory(String checksum, String status, int rows) { + if (rows != 1 || !V19_CHECKSUM.equals(checksum) || !"RUNNING".equals(status)) { + throw new IllegalStateException("V19_RECOVERY_HISTORY_STATE_INVALID"); + } + } + + static final class RolePermissionKey { + final long roleId; + final long permissionId; + + RolePermissionKey(long roleId, long permissionId) { + this.roleId = roleId; + this.permissionId = permissionId; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof RolePermissionKey)) return false; + RolePermissionKey key = (RolePermissionKey) other; + return roleId == key.roleId && permissionId == key.permissionId; + } + + @Override + public int hashCode() { + return (int) (31L * roleId + permissionId); + } + } + + static final class RecoveryResult { + final int baselineCount; + final int addedCount; + final int changedCount; + + RecoveryResult(int baselineCount, int addedCount, int changedCount) { + this.baselineCount = baselineCount; + this.addedCount = addedCount; + this.changedCount = changedCount; + } + } + + static final class Snapshot { + final String manifestHash; + final String rolePermissionHash; + final Map rolePermissions; + + Snapshot(String manifestHash, String rolePermissionHash, + Map rolePermissions) { + this.manifestHash = manifestHash; + this.rolePermissionHash = rolePermissionHash; + this.rolePermissions = rolePermissions; + } + } + + private static final class ManifestEntry { + private final long length; + private final String checksum; + + private ManifestEntry(long length, String checksum) { + this.length = length; + this.checksum = checksum; + } + } + + private static final class Arguments { + private final String url; + private final String user; + private final String passwordEnvironment; + private final String snapshotDirectory; + private final boolean apply; + private final int lockTimeoutSeconds; + + private Arguments(Map values) { + Set allowed = new LinkedHashSet<>(Arrays.asList( + "url", "user", "password-env", "snapshot", "mode", "lock-timeout-seconds")); + for (String key : values.keySet()) { + if (!allowed.contains(key)) throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_UNKNOWN:" + key); + } + this.url = required(values, "url"); + this.user = required(values, "user"); + this.passwordEnvironment = values.getOrDefault("password-env", "DB_PASSWORD"); + this.snapshotDirectory = required(values, "snapshot"); + String mode = values.getOrDefault("mode", "validate"); + if (!"validate".equals(mode) && !"apply".equals(mode)) { + throw new IllegalArgumentException("V19_RECOVERY_MODE_INVALID"); + } + this.apply = "apply".equals(mode); + this.lockTimeoutSeconds = Integer.parseInt(values.getOrDefault("lock-timeout-seconds", "60")); + if (lockTimeoutSeconds < 0 || lockTimeoutSeconds > 3600) { + throw new IllegalArgumentException("V19_RECOVERY_LOCK_TIMEOUT_INVALID"); + } + } + + private static Arguments parse(String[] args) { + Map values = new LinkedHashMap<>(); + for (String arg : args) { + if (!arg.startsWith("--") || arg.indexOf('=') < 3) { + throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_INVALID"); + } + int split = arg.indexOf('='); + String key = arg.substring(2, split); + if (values.put(key, arg.substring(split + 1)) != null) { + throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_DUPLICATE:" + key); + } + } + return new Arguments(values); + } + + private static String required(Map values, String key) { + String value = values.get(key); + if (value == null || value.trim().isEmpty()) { + throw new IllegalArgumentException("V19_RECOVERY_ARGUMENT_REQUIRED:" + key); + } + return value; + } + } +} diff --git a/src/main/java/com/finance/system/observability/LogText.java b/src/main/java/com/finance/system/observability/LogText.java new file mode 100644 index 0000000..16be102 --- /dev/null +++ b/src/main/java/com/finance/system/observability/LogText.java @@ -0,0 +1,252 @@ +package com.finance.system.observability; + +import org.springframework.util.StringUtils; + +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +/** Central Chinese labels for console, access-log and audit-log projections. */ +public final class LogText { + private static final Map API_DOMAINS = new LinkedHashMap<>(); + private static final Map AUDIT_ACTIONS = new LinkedHashMap<>(); + private static final Map RESOURCE_TYPES = new LinkedHashMap<>(); + + static { + 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", "出纳付款"); + API_DOMAINS.put("/api/feishu/directory", "飞书通讯录"); + API_DOMAINS.put("/api/feishu/approval", "飞书审批"); + API_DOMAINS.put("/api/feishu", "飞书集成"); + API_DOMAINS.put("/api/integrations/kingdee", "金蝶同步配置"); + 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/user-groups", "用户组"); + API_DOMAINS.put("/api/roles", "角色权限"); + API_DOMAINS.put("/api/auth", "登录与用户"); + 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/sources", "来源单据"); + API_DOMAINS.put("/api/v1/dashboard", "首页统计"); + + AUDIT_ACTIONS.put("security.authorization.denied", "权限校验拒绝"); + AUDIT_ACTIONS.put("integration.feishu.directory.sync-trigger", "触发飞书通讯录同步"); + AUDIT_ACTIONS.put("integration.feishu.approval.sync", "同步飞书审批定义"); + AUDIT_ACTIONS.put("iam.group.member.update", "更新用户组成员"); + AUDIT_ACTIONS.put("iam.group.role.update", "更新用户组角色"); + AUDIT_ACTIONS.put("iam.role.create", "新增角色"); + 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.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("finance.approval.approve", "审批通过"); + AUDIT_ACTIONS.put("finance.approval.reject", "审批退回"); + AUDIT_ACTIONS.put("finance.approval.transfer", "转交审批"); + AUDIT_ACTIONS.put("finance.payment.register", "登记付款"); + AUDIT_ACTIONS.put("finance.payment.verify", "复核付款"); + AUDIT_ACTIONS.put("finance.payment.reject", "驳回付款"); + AUDIT_ACTIONS.put("business.config.master.status-change", "变更业务配置状态"); + AUDIT_ACTIONS.put("business.config.budget-subject.create", "新增预算科目"); + AUDIT_ACTIONS.put("business.config.budget-subject.status-change", "变更预算科目状态"); + AUDIT_ACTIONS.put("business.config.legal-entity.create", "新增法人主体"); + AUDIT_ACTIONS.put("business.config.cost-center.create", "新增成本中心"); + AUDIT_ACTIONS.put("business.config.payment-method.create", "新增付款方式"); + AUDIT_ACTIONS.put("business.config.payment-account.create", "新增公司付款账户"); + + RESOURCE_TYPES.put("AUTHORIZATION", "权限校验"); + RESOURCE_TYPES.put("FEISHU_DIRECTORY_RUN", "飞书通讯录同步任务"); + 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_BANK_ACCOUNT", "收款账户"); + RESOURCE_TYPES.put("REIM_APPLICATION", "报销申请"); + RESOURCE_TYPES.put("REIM_ATTACHMENT", "报销附件"); + RESOURCE_TYPES.put("REIM_PAYMENT", "付款记录"); + RESOURCE_TYPES.put("BIZ_LEGAL_ENTITY", "法人主体"); + RESOURCE_TYPES.put("BIZ_COST_CENTER", "成本中心"); + RESOURCE_TYPES.put("BIZ_PAYMENT_METHOD", "付款方式"); + RESOURCE_TYPES.put("BIZ_PAYMENT_ACCOUNT", "公司付款账户"); + RESOURCE_TYPES.put("BIZ_BUDGET_SUBJECT", "预算科目"); + } + + private LogText() {} + + public static String apiOperation(String method, String route) { + String safeRoute = StringUtils.hasText(route) ? route : "UNMATCHED"; + if ("UNMATCHED".equalsIgnoreCase(safeRoute)) return "未匹配到系统接口"; + String domain = "系统接口"; + for (Map.Entry entry : API_DOMAINS.entrySet()) { + if (safeRoute.startsWith(entry.getKey())) { + domain = entry.getValue(); + break; + } + } + return domain + "-" + apiAction(method, safeRoute); + } + + private static String apiAction(String method, String route) { + String upperMethod = method == null ? "" : method.toUpperCase(Locale.ROOT); + if (route.endsWith("/login") || route.endsWith("/feishu-login")) return "登录"; + if (route.endsWith("/logout")) return "退出登录"; + if (route.endsWith("/refresh")) return "刷新登录凭证"; + if (route.endsWith("/auth-url")) return "获取授权地址"; + if (route.endsWith("/callback")) return "处理授权回调"; + if (route.endsWith("/webhook")) return "接收事件回调"; + 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("/approve")) return "审批通过"; + if (route.endsWith("/reject")) return "审批退回"; + if (route.endsWith("/transfer")) return "转交审批"; + if (route.endsWith("/partial-pay")) return "登记分次付款"; + if (route.endsWith("/pay")) return "登记付款"; + if (route.endsWith("/verify")) return "复核付款"; + if (route.endsWith("/sync")) return "执行同步"; + if (route.endsWith("/test")) return "测试连接或绑定"; + if (route.endsWith("/preview")) return "预览同步结果"; + if (route.endsWith("/prepare-table")) return "准备同步数据表"; + if (route.endsWith("/execute")) return "立即执行任务"; + if (route.endsWith("/default")) return "设置默认账户"; + if (route.endsWith("/status")) return "查询或变更状态"; + if (route.endsWith("/runs")) return "查询执行记录"; + if (route.endsWith("/organization/members")) return "查询组织员工"; + if (route.endsWith("/organization")) return "查询组织架构"; + if (route.endsWith("/form-definition")) return "获取申请表单定义"; + if (route.endsWith("/workbench")) return "查询申请工作台"; + if (route.endsWith("/my") || route.endsWith("/mine") || route.endsWith("/me")) return "查询本人信息"; + if (route.contains("/candidates") || route.contains("/member-candidates")) return "搜索可选人员"; + if (route.endsWith("/permissions")) return "查询或保存权限"; + if (route.endsWith("/members")) return "查询或保存成员"; + if (route.endsWith("/roles") || route.endsWith("/groups")) return "查询或保存关联关系"; + if (route.endsWith("/references")) return "查询业务配置引用数据"; + if (route.endsWith("/budgets/overview")) return "查询预算总览"; + if (route.endsWith("/form-attachments")) return "上传表单附件"; + if ("GET".equals(upperMethod)) return route.contains("{") ? "查看详情" : "查询列表"; + if ("POST".equals(upperMethod)) return "新增或提交"; + if ("PUT".equals(upperMethod)) return "更新并保存"; + if ("PATCH".equals(upperMethod)) return "变更状态"; + if ("DELETE".equals(upperMethod)) return "删除或停用"; + return "处理请求"; + } + + public static String method(String method) { + if (method == null) return "未知请求方式"; + switch (method.toUpperCase(Locale.ROOT)) { + case "GET": return "GET-查询"; + case "POST": return "POST-提交"; + case "PUT": return "PUT-完整更新"; + case "PATCH": return "PATCH-部分更新"; + case "DELETE": return "DELETE-删除"; + case "HEAD": return "HEAD-读取元信息"; + case "OPTIONS": return "OPTIONS-跨域预检"; + default: return method + "-其他请求"; + } + } + + public static String status(int status) { + if (status >= 500) return status + "-服务异常"; + switch (status) { + case 200: return "200-成功"; + case 201: return "201-创建成功"; + case 204: return "204-成功无内容"; + case 400: return "400-请求参数错误"; + case 401: return "401-未登录或登录失效"; + case 403: return "403-权限不足"; + case 404: return "404-接口或资源不存在"; + case 409: return "409-业务状态冲突"; + case 422: return "422-业务校验未通过"; + default: return status + (status >= 400 ? "-请求失败" : "-已处理"); + } + } + + public static String outcome(String outcome) { + if (!StringUtils.hasText(outcome)) return "未知结果"; + switch (outcome.toUpperCase(Locale.ROOT)) { + case "SUCCESS": return "成功"; + case "FAILURE": case "FAILED": return "失败"; + case "DENIED": return "已拒绝"; + case "PARTIAL": return "部分成功"; + case "PENDING": return "处理中"; + default: return "其他结果(" + outcome + ")"; + } + } + + public static String auditCategory(String category) { + if (category == null) return "未分类事件"; + switch (category.toUpperCase(Locale.ROOT)) { + case "SECURITY": return "安全事件"; + case "BUSINESS": return "业务审计"; + case "ADMIN": return "系统管理审计"; + case "INTEGRATION": return "集成审计"; + default: return "其他审计(" + category + ")"; + } + } + + public static String auditAction(String action) { + String label = AUDIT_ACTIONS.get(action); + return label != null ? label : (StringUtils.hasText(action) ? "审计动作(" + action + ")" : "未知审计动作"); + } + + public static String resourceType(String type) { + String label = RESOURCE_TYPES.get(type); + return label != null ? label : (StringUtils.hasText(type) ? "业务资源(" + type + ")" : "未指定资源"); + } + + public static String actorType(String type) { + if (!StringUtils.hasText(type)) return "未知操作者"; + if ("USER".equalsIgnoreCase(type)) return "用户"; + if ("SYSTEM".equalsIgnoreCase(type)) return "系统任务"; + if ("SERVICE".equalsIgnoreCase(type)) return "后台服务"; + return "其他操作者(" + type + ")"; + } + + public static String reason(String code) { + if (!StringUtils.hasText(code)) return "无补充原因"; + switch (code) { + case "DEFAULT_DENY": return "默认拒绝:未命中允许规则"; + case "UI_PERMISSION_NOT_BUSINESS_AUTHORITY": return "页面权限不能替代业务操作权限"; + case "SOD_DENIED": return "职责分离规则拒绝"; + default: return "原因代码(" + code + ")"; + } + } + + public static String error(String code) { + if (!StringUtils.hasText(code)) return "无错误"; + if (code.startsWith("HTTP_")) return status(parseStatus(code)) + "(" + code + ")"; + switch (code) { + case "SERVLET_EXCEPTION": return "接口处理异常(SERVLET_EXCEPTION)"; + case "IO_EXCEPTION": return "网络读写异常(IO_EXCEPTION)"; + case "RUNTIME_EXCEPTION": return "运行时异常(RUNTIME_EXCEPTION)"; + case "TRUSTED_CONTEXT_INVALID": return "可信请求上下文无效(TRUSTED_CONTEXT_INVALID)"; + case "ENTRY_BUILD_FAILED": return "日志记录构建失败(ENTRY_BUILD_FAILED)"; + default: return "业务错误(" + code + ")"; + } + } + + private static int parseStatus(String code) { + try { return Integer.parseInt(code.substring(5)); } + catch (RuntimeException ignored) { return 500; } + } +} diff --git a/src/main/java/com/finance/system/observability/MdcTaskDecorator.java b/src/main/java/com/finance/system/observability/MdcTaskDecorator.java new file mode 100644 index 0000000..6ef0fe0 --- /dev/null +++ b/src/main/java/com/finance/system/observability/MdcTaskDecorator.java @@ -0,0 +1,26 @@ +package com.finance.system.observability; + +import org.slf4j.MDC; +import org.springframework.core.task.TaskDecorator; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +public class MdcTaskDecorator implements TaskDecorator { + @Override + public Runnable decorate(Runnable runnable) { + Map captured = MDC.getCopyOfContextMap(); + return () -> { + Map previous = MDC.getCopyOfContextMap(); + try { + if (captured == null) MDC.clear(); + else MDC.setContextMap(captured); + runnable.run(); + } finally { + if (previous == null) MDC.clear(); + else MDC.setContextMap(previous); + } + }; + } +} diff --git a/src/main/java/com/finance/system/observability/OutboundTraceInterceptor.java b/src/main/java/com/finance/system/observability/OutboundTraceInterceptor.java new file mode 100644 index 0000000..58c6f39 --- /dev/null +++ b/src/main/java/com/finance/system/observability/OutboundTraceInterceptor.java @@ -0,0 +1,31 @@ +package com.finance.system.observability; + +import org.slf4j.MDC; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.io.IOException; + +@Component +public class OutboundTraceInterceptor implements ClientHttpRequestInterceptor { + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { + String requestId = MDC.get("request_id"); + if (StringUtils.hasText(requestId) && !request.getHeaders().containsKey("X-Request-Id")) { + request.getHeaders().set("X-Request-Id", requestId); + } + String traceId = MDC.get("trace_id"); + String spanId = MDC.get("span_id"); + if (StringUtils.hasText(traceId) && StringUtils.hasText(spanId) + && !request.getHeaders().containsKey("traceparent")) { + request.getHeaders().set("traceparent", "00-" + traceId + "-" + spanId + "-01"); + } + return execution.execute(request, body); + } +} + diff --git a/src/main/java/com/finance/system/observability/RequestContext.java b/src/main/java/com/finance/system/observability/RequestContext.java new file mode 100644 index 0000000..10a3b8f --- /dev/null +++ b/src/main/java/com/finance/system/observability/RequestContext.java @@ -0,0 +1,48 @@ +package com.finance.system.observability; + +import javax.servlet.http.HttpServletRequest; + +public final class RequestContext { + public static final String REQUEST_ID_ATTRIBUTE = RequestContext.class.getName() + ".requestId"; + public static final String CLIENT_REQUEST_ID_ATTRIBUTE = RequestContext.class.getName() + ".clientRequestId"; + public static final String TRACE_ID_ATTRIBUTE = RequestContext.class.getName() + ".traceId"; + public static final String SPAN_ID_ATTRIBUTE = RequestContext.class.getName() + ".spanId"; + public static final String TENANT_ID_ATTRIBUTE = RequestContext.class.getName() + ".tenantId"; + public static final String ORGANIZATION_ID_ATTRIBUTE = RequestContext.class.getName() + ".organizationId"; + + private RequestContext() { + } + + public static String requestId(HttpServletRequest request) { + return value(request.getAttribute(REQUEST_ID_ATTRIBUTE)); + } + + public static String clientRequestId(HttpServletRequest request) { + return value(request.getAttribute(CLIENT_REQUEST_ID_ATTRIBUTE)); + } + + public static String traceId(HttpServletRequest request) { + return value(request.getAttribute(TRACE_ID_ATTRIBUTE)); + } + + public static String spanId(HttpServletRequest request) { + return value(request.getAttribute(SPAN_ID_ATTRIBUTE)); + } + + public static String tenantId(HttpServletRequest request) { + return value(request.getAttribute(TENANT_ID_ATTRIBUTE)); + } + + public static Long organizationId(HttpServletRequest request) { + Object value = request.getAttribute(ORGANIZATION_ID_ATTRIBUTE); + if (value instanceof Number) return ((Number) value).longValue(); + if (value == null) return null; + try { return Long.valueOf(String.valueOf(value)); } + catch (NumberFormatException ignored) { return null; } + } + + private static String value(Object value) { + return value == null ? null : String.valueOf(value); + } +} + diff --git a/src/main/java/com/finance/system/observability/RequestContextFilter.java b/src/main/java/com/finance/system/observability/RequestContextFilter.java new file mode 100644 index 0000000..e3bedd7 --- /dev/null +++ b/src/main/java/com/finance/system/observability/RequestContextFilter.java @@ -0,0 +1,96 @@ +package com.finance.system.observability; + +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Component("financeRequestContextFilter") +public class RequestContextFilter extends OncePerRequestFilter { + private static final Pattern SAFE_CLIENT_REQUEST_ID = Pattern.compile("[A-Za-z0-9._-]{1,64}"); + private static final Pattern TRACE_PARENT = Pattern.compile( + "^[0-9a-fA-F]{2}-([0-9a-fA-F]{32})-([0-9a-fA-F]{16})-[0-9a-fA-F]{2}$"); + + private final String tenantId; + private final Long organizationId; + + public RequestContextFilter(@Value("${observability.tenant-id:default}") String tenantId, + @Value("${observability.organization-id:1}") Long organizationId) { + this.tenantId = safeTenant(tenantId); + if (organizationId == null || organizationId <= 0) + throw new IllegalArgumentException("observability.organization-id must be positive"); + this.organizationId = organizationId; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + Map previous = MDC.getCopyOfContextMap(); + String requestId = randomHex32(); + String clientRequestId = safeClientRequestId(request.getHeader("X-Request-Id")); + String traceId = incomingTraceId(request.getHeader("traceparent")); + if (traceId == null) traceId = randomHex32(); + String spanId = randomHex32().substring(0, 16); + + request.setAttribute(RequestContext.REQUEST_ID_ATTRIBUTE, requestId); + request.setAttribute(RequestContext.CLIENT_REQUEST_ID_ATTRIBUTE, clientRequestId); + request.setAttribute(RequestContext.TRACE_ID_ATTRIBUTE, traceId); + request.setAttribute(RequestContext.SPAN_ID_ATTRIBUTE, spanId); + request.setAttribute(RequestContext.TENANT_ID_ATTRIBUTE, tenantId); + request.setAttribute(RequestContext.ORGANIZATION_ID_ATTRIBUTE, organizationId); + response.setHeader("X-Request-Id", requestId); + response.setHeader("traceparent", "00-" + traceId + "-" + spanId + "-01"); + + put("request_id", requestId); + put("client_request_id", clientRequestId); + put("trace_id", traceId); + put("span_id", spanId); + put("tenant_id", tenantId); + put("organization_id", String.valueOf(organizationId)); + try { + filterChain.doFilter(request, response); + } finally { + if (previous == null) MDC.clear(); + else MDC.setContextMap(previous); + } + } + + private static void put(String key, String value) { + if (StringUtils.hasText(value)) MDC.put(key, value); + } + + private static String safeClientRequestId(String value) { + if (!StringUtils.hasText(value)) return null; + String trimmed = value.trim(); + return SAFE_CLIENT_REQUEST_ID.matcher(trimmed).matches() ? trimmed : null; + } + + private static String incomingTraceId(String traceparent) { + if (!StringUtils.hasText(traceparent)) return null; + Matcher matcher = TRACE_PARENT.matcher(traceparent.trim()); + if (!matcher.matches()) return null; + String traceId = matcher.group(1).toLowerCase(); + return "00000000000000000000000000000000".equals(traceId) ? null : traceId; + } + + private static String randomHex32() { + return UUID.randomUUID().toString().replace("-", ""); + } + + private static String safeTenant(String value) { + if (StringUtils.hasText(value) && value.matches("[A-Za-z0-9._-]{1,64}")) return value; + return "default"; + } +} + diff --git a/src/main/java/com/finance/system/repository/ApplicantDepartmentDirectoryRepository.java b/src/main/java/com/finance/system/repository/ApplicantDepartmentDirectoryRepository.java index 9254950..53c745a 100644 --- a/src/main/java/com/finance/system/repository/ApplicantDepartmentDirectoryRepository.java +++ b/src/main/java/com/finance/system/repository/ApplicantDepartmentDirectoryRepository.java @@ -21,8 +21,10 @@ public class ApplicantDepartmentDirectoryRepository { List values = jdbc.query( "SELECT d.open_department_id,d.name " + "FROM feishu_directory_user_department ud " + + "JOIN feishu_directory_user u ON u.open_id=ud.open_id " + "JOIN feishu_directory_department d ON d.open_department_id=ud.open_department_id " - + "WHERE ud.open_id=? AND d.open_department_id<>? " + + "WHERE ud.open_id=? AND u.eligible=TRUE AND u.employment_status='ACTIVE' " + + "AND d.open_department_id<>? " + "ORDER BY d.sort_order,d.open_department_id LIMIT 1", (rs, rowNum) -> new DirectoryDepartment( rs.getString("open_department_id"), rs.getString("name")), @@ -30,6 +32,99 @@ public class ApplicantDepartmentDirectoryRepository { return values.stream().findFirst(); } + /** + * Resolves a department only from the last atomically published directory + * generation. The user, membership and department must all belong to that + * same successful revision and context; a partial or unavailable + * publication therefore produces no result. + */ + public Optional findPreferredPublishedEligibleNonRootByOpenId( + String openId, String tenantId) { + List values = jdbc.query( + "SELECT d.open_department_id,d.name " + + "FROM feishu_directory_state s " + + "JOIN feishu_directory_user u " + + "ON u.snapshot_run_id=s.last_successful_run_id AND u.context=s.successful_context " + + "JOIN feishu_directory_user_department ud " + + "ON ud.open_id=u.open_id AND ud.revision_run_id=s.last_successful_run_id " + + "JOIN feishu_directory_department d " + + "ON d.open_department_id=ud.open_department_id " + + "AND d.snapshot_run_id=s.last_successful_run_id AND d.context=s.successful_context " + + "WHERE s.id=1 AND s.tenant_id=? " + + "AND s.last_successful_run_id IS NOT NULL AND s.last_successful_at IS NOT NULL " + + "AND s.successful_context IS NOT NULL " + + "AND u.open_id=? AND u.eligible=TRUE AND u.employment_status='ACTIVE' " + + "AND d.open_department_id<>? " + + "ORDER BY d.sort_order,d.open_department_id LIMIT 1", + (rs, rowNum) -> new DirectoryDepartment( + rs.getString("open_department_id"), rs.getString("name")), + tenantId, openId, ROOT_DEPARTMENT_ID); + return values.stream().findFirst(); + } + + /** Validates an explicit picker value against this applicant's current published membership. */ + public Optional findPublishedEligibleNonRootMembership( + String openId, String tenantId, String openDepartmentId) { + List values = jdbc.query( + "SELECT d.open_department_id,d.name " + + "FROM feishu_directory_state s " + + "JOIN feishu_directory_user u " + + "ON u.snapshot_run_id=s.last_successful_run_id AND u.context=s.successful_context " + + "JOIN feishu_directory_user_department ud " + + "ON ud.open_id=u.open_id AND ud.revision_run_id=s.last_successful_run_id " + + "JOIN feishu_directory_department d " + + "ON d.open_department_id=ud.open_department_id " + + "AND d.snapshot_run_id=s.last_successful_run_id AND d.context=s.successful_context " + + "WHERE s.id=1 AND s.tenant_id=? " + + "AND s.last_successful_run_id IS NOT NULL AND s.last_successful_at IS NOT NULL " + + "AND s.successful_context IS NOT NULL " + + "AND u.open_id=? AND u.eligible=TRUE AND u.employment_status='ACTIVE' " + + "AND d.open_department_id=? AND d.open_department_id<>? LIMIT 1", + (rs, rowNum) -> new DirectoryDepartment( + rs.getString("open_department_id"), rs.getString("name")), + tenantId, openId, openDepartmentId, ROOT_DEPARTMENT_ID); + return values.stream().findFirst(); + } + + /** + * Resolves the applicant's current published membership through the exact + * immutable local-department binding. This is the canonical read for an + * existing application's persisted department identity. + */ + public Optional findPublishedEligibleNonRootMembershipByLocalDepartment( + String openId, String tenantId, Long localDepartmentId) { + List values = jdbc.query( + "SELECT d.open_department_id,d.name " + + "FROM feishu_directory_state s " + + "JOIN feishu_directory_user u " + + "ON u.snapshot_run_id=s.last_successful_run_id AND u.context=s.successful_context " + + "JOIN feishu_directory_user_department ud " + + "ON ud.open_id=u.open_id AND ud.revision_run_id=s.last_successful_run_id " + + "JOIN feishu_directory_department d " + + "ON d.open_department_id=ud.open_department_id " + + "AND d.snapshot_run_id=s.last_successful_run_id AND d.context=s.successful_context " + + "JOIN feishu_directory_department_binding b " + + "ON b.open_department_id=d.open_department_id AND b.sys_department_id=? " + + "WHERE s.id=1 AND s.tenant_id=? " + + "AND s.last_successful_run_id IS NOT NULL AND s.last_successful_at IS NOT NULL " + + "AND s.successful_context IS NOT NULL " + + "AND u.open_id=? AND u.eligible=TRUE AND u.employment_status='ACTIVE' " + + "AND d.open_department_id<>? LIMIT 1", + (rs, rowNum) -> new DirectoryDepartment( + rs.getString("open_department_id"), rs.getString("name")), + localDepartmentId, tenantId, openId, ROOT_DEPARTMENT_ID); + return values.stream().findFirst(); + } + + /** Returns only the exact V14 identity mapping, independent of directory publication state. */ + public Optional findBoundOpenDepartmentIdByLocalDepartment(Long localDepartmentId) { + List values = jdbc.query( + "SELECT open_department_id FROM feishu_directory_department_binding " + + "WHERE sys_department_id=? LIMIT 1", + (rs, rowNum) -> rs.getString("open_department_id"), localDepartmentId); + return values.stream().findFirst(); + } + public Optional findByOpenDepartmentId(String openDepartmentId) { List values = jdbc.query( "SELECT open_department_id,name FROM feishu_directory_department " diff --git a/src/main/java/com/finance/system/repository/FeishuDirectoryDepartmentBindingStore.java b/src/main/java/com/finance/system/repository/FeishuDirectoryDepartmentBindingStore.java new file mode 100644 index 0000000..9b09468 --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuDirectoryDepartmentBindingStore.java @@ -0,0 +1,83 @@ +package com.finance.system.repository; + +import com.finance.system.exception.BusinessException; +import com.finance.system.util.Sha256; +import lombok.Value; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** Exact, concurrency-safe bridge from a Feishu department identity to local master data. */ +@Repository +public class FeishuDirectoryDepartmentBindingStore { + private static final String CODE_PREFIX = "FS-"; + private final JdbcTemplate jdbc; + + public FeishuDirectoryDepartmentBindingStore(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public Binding resolveOrCreate(String openDepartmentId, String departmentName) { + List existing = findForUpdate(openDepartmentId); + if (!existing.isEmpty()) return existing.get(0); + + String code = CODE_PREFIX + Sha256.hex(openDepartmentId).substring(0, 40); + String name = boundedName(departmentName); + try { + jdbc.update("INSERT INTO sys_department" + + "(dept_code,dept_name,parent_id,sort_order,status,created_at,updated_at) " + + "VALUES (?,?,NULL,0,'ACTIVE',UTC_TIMESTAMP(6),UTC_TIMESTAMP(6))", + code, name); + } catch (DataIntegrityViolationException duplicateCode) { + // A duplicate stable code is reusable only when the competing + // transaction has also completed the exact identity binding. This + // keeps same-open-id first creation idempotent without adopting an + // unrelated/manual department that merely owns the derived code. + List concurrentlyBound = findForUpdate(openDepartmentId); + if (concurrentlyBound.size() == 1) return concurrentlyBound.get(0); + throw conflict(); + } + Long departmentId = jdbc.queryForObject( + "SELECT id FROM sys_department WHERE dept_code=? FOR UPDATE", Long.class, code); + if (departmentId == null) throw conflict(); + + jdbc.update("INSERT INTO feishu_directory_department_binding" + + "(open_department_id,sys_department_id,created_at,updated_at) " + + "VALUES (?,?,UTC_TIMESTAMP(6),UTC_TIMESTAMP(6)) " + + "ON DUPLICATE KEY UPDATE open_department_id=open_department_id", + openDepartmentId, departmentId); + List resolved = findForUpdate(openDepartmentId); + if (resolved.size() != 1 || !departmentId.equals(resolved.get(0).getDepartmentId())) { + throw conflict(); + } + return resolved.get(0); + } + + private List findForUpdate(String openDepartmentId) { + return jdbc.query("SELECT b.sys_department_id,d.status " + + "FROM feishu_directory_department_binding b " + + "JOIN sys_department d ON d.id=b.sys_department_id " + + "WHERE b.open_department_id=? FOR UPDATE", + (rs, rowNum) -> new Binding( + rs.getLong("sys_department_id"), rs.getString("status")), + openDepartmentId); + } + + private static String boundedName(String value) { + String name = value == null ? "" : value.trim(); + if (name.isEmpty()) name = "飞书部门"; + return name.length() <= 200 ? name : name.substring(0, 200); + } + + private static BusinessException conflict() { + return new BusinessException("飞书部门绑定冲突,请联系管理员处理", 409); + } + + @Value + public static class Binding { + Long departmentId; + String departmentStatus; + } +} diff --git a/src/main/java/com/finance/system/repository/FeishuTravelApplicationRepository.java b/src/main/java/com/finance/system/repository/FeishuTravelApplicationRepository.java new file mode 100644 index 0000000..b7e4e28 --- /dev/null +++ b/src/main/java/com/finance/system/repository/FeishuTravelApplicationRepository.java @@ -0,0 +1,12 @@ +package com.finance.system.repository; + +import com.finance.system.entity.FeishuTravelApplication; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface FeishuTravelApplicationRepository extends JpaRepository { + List findByApplicantUserIdOrderByStartDateDescIdDesc(Long applicantUserId); + Optional findByIdAndApplicantUserId(Long id, Long applicantUserId); +} diff --git a/src/main/java/com/finance/system/repository/FileStorageCleanupTaskRepository.java b/src/main/java/com/finance/system/repository/FileStorageCleanupTaskRepository.java new file mode 100644 index 0000000..e4e5a26 --- /dev/null +++ b/src/main/java/com/finance/system/repository/FileStorageCleanupTaskRepository.java @@ -0,0 +1,16 @@ +package com.finance.system.repository; + +import com.finance.system.entity.FileStorageCleanupTask; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.time.LocalDateTime; +import java.util.List; + +@Repository +public interface FileStorageCleanupTaskRepository extends JpaRepository { + boolean existsByStorageProviderAndStorageObjectKey(String storageProvider, String storageObjectKey); + + List findTop20ByTaskStatusAndNextAttemptAtLessThanEqualOrderByIdAsc( + String taskStatus, LocalDateTime nextAttemptAt); +} diff --git a/src/main/java/com/finance/system/repository/ReimApplicationRepository.java b/src/main/java/com/finance/system/repository/ReimApplicationRepository.java index e941d25..bd57713 100644 --- a/src/main/java/com/finance/system/repository/ReimApplicationRepository.java +++ b/src/main/java/com/finance/system/repository/ReimApplicationRepository.java @@ -11,39 +11,85 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; +import java.util.Optional; @Repository public interface ReimApplicationRepository extends JpaRepository { - ReimApplication findByApplicationNo(String applicationNo); - - List findByApplicantIdOrderByCreatedAtDesc(Long applicantId); - - Page findByApplicantIdOrderByCreatedAtDesc(Long applicantId, Pageable pageable); - - Page findByApplicantIdAndApprovalStatus(Long applicantId, String approvalStatus, Pageable pageable); - - Page findByApplicantIdAndApplicationStatus(Long applicantId, String applicationStatus, Pageable pageable); - - Page findByApplicationStatus(String applicationStatus, Pageable pageable); - - Page findByApplicationStatusAndApprovalStatus(String applicationStatus, String approvalStatus, Pageable pageable); - - Page findByApprovalStatus(String approvalStatus, Pageable pageable); - - Page findByApprovalStatusAndPaymentStatus(String approvalStatus, String paymentStatus, Pageable pageable); - - Page findByApprovalStatusAndPaymentStatusIn(String approvalStatus, List paymentStatuses, Pageable pageable); - - Page findByCurrentApproverIdAndApprovalStatus(Long currentApproverId, String approvalStatus, Pageable pageable); + String SCOPE_PREDICATE = "(:scope = 'ALL' " + + "or (:scope = 'SELF' and a.applicantId = :actorId) " + + "or (:scope = 'CURRENT_APPROVER' and a.currentApproverId = :actorId) " + + "or (:scope in ('DEPARTMENT','DEPARTMENT_TREE') and a.departmentId in :departmentIds))"; List findBySourceDocNoAndSourceSystem(String sourceDocNo, String sourceSystem); List findTopByApplicationNoStartingWithOrderByApplicationNoDesc(String prefix); - List findFirst10ByApplicantIdOrderByCreatedAtDesc(Long applicantId); - @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("select a from ReimApplication a where a.id = :id and a.deleted = false") java.util.Optional findByIdForUpdate(@Param("id") Long id); + + @Query("select a from ReimApplication a where a.tenantId = :tenantId and a.deleted = false and " + + SCOPE_PREDICATE + " and (:applicationStatus is null or a.applicationStatus = :applicationStatus) " + + "and (:approvalStatus is null or a.approvalStatus = :approvalStatus) " + + "and (:paymentStatus is null or a.paymentStatus = :paymentStatus)") + Page findScoped(@Param("tenantId") String tenantId, + @Param("scope") String scope, @Param("actorId") Long actorId, + @Param("departmentIds") List departmentIds, + @Param("applicationStatus") String applicationStatus, + @Param("approvalStatus") String approvalStatus, + @Param("paymentStatus") String paymentStatus, Pageable pageable); + + @Query(value = "select a from ReimApplication a where a.tenantId = :tenantId and a.deleted = false " + + "and a.applicantId = :applicantId and " + SCOPE_PREDICATE + + " and (:applicationStatus is null or a.applicationStatus = :applicationStatus) " + + "and (:approvalStatus is null or a.approvalStatus = :approvalStatus)", + countQuery = "select count(a) from ReimApplication a where a.tenantId = :tenantId " + + "and a.deleted = false and a.applicantId = :applicantId and " + SCOPE_PREDICATE + + " and (:applicationStatus is null or a.applicationStatus = :applicationStatus) " + + "and (:approvalStatus is null or a.approvalStatus = :approvalStatus)") + Page findScopedForApplicant(@Param("tenantId") String tenantId, + @Param("scope") String scope, @Param("actorId") Long actorId, + @Param("departmentIds") List departmentIds, @Param("applicantId") Long applicantId, + @Param("applicationStatus") String applicationStatus, + @Param("approvalStatus") String approvalStatus, Pageable pageable); + + @Query("select a from ReimApplication a where a.tenantId = :tenantId and a.deleted = false " + + "and a.approvalStatus = 'APPROVED' and a.paymentStatus in ('UNPAID','PARTIAL') and " + + SCOPE_PREDICATE) + Page findScopedPaymentTasks(@Param("tenantId") String tenantId, + @Param("scope") String scope, @Param("actorId") Long actorId, + @Param("departmentIds") List departmentIds, Pageable pageable); + + @Query("select a from ReimApplication a where a.id = :id and a.tenantId = :tenantId " + + "and a.deleted = false and " + SCOPE_PREDICATE) + Optional findScopedById(@Param("id") Long id, @Param("tenantId") String tenantId, + @Param("scope") String scope, @Param("actorId") Long actorId, + @Param("departmentIds") List departmentIds); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select a from ReimApplication a where a.id = :id and a.tenantId = :tenantId " + + "and a.deleted = false and " + SCOPE_PREDICATE) + Optional findScopedByIdForUpdate(@Param("id") Long id, + @Param("tenantId") String tenantId, @Param("scope") String scope, + @Param("actorId") Long actorId, @Param("departmentIds") List departmentIds); + + @Query("select a from ReimApplication a where a.applicationNo = :applicationNo " + + "and a.tenantId = :tenantId and a.deleted = false and " + SCOPE_PREDICATE) + Optional findScopedByApplicationNo(@Param("applicationNo") String applicationNo, + @Param("tenantId") String tenantId, @Param("scope") String scope, + @Param("actorId") Long actorId, @Param("departmentIds") List departmentIds); + + @Query("select count(a), " + + "sum(case when a.approvalStatus = 'PENDING' then 1 else 0 end), " + + "sum(case when a.approvalStatus = 'APPROVED' then 1 else 0 end), " + + "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) " + + "from ReimApplication a where a.tenantId = :tenantId and a.deleted = false and " + + SCOPE_PREDICATE) + Object[] aggregateScoped(@Param("tenantId") String tenantId, @Param("scope") String scope, + @Param("actorId") Long actorId, @Param("departmentIds") List departmentIds); } diff --git a/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java b/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java index ca2819d..9a9afcb 100644 --- a/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java +++ b/src/main/java/com/finance/system/repository/ReimAttachmentRepository.java @@ -38,6 +38,9 @@ public interface ReimAttachmentRepository extends JpaRepository findTop50ByUploadStatusAndCreatedAtBeforeOrderByIdAsc( + String uploadStatus, LocalDateTime createdAt); + @Query("select coalesce(sum(a.fileSize), 0) from ReimAttachment a " + "where a.uploaderId = :uploaderId and a.createdAt >= :createdAt") Long sumUploadedBytesSince(@Param("uploaderId") Long uploaderId, diff --git a/src/main/java/com/finance/system/repository/ReimPaymentRepository.java b/src/main/java/com/finance/system/repository/ReimPaymentRepository.java index bd535df..151c323 100644 --- a/src/main/java/com/finance/system/repository/ReimPaymentRepository.java +++ b/src/main/java/com/finance/system/repository/ReimPaymentRepository.java @@ -3,23 +3,58 @@ package com.finance.system.repository; import com.finance.system.entity.ReimPayment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import javax.persistence.LockModeType; import java.util.List; +import java.util.Optional; @Repository public interface ReimPaymentRepository extends JpaRepository { List findByApplicationId(Long applicationId); - List findByPayeeId(Long payeeId); - - ReimPayment findByPaymentNo(String paymentNo); - ReimPayment findByIdempotencyKey(String idempotencyKey); - List findByOperatorId(Long operatorId); - - List findByPaymentStatus(String paymentStatus); - List findTopByPaymentNoStartingWithOrderByPaymentNoDesc(String prefix); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select p from ReimPayment p where p.id = :id and p.tenantId = :tenantId and p.deleted = false") + Optional findByIdForUpdate(@Param("id") Long id, @Param("tenantId") String tenantId); + + @Query("select p from ReimPayment p, ReimApplication a where p.applicationId = a.id " + + "and p.tenantId = :tenantId and a.tenantId = :tenantId and p.deleted = false and a.deleted = false " + + "and (:scope = 'ALL' or (:scope = 'SELF' and a.applicantId = :actorId) " + + "or (:scope = 'CURRENT_APPROVER' and a.currentApproverId = :actorId) " + + "or (:scope in ('DEPARTMENT','DEPARTMENT_TREE') and a.departmentId in :departmentIds)) " + + "and (:status is null or p.paymentStatus = :status) order by p.createdAt desc, p.id desc") + Page findScoped(@Param("tenantId") String tenantId, @Param("scope") String scope, + @Param("actorId") Long actorId, @Param("departmentIds") List departmentIds, + @Param("status") String status, Pageable pageable); + + @Query("select p from ReimPayment p, ReimApplication a where p.applicationId = a.id " + + "and p.tenantId = :tenantId and a.tenantId = :tenantId " + + "and p.deleted = false and a.deleted = false and a.applicantId = :applicantId " + + "and (:scope = 'ALL' or (:scope = 'SELF' and a.applicantId = :actorId) " + + "or (:scope = 'CURRENT_APPROVER' and a.currentApproverId = :actorId) " + + "or (:scope in ('DEPARTMENT','DEPARTMENT_TREE') and a.departmentId in :departmentIds)) " + + "order by p.createdAt desc, p.id desc") + List findScopedForApplicant(@Param("tenantId") String tenantId, + @Param("scope") String scope, @Param("actorId") Long actorId, + @Param("departmentIds") List departmentIds, @Param("applicantId") Long applicantId); + + @Query("select p from ReimPayment p, ReimApplication a where p.applicationId = a.id " + + "and p.paymentNo = :paymentNo and p.tenantId = :tenantId and a.tenantId = :tenantId " + + "and p.deleted = false and a.deleted = false " + + "and (:scope = 'ALL' or (:scope = 'SELF' and a.applicantId = :actorId) " + + "or (:scope = 'CURRENT_APPROVER' and a.currentApproverId = :actorId) " + + "or (:scope in ('DEPARTMENT','DEPARTMENT_TREE') and a.departmentId in :departmentIds))") + Optional findScopedByPaymentNo(@Param("paymentNo") String paymentNo, + @Param("tenantId") String tenantId, @Param("scope") String scope, + @Param("actorId") Long actorId, @Param("departmentIds") List departmentIds); } diff --git a/src/main/java/com/finance/system/repository/SysApiAccessLogRepository.java b/src/main/java/com/finance/system/repository/SysApiAccessLogRepository.java index 9aa20b7..df1f1b6 100644 --- a/src/main/java/com/finance/system/repository/SysApiAccessLogRepository.java +++ b/src/main/java/com/finance/system/repository/SysApiAccessLogRepository.java @@ -13,11 +13,32 @@ import java.util.List; public interface SysApiAccessLogRepository extends JpaRepository { @Query("select l from SysApiAccessLog l " - + "where (:category is null or :category = '' or l.category = :category) " + + "where l.tenantId = :tenantId and l.organizationId = :organizationId " + + "and (:category is null or :category = '' or l.category = :category) " + + "and (:actorId is null or l.operatorId = :actorId) " + "and (:operator is null or :operator = '' or l.operatorName = :operator) " + "order by l.createdAt desc, l.id desc") List search( + @Param("tenantId") String tenantId, + @Param("organizationId") Long organizationId, @Param("category") String category, + @Param("actorId") Long actorId, @Param("operator") String operator, Pageable pageable); + + @Query("select l from SysApiAccessLog l where l.tenantId = :tenantId " + + "and l.organizationId = :organizationId " + + "and (:category is null or l.category = :category) " + + "and (:actorId is null or l.operatorId = :actorId) " + + "and (:operator is null or l.operatorName = :operator) " + + "and (:outcome is null or l.outcome = :outcome) " + + "and (:cursorTime is null or l.createdAt < :cursorTime " + + "or (l.createdAt = :cursorTime and l.id < :cursorId)) " + + "order by l.createdAt desc, l.id desc") + List searchCursor(@Param("tenantId") String tenantId, + @Param("organizationId") Long organizationId, + @Param("category") String category, @Param("actorId") Long actorId, + @Param("operator") String operator, @Param("outcome") String outcome, + @Param("cursorTime") java.time.LocalDateTime cursorTime, @Param("cursorId") Long cursorId, + Pageable pageable); } diff --git a/src/main/java/com/finance/system/repository/SysBankAccountRepository.java b/src/main/java/com/finance/system/repository/SysBankAccountRepository.java index b166877..c0e104c 100644 --- a/src/main/java/com/finance/system/repository/SysBankAccountRepository.java +++ b/src/main/java/com/finance/system/repository/SysBankAccountRepository.java @@ -2,8 +2,12 @@ package com.finance.system.repository; import com.finance.system.entity.SysBankAccount; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import javax.persistence.LockModeType; import java.util.List; @Repository @@ -11,5 +15,17 @@ public interface SysBankAccountRepository extends JpaRepository findByUserId(Long userId); + List findByUserIdIn(List userIds); + + List findByPayeeId(Long payeeId); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select a from SysBankAccount a where a.payeeId = :payeeId order by a.id") + List findByPayeeIdForUpdate(@Param("payeeId") Long payeeId); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select a from SysBankAccount a where a.userId = :userId order by a.id") + List findByUserIdForUpdate(@Param("userId") Long userId); + SysBankAccount findByUserIdAndIsDefaultTrue(Long userId); -} \ No newline at end of file +} diff --git a/src/main/java/com/finance/system/repository/SysBudgetRepository.java b/src/main/java/com/finance/system/repository/SysBudgetRepository.java deleted file mode 100644 index 96c38cb..0000000 --- a/src/main/java/com/finance/system/repository/SysBudgetRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.finance.system.repository; - -import com.finance.system.entity.SysBudget; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface SysBudgetRepository extends JpaRepository { - - SysBudget findByDeptIdAndExpenseTypeIdAndFiscalYear(Long deptId, Long expenseTypeId, Integer fiscalYear); - - List findByDeptId(Long deptId); - - List findByExpenseTypeId(Long expenseTypeId); -} \ No newline at end of file diff --git a/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java b/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java index 3abeca0..94d1c7b 100644 --- a/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java +++ b/src/main/java/com/finance/system/repository/SysIntegrationConfigRepository.java @@ -9,6 +9,7 @@ import java.util.Optional; @Repository public interface SysIntegrationConfigRepository extends JpaRepository { - Optional findByProviderAndConfigKey(String provider, String configKey); - List findByProviderOrderByConfigKeyAsc(String provider); + Optional findByTenantIdAndProviderAndConfigKey( + String tenantId, String provider, String configKey); + List findByTenantIdAndProviderOrderByConfigKeyAsc(String tenantId, String provider); } diff --git a/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java b/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java index 279c315..6c99df5 100644 --- a/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java +++ b/src/main/java/com/finance/system/repository/SysKingdeeSyncConfigRepository.java @@ -12,11 +12,13 @@ import java.util.Optional; @Repository public interface SysKingdeeSyncConfigRepository extends JpaRepository { - boolean existsByTargetTableName(String targetTableName); - boolean existsByTargetTableNameAndIdNot(String targetTableName, Long id); - Optional findByTargetTableName(String targetTableName); + java.util.List findByTenantIdOrderByIdAsc(String tenantId); + boolean existsByTenantIdAndTargetTableNameAndIdNot(String tenantId, String targetTableName, Long id); + Optional findByIdAndTenantId(Long id, String tenantId); + Optional findByTenantIdAndTargetTableName(String tenantId, String targetTableName); @Lock(LockModeType.PESSIMISTIC_WRITE) - @Query("select c from SysKingdeeSyncConfig c where c.id = :id") - Optional findByIdForUpdate(@Param("id") Long id); + @Query("select c from SysKingdeeSyncConfig c where c.id = :id and c.tenantId = :tenantId") + Optional findByIdAndTenantIdForUpdate(@Param("id") Long id, + @Param("tenantId") String tenantId); } diff --git a/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java b/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java index 86b074b..c5cc7a2 100644 --- a/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java +++ b/src/main/java/com/finance/system/repository/SysKingdeeSyncRunRepository.java @@ -15,8 +15,9 @@ import javax.persistence.LockModeType; @Repository public interface SysKingdeeSyncRunRepository extends JpaRepository { - List findTop100ByConfigIdOrderByStartedAtDescIdDesc(Long configId); - Optional findFirstByConfigIdAndStatusOrderByStartedAtDesc(Long configId, String status); + List findTop100ByTenantIdAndConfigIdOrderByStartedAtDescIdDesc(String tenantId, Long configId); + Optional findFirstByTenantIdAndConfigIdAndStatusOrderByStartedAtDesc( + String tenantId, Long configId, String status); void deleteByConfigId(Long configId); @Lock(LockModeType.PESSIMISTIC_WRITE) diff --git a/src/main/java/com/finance/system/repository/SysPayeeRepository.java b/src/main/java/com/finance/system/repository/SysPayeeRepository.java new file mode 100644 index 0000000..2f69b17 --- /dev/null +++ b/src/main/java/com/finance/system/repository/SysPayeeRepository.java @@ -0,0 +1,27 @@ +package com.finance.system.repository; + +import com.finance.system.entity.SysPayee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import javax.persistence.LockModeType; +import java.util.List; +import java.util.Optional; + +public interface SysPayeeRepository extends JpaRepository { + List findByTenantIdAndOrganizationIdOrderByDisplayNameAscIdAsc( + String tenantId, Long organizationId); + + Optional findByEmployeeUserId(Long employeeUserId); + + Optional findByEmployeeOpenId(String employeeOpenId); + + boolean existsByTenantIdAndSupplierCreditCodeAndIdNot( + String tenantId, String supplierCreditCode, Long id); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query("select p from SysPayee p where p.id = :id") + Optional findByIdForUpdate(@Param("id") Long id); +} diff --git a/src/main/java/com/finance/system/repository/SysUserKingdeeAccountRepository.java b/src/main/java/com/finance/system/repository/SysUserKingdeeAccountRepository.java index 78dd7c8..88a5c99 100644 --- a/src/main/java/com/finance/system/repository/SysUserKingdeeAccountRepository.java +++ b/src/main/java/com/finance/system/repository/SysUserKingdeeAccountRepository.java @@ -8,6 +8,9 @@ import java.util.Optional; @Repository public interface SysUserKingdeeAccountRepository extends JpaRepository { - Optional findByKingdeeUsername(String kingdeeUsername); - boolean existsByUserId(Long userId); + Optional findByTenantIdAndKingdeeUsername(String tenantId, String kingdeeUsername); + Optional findByUserIdAndTenantId(Long userId, String tenantId); + Optional findByEmployeeOpenIdAndTenantId(String employeeOpenId, String tenantId); + java.util.List findByTenantId(String tenantId); + boolean existsByUserIdAndTenantId(Long userId, String tenantId); } diff --git a/src/main/java/com/finance/system/repository/SysUserRepository.java b/src/main/java/com/finance/system/repository/SysUserRepository.java index 1d848ae..7ca8008 100644 --- a/src/main/java/com/finance/system/repository/SysUserRepository.java +++ b/src/main/java/com/finance/system/repository/SysUserRepository.java @@ -15,11 +15,19 @@ public interface SysUserRepository extends JpaRepository { SysUser findByFeishuOpenId(String feishuOpenId); + @Query(value = "SELECT COUNT(*) FROM feishu_directory_user WHERE open_id=:openId AND employment_status='ACTIVE' AND eligible=1", nativeQuery = true) + long countActiveDirectoryEmployee(@Param("openId") String openId); + + @Query(value = "SELECT name FROM feishu_directory_user WHERE open_id=:openId AND employment_status='ACTIVE' AND eligible=1", nativeQuery = true) + String findActiveDirectoryEmployeeName(@Param("openId") String openId); + SysUser findByFeishuUserId(String feishuUserId); SysUser findByEmployeeNo(String employeeNo); List findByUserType(String userType); + List findByTenantId(String tenantId); + Optional findByIdAndTenantId(Long id, String tenantId); @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) @Query("select u from SysUser u where u.id = :id") diff --git a/src/main/java/com/finance/system/security/ApiAccessLogFilter.java b/src/main/java/com/finance/system/security/ApiAccessLogFilter.java index 22ab951..a2e5593 100644 --- a/src/main/java/com/finance/system/security/ApiAccessLogFilter.java +++ b/src/main/java/com/finance/system/security/ApiAccessLogFilter.java @@ -1,6 +1,8 @@ package com.finance.system.security; import com.finance.system.entity.SysApiAccessLog; +import com.finance.system.observability.LogText; +import com.finance.system.observability.RequestContext; import com.finance.system.service.ApiAccessLogService; import com.finance.system.util.AuditUtil; import lombok.RequiredArgsConstructor; @@ -8,68 +10,75 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.servlet.HandlerMapping; +import org.slf4j.MDC; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Map; import java.util.UUID; +import java.util.concurrent.TimeUnit; /** - * Records every /api/** call for the in-app operation log. Persistence is - * asynchronous so request latency is not tied to the logging write path. - * Authorization headers and known secret query keys are never stored. + * Records request-safe /api/** access metadata for the compatibility log UI. + * Health checks and preflight requests are excluded, and raw paths, query + * strings, bodies, headers, and user-agent values are never persisted. */ @Component @Slf4j @RequiredArgsConstructor public class ApiAccessLogFilter extends OncePerRequestFilter { - private static final Set REDACT_QUERY_KEYS = new HashSet<>(Arrays.asList( - "password", "passwd", "secret", "token", "access_token", "refresh_token", - "authorization", "code", "state", "ticket", "signature", "nonce", - "client_secret", "app_secret", "jwt", "email", "mobile", "phone", - "open_id", "user_id")); - private final ApiAccessLogService apiAccessLogService; @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = path(request); - // Capture every API method (including read and preflight requests), as - // well as operational actuator endpoints. Static resources are excluded. - return !(path.startsWith("/api/") || path.startsWith("/actuator/")); + if ("OPTIONS".equalsIgnoreCase(request.getMethod())) return true; + if (path.equals("/actuator/health") || path.startsWith("/actuator/health/")) return true; + return !path.startsWith("/api/"); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - long started = System.currentTimeMillis(); + long startedNanos = System.nanoTime(); String requestId = resolveRequestId(request); + Map previousMdc = MDC.getCopyOfContextMap(); + UserPrincipal principal = AuditUtil.getCurrentUser(); + String terminalErrorCode = null; + if (principal != null && principal.getId() != null) MDC.put("user_id", String.valueOf(principal.getId())); response.setHeader("X-Request-Id", requestId); try { filterChain.doFilter(request, response); + } catch (ServletException e) { + terminalErrorCode = "SERVLET_EXCEPTION"; + throw e; + } catch (IOException e) { + terminalErrorCode = "IO_EXCEPTION"; + throw e; + } catch (RuntimeException e) { + terminalErrorCode = "RUNTIME_EXCEPTION"; + throw e; } finally { SysApiAccessLog entry = null; try { - entry = buildEntry(request, response, requestId, started); - UserPrincipal user = AuditUtil.getCurrentUser(); - String operatorName = user == null ? entry.getOperatorName() : safe(user.getRealName(), 100); - String operatorId = user == null || user.getId() == null ? "未登录" : String.valueOf(user.getId()); - log.info("接口访问 | 请求ID={} | 操作人={}(用户ID={}) | 方法={} | 路径={} | 参数={} | 状态={} | 耗时={}毫秒 | 分类={} | 来源IP={}", - entry.getRequestId(), operatorName, operatorId, methodLabel(entry.getHttpMethod()), - entry.getRequestPath(), entry.getQueryString() == null ? "无" : entry.getQueryString(), - statusLabel(entry.getStatusCode()), entry.getDurationMs(), entry.getCategory(), - entry.getClientIp()); - } catch (Exception ignored) { - log.warn("接口日志记录失败 | 请求ID={} | 方法={} | 路径={} | 状态码={}", - requestId, methodLabel(safe(request.getMethod(), 16)), - safe(path(request), 500), response.getStatus()); + entry = buildEntry(request, response, requestId, startedNanos, terminalErrorCode); + log.info("接口调用 | 接口名称={} | 请求方式={} | 路由={} | 操作人={} | 操作人标识={} | 响应状态={} | 执行结果={} | 耗时={}毫秒 | 请求编号={} | 追踪编号={}", + LogText.apiOperation(entry.getHttpMethod(), entry.getRequestRoute()), + LogText.method(entry.getHttpMethod()), entry.getRequestRoute(), entry.getOperatorName(), + entry.getOperatorId(), LogText.status(entry.getStatusCode()), LogText.outcome(entry.getOutcome()), + entry.getDurationMs(), entry.getRequestId(), entry.getTraceId()); + } catch (Exception failure) { + String diagnostic = captureDiagnostic(failure); + log.warn("接口访问日志采集失败 | 接口名称={} | 请求方式={} | 路由={} | 响应状态={} | 诊断={} | 请求编号={}", + LogText.apiOperation(request.getMethod(), route(request)), LogText.method(request.getMethod()), + route(request), LogText.status(response.getStatus()), LogText.error(diagnostic), requestId); } if (entry != null) { try { @@ -78,40 +87,53 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { // Logging must never break the original request/response path. } } + if (previousMdc == null) MDC.clear(); + else MDC.setContextMap(previousMdc); } } private SysApiAccessLog buildEntry(HttpServletRequest request, HttpServletResponse response, - String requestId, long started) { - String requestPath = truncate(path(request), 500); + String requestId, long startedNanos, String terminalErrorCode) { + String requestRoute = route(request); UserPrincipal user = AuditUtil.getCurrentUser(); + String trustedTenant = user == null ? RequestContext.tenantId(request) : user.getTenantId(); + Long trustedOrganization = user == null ? RequestContext.organizationId(request) : user.getOrganizationId(); + if (!StringUtils.hasText(trustedTenant) || trustedOrganization == null || trustedOrganization <= 0) { + throw new IllegalArgumentException("ACCESS_LOG_TRUSTED_CONTEXT_REQUIRED"); + } String operatorName = user != null && StringUtils.hasText(user.getRealName()) ? user.getRealName() : (user != null && StringUtils.hasText(user.getEmployeeNo()) ? user.getEmployeeNo() : "匿名"); - int status = response.getStatus(); + int status = terminalErrorCode != null && response.getStatus() < 400 ? 500 : response.getStatus(); return SysApiAccessLog.builder() .requestId(requestId) + .clientRequestId(RequestContext.clientRequestId(request)) + .traceId(RequestContext.traceId(request)) + .spanId(RequestContext.spanId(request)) + .tenantId(trustedTenant) + .organizationId(trustedOrganization) .httpMethod(truncate(request.getMethod(), 16)) - .requestPath(requestPath) - .queryString(sanitizeQuery(request.getQueryString())) - .category(ApiAccessLogService.categorize(requestPath)) + .requestPath(requestRoute) + .requestRoute(requestRoute) + .queryString(null) + .category(ApiAccessLogService.categorize(requestRoute)) .operatorId(user == null ? null : user.getId()) .operatorName(truncate(operatorName, 100)) .statusCode(status) - .durationMs((int) Math.min(Integer.MAX_VALUE, Math.max(0, System.currentTimeMillis() - started))) + .durationMs((int) Math.min(Integer.MAX_VALUE, + TimeUnit.NANOSECONDS.toMillis(Math.max(0L, System.nanoTime() - startedNanos)))) .clientIp(truncate(clientIp(request), 64)) - .userAgent(safe(request.getHeader("User-Agent"), 500)) - .errorMessage(status >= 400 ? truncate("HTTP " + status, 1000) : null) + .userAgent(null) + .outcome(terminalErrorCode != null || status >= 400 ? "FAILURE" : "SUCCESS") + .errorCode(terminalErrorCode != null ? terminalErrorCode : (status >= 400 ? "HTTP_" + status : null)) + .errorMessage(null) + .createdAt(LocalDateTime.now(ZoneOffset.UTC)) .build(); } private String resolveRequestId(HttpServletRequest request) { - String incoming = request.getHeader("X-Request-Id"); - if (StringUtils.hasText(incoming) && incoming.length() <= 64 - && incoming.matches("[A-Za-z0-9._-]+")) { - return incoming; - } - return UUID.randomUUID().toString().replace("-", ""); + String contextual = RequestContext.requestId(request); + return StringUtils.hasText(contextual) ? contextual : UUID.randomUUID().toString().replace("-", ""); } private String path(HttpServletRequest request) { @@ -129,31 +151,13 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { return safe(request.getRemoteAddr(), 64); } - private String sanitizeQuery(String query) { - if (!StringUtils.hasText(query)) { - return null; + private String route(HttpServletRequest request) { + Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); + if (pattern != null && StringUtils.hasText(String.valueOf(pattern))) { + return truncate(String.valueOf(pattern), 500); } - StringBuilder sanitized = new StringBuilder(); - for (String part : query.split("&")) { - if (!StringUtils.hasText(part)) { - continue; - } - if (sanitized.length() > 0) { - sanitized.append('&'); - } - int eq = part.indexOf('='); - String key = eq >= 0 ? part.substring(0, eq) : part; - String value = eq >= 0 ? part.substring(eq + 1) : ""; - if (REDACT_QUERY_KEYS.contains(key.toLowerCase(Locale.ROOT))) { - sanitized.append(safe(key, 100)).append('=').append("[REDACTED]"); - } else { - sanitized.append(safe(key, 100)); - if (eq >= 0) { - sanitized.append('=').append(safe(value, 200)); - } - } - } - return safe(sanitized.toString(), 1000); + // Never persist an unmatched raw path: it may contain tokens or personal identifiers. + return "UNMATCHED"; } private String truncate(String value, int max) { @@ -171,33 +175,8 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { return result.isEmpty() ? null : result; } - private String methodLabel(String method) { - if (method == null) return "未知"; - switch (method.toUpperCase(Locale.ROOT)) { - case "GET": return "GET-查询"; - case "POST": return "POST-提交"; - case "PUT": return "PUT-更新"; - case "PATCH": return "PATCH-部分更新"; - case "DELETE": return "DELETE-删除"; - case "HEAD": return "HEAD-读取元信息"; - case "OPTIONS": return "OPTIONS-跨域预检"; - default: return safe(method, 16); - } - } - - private String statusLabel(int status) { - if (status >= 500) return status + "-服务异常"; - switch (status) { - case 200: return "200-成功"; - case 201: return "201-创建成功"; - case 204: return "204-成功无内容"; - case 400: return "400-请求参数错误"; - case 401: return "401-未认证"; - case 403: return "403-无权限"; - case 404: return "404-资源不存在"; - case 409: return "409-业务冲突"; - case 422: return "422-业务校验未通过"; - default: return status + (status >= 400 ? "-请求失败" : "-已处理"); - } + private String captureDiagnostic(Exception failure) { + return failure instanceof IllegalArgumentException + ? "TRUSTED_CONTEXT_INVALID" : "ENTRY_BUILD_FAILED"; } } diff --git a/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java b/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java index 26d4f0e..1a551b8 100644 --- a/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java +++ b/src/main/java/com/finance/system/security/JwtAuthenticationFilter.java @@ -85,6 +85,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { .realName(user.getRealName()) .userType(userType) .feishuOpenId(user.getFeishuOpenId()) + .tenantId(user.getTenantId()) + .organizationId(user.getOrganizationId()) + .departmentId(user.getDepartmentId()) .build(); UsernamePasswordAuthenticationToken authentication = diff --git a/src/main/java/com/finance/system/security/PermissionChecker.java b/src/main/java/com/finance/system/security/PermissionChecker.java index 8452a5b..6de0e3e 100644 --- a/src/main/java/com/finance/system/security/PermissionChecker.java +++ b/src/main/java/com/finance/system/security/PermissionChecker.java @@ -1,5 +1,9 @@ package com.finance.system.security; +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.springframework.security.core.Authentication; import org.springframework.stereotype.Component; @@ -8,7 +12,12 @@ import org.springframework.stereotype.Component; @Component("permissionChecker") public class PermissionChecker { private final RoleService roleService; - public PermissionChecker(RoleService roleService) { this.roleService = roleService; } + private final AuthorizationService authorizationService; + + public PermissionChecker(RoleService roleService, AuthorizationService authorizationService) { + this.roleService = roleService; + this.authorizationService = authorizationService; + } public boolean has(Authentication authentication, String permissionCode) { if (authentication == null || !authentication.isAuthenticated() @@ -16,7 +25,8 @@ public class PermissionChecker { UserPrincipal principal = (UserPrincipal) authentication.getPrincipal(); if (principal.getId() == null) return false; try { - return roleService.hasPermission(principal.getId(), permissionCode); + boolean legacy = roleService.hasPermission(principal.getId(), permissionCode); + return authorizationService.evaluateLegacy(authorizationService.subject(principal), permissionCode, false, legacy); } catch (RuntimeException ex) { return false; } @@ -28,7 +38,8 @@ public class PermissionChecker { UserPrincipal principal = (UserPrincipal) authentication.getPrincipal(); if (principal.getId() == null) return false; try { - return roleService.hasEditPermission(principal.getId(), permissionCode); + boolean legacy = roleService.hasEditPermission(principal.getId(), permissionCode); + return authorizationService.evaluateLegacy(authorizationService.subject(principal), permissionCode, true, legacy); } catch (RuntimeException ex) { return false; } @@ -51,4 +62,34 @@ public class PermissionChecker { } return false; } + + /** 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); + authorizationService.check(AuthorizationRequest.builder().subject(subject) + .resource(resource).action(action).resourceContext(context).build()); + return true; + } + + 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); + return authorizationService.can(AuthorizationRequest.builder().subject(subject) + .resource(resource).action(action).resourceContext(context).build()); + } + + private boolean isGlobalIam(String resource) { + return resource != null && resource.startsWith("iam."); + } + + private SubjectContext authenticatedSubject(Authentication authentication) { + if (authentication == null || !authentication.isAuthenticated() + || !(authentication.getPrincipal() instanceof UserPrincipal)) return null; + UserPrincipal principal = (UserPrincipal) authentication.getPrincipal(); + return principal.getId() == null ? null : authorizationService.subject(principal); + } } diff --git a/src/main/java/com/finance/system/security/UserPrincipal.java b/src/main/java/com/finance/system/security/UserPrincipal.java index 33dd0bb..5dc4cf6 100644 --- a/src/main/java/com/finance/system/security/UserPrincipal.java +++ b/src/main/java/com/finance/system/security/UserPrincipal.java @@ -21,6 +21,12 @@ public class UserPrincipal implements UserDetails { private String realName; private String userType; private String feishuOpenId; + /** Loaded from sys_user for every authenticated request; never trusted from JWT claims. */ + private String tenantId; + /** Loaded from sys_user for every authenticated request; never trusted from JWT claims. */ + private Long organizationId; + /** Loaded from the database on every request; never trusted from JWT claims. */ + private Long departmentId; @Override public Collection getAuthorities() { diff --git a/src/main/java/com/finance/system/security/finance/BankAccountProtection.java b/src/main/java/com/finance/system/security/finance/BankAccountProtection.java new file mode 100644 index 0000000..87e69c3 --- /dev/null +++ b/src/main/java/com/finance/system/security/finance/BankAccountProtection.java @@ -0,0 +1,193 @@ +package com.finance.system.security.finance; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Purpose-specific protection for persisted payee bank-account numbers. */ +@Component +public class BankAccountProtection { + static final String PREFIX = "BANK[v1]:"; + private static final String CIPHER = "AES/GCM/NoPadding"; + private static final String HMAC = "HmacSHA256"; + private static final int NONCE_BYTES = 12; + private static final int TAG_BITS = 128; + private static final int KEY_BYTES = 32; + + private final String encryptionKeyRing; + private final String fingerprintKey; + private final String activeKeyVersion; + private final SecureRandom secureRandom = new SecureRandom(); + + public BankAccountProtection( + @Value("${app.bank-account.encryption-keys:${APP_BANK_ACCOUNT_ENCRYPTION_KEYS:}}") + String encryptionKeyRing, + @Value("${app.bank-account.fingerprint-key:${APP_BANK_ACCOUNT_FINGERPRINT_KEY:}}") + String fingerprintKey, + @Value("${app.bank-account.active-key-version:${APP_BANK_ACCOUNT_ACTIVE_KEY_VERSION:}}") + String activeKeyVersion) { + this.encryptionKeyRing = encryptionKeyRing; + this.fingerprintKey = fingerprintKey; + this.activeKeyVersion = activeKeyVersion; + } + + public ProtectedValue protect(String normalizedAccountNo) { + if (!StringUtils.hasText(normalizedAccountNo)) { + throw new IllegalArgumentException("BANK_ACCOUNT_NUMBER_REQUIRED"); + } + Map keys = encryptionKeys(); + String version = requireVersion(activeKeyVersion); + SecretKeySpec key = keys.get(version); + if (key == null) throw new IllegalStateException("BANK_ACCOUNT_ACTIVE_KEY_NOT_FOUND"); + byte[] nonce = new byte[NONCE_BYTES]; + secureRandom.nextBytes(nonce); + try { + Cipher cipher = Cipher.getInstance(CIPHER); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, nonce)); + cipher.updateAAD(aad(version)); + byte[] encrypted = cipher.doFinal(normalizedAccountNo.getBytes(StandardCharsets.UTF_8)); + byte[] payload = ByteBuffer.allocate(nonce.length + encrypted.length) + .put(nonce).put(encrypted).array(); + return new ProtectedValue(PREFIX + version + ":" + Base64.getEncoder().encodeToString(payload), + fingerprint(normalizedAccountNo), + FinanceFieldProjection.maskBankAccount(normalizedAccountNo), version); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("BANK_ACCOUNT_ENCRYPTION_FAILED", e); + } + } + + /** Equality lookup only; this value is never a substitute for ciphertext. */ + public String fingerprint(String normalizedAccountNo) { + if (!StringUtils.hasText(normalizedAccountNo)) { + throw new IllegalArgumentException("BANK_ACCOUNT_NUMBER_REQUIRED"); + } + try { + Mac mac = Mac.getInstance(HMAC); + mac.init(new SecretKeySpec(decodeKey(fingerprintKey, "BANK_ACCOUNT_FINGERPRINT_KEY"), HMAC)); + return hex(mac.doFinal(normalizedAccountNo.getBytes(StandardCharsets.UTF_8))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("BANK_ACCOUNT_FINGERPRINT_FAILED", e); + } + } + + /** Called only by the audited payment-secret access service. */ + public String decryptForPaymentExecution(String ciphertext) { + if (!StringUtils.hasText(ciphertext) || !ciphertext.startsWith(PREFIX)) { + throw new IllegalStateException("BANK_ACCOUNT_CIPHERTEXT_REQUIRED"); + } + try { + String encoded = ciphertext.substring(PREFIX.length()); + int separator = encoded.indexOf(':'); + if (separator <= 0 || separator == encoded.length() - 1) throw new IllegalArgumentException(); + String version = requireVersion(encoded.substring(0, separator)); + SecretKeySpec key = encryptionKeys().get(version); + if (key == null) throw new IllegalStateException("BANK_ACCOUNT_KEY_VERSION_NOT_AVAILABLE"); + byte[] payload = Base64.getDecoder().decode(encoded.substring(separator + 1)); + if (payload.length <= NONCE_BYTES) throw new IllegalArgumentException(); + byte[] nonce = new byte[NONCE_BYTES]; + byte[] encrypted = new byte[payload.length - NONCE_BYTES]; + System.arraycopy(payload, 0, nonce, 0, NONCE_BYTES); + System.arraycopy(payload, NONCE_BYTES, encrypted, 0, encrypted.length); + Cipher cipher = Cipher.getInstance(CIPHER); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, nonce)); + cipher.updateAAD(aad(version)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (IllegalStateException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException("BANK_ACCOUNT_CIPHERTEXT_INVALID", e); + } + } + + public void assertConfigured() { + String version = requireVersion(activeKeyVersion); + if (!encryptionKeys().containsKey(version)) { + throw new IllegalStateException("BANK_ACCOUNT_ACTIVE_KEY_NOT_FOUND"); + } + decodeKey(fingerprintKey, "BANK_ACCOUNT_FINGERPRINT_KEY"); + } + + private Map encryptionKeys() { + if (!StringUtils.hasText(encryptionKeyRing)) { + throw new IllegalStateException("BANK_ACCOUNT_ENCRYPTION_KEYS_REQUIRED"); + } + Map result = new LinkedHashMap<>(); + for (String entry : encryptionKeyRing.split(",")) { + int separator = entry.indexOf('='); + if (separator <= 0 || separator == entry.length() - 1) { + throw new IllegalStateException("BANK_ACCOUNT_ENCRYPTION_KEYS_INVALID"); + } + String version = requireVersion(entry.substring(0, separator).trim()); + byte[] key = decodeKey(entry.substring(separator + 1).trim(), "BANK_ACCOUNT_ENCRYPTION_KEY"); + if (result.put(version, new SecretKeySpec(key, "AES")) != null) { + throw new IllegalStateException("BANK_ACCOUNT_KEY_VERSION_DUPLICATED"); + } + } + return result; + } + + private static byte[] decodeKey(String encoded, String name) { + if (!StringUtils.hasText(encoded)) throw new IllegalStateException(name + "_REQUIRED"); + try { + byte[] key = Base64.getDecoder().decode(encoded.trim()); + if (key.length != KEY_BYTES) throw new IllegalStateException(name + "_MUST_BE_BASE64_32_BYTES"); + return key; + } catch (IllegalArgumentException e) { + throw new IllegalStateException(name + "_MUST_BE_BASE64_32_BYTES", e); + } + } + + private static String requireVersion(String value) { + if (!StringUtils.hasText(value) || !value.matches("[A-Za-z0-9._-]{1,32}")) { + throw new IllegalStateException("BANK_ACCOUNT_KEY_VERSION_INVALID"); + } + return value; + } + + private static byte[] aad(String version) { + return ("sys_bank_account|" + version).getBytes(StandardCharsets.UTF_8); + } + + private static String hex(byte[] value) { + StringBuilder result = new StringBuilder(value.length * 2); + for (byte current : value) result.append(String.format("%02x", current & 0xff)); + return result.toString(); + } + + public static final class ProtectedValue { + private final String ciphertext; + private final String fingerprint; + private final String mask; + private final String keyVersion; + + ProtectedValue(String ciphertext, String fingerprint, String mask, String keyVersion) { + this.ciphertext = ciphertext; + this.fingerprint = fingerprint; + this.mask = mask; + this.keyVersion = keyVersion; + } + + public String getCiphertext() { return ciphertext; } + public String getFingerprint() { return fingerprint; } + public String getMask() { return mask; } + public String getKeyVersion() { return keyVersion; } + + @Override + public String toString() { + return "ProtectedValue{keyVersion='" + keyVersion + "'}"; + } + } +} diff --git a/src/main/java/com/finance/system/security/finance/FinanceAuthorization.java b/src/main/java/com/finance/system/security/finance/FinanceAuthorization.java new file mode 100644 index 0000000..a792f43 --- /dev/null +++ b/src/main/java/com/finance/system/security/finance/FinanceAuthorization.java @@ -0,0 +1,151 @@ +package com.finance.system.security.finance; + +import com.finance.system.authorization.AuthorizationDecision; +import com.finance.system.authorization.AuthorizationRequest; +import com.finance.system.authorization.AuthorizationService; +import com.finance.system.authorization.DataScope; +import com.finance.system.authorization.ResourceContext; +import com.finance.system.authorization.SubjectContext; +import com.finance.system.entity.ReimApplication; +import com.finance.system.entity.SysUser; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.exception.UnauthorizedException; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.repository.SysUserRoleRepository; +import com.finance.system.security.UserPrincipal; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** Finance-domain adapter over the canonical IAM evaluator. */ +@Component +@RequiredArgsConstructor +public class FinanceAuthorization { + private final AuthorizationService authorizationService; + private final SysUserRepository users; + private final SysUserRoleRepository userRoles; + + /** + * Resolves the largest candidate data scope for the repository predicate only. + * Field obligations from this synthetic context must never be used for output; + * callers obtain those from {@link #checkApplication} for each actual row. + */ + public FinanceScope scope(Long actorId, String resource, String action) { + SubjectContext subject = subject(actorId); + ResourceContext matchingContext = ResourceContext.builder() + .resourceType(resource) + .ownerId(actorId) + .currentApproverId(actorId) + .tenantId(subject.getTenantId()) + .departmentId(subject.getDepartmentId()) + .organizationId(subject.getOrganizationId()) + .build(); + AuthorizationDecision decision = authorizationService.check(AuthorizationRequest.builder() + .subject(subject).resource(resource).action(action).resourceContext(matchingContext).build()); + DataScope resolved = decision.getResolvedScope(); + if (resolved == null) throw new UnauthorizedException("未获得财务数据范围"); + List departmentIds = new ArrayList<>(); + if (resolved == DataScope.DEPARTMENT && subject.getDepartmentId() != null) { + departmentIds.add(subject.getDepartmentId()); + } else if (resolved == DataScope.DEPARTMENT_TREE) { + departmentIds.addAll(subject.safeDepartmentTreeIds()); + if (subject.getDepartmentId() != null && !departmentIds.contains(subject.getDepartmentId())) { + departmentIds.add(subject.getDepartmentId()); + } + } + if (departmentIds.isEmpty()) departmentIds = Collections.singletonList(-1L); + return new FinanceScope(resolved, actorId, departmentIds, subject.getTenantId()); + } + + public AuthorizationDecision checkApplication(Long actorId, String resource, String action, + ReimApplication application) { + return authorizationService.check(applicationRequest(actorId, resource, action, application)); + } + + /** Capability probe for server-generated actions; unlike check, a denied probe is not an operation attempt. */ + public boolean canApplication(Long actorId, String resource, String action, + ReimApplication application) { + return authorizationService.can(applicationRequest(actorId, resource, action, application)); + } + + /** Evaluates a user-owned resource against its real isolation and ownership boundary. */ + public AuthorizationDecision checkUserResource(SubjectContext subject, String resource, String action, + SysUser owner, String resourceId) { + return authorizationService.check(userResourceRequest(subject, resource, action, owner, resourceId)); + } + + /** Read/list probe for a user-owned resource; explicit DENY remains authoritative. */ + public boolean canUserResource(SubjectContext subject, String resource, String action, + SysUser owner, String resourceId) { + return authorizationService.can(userResourceRequest(subject, resource, action, owner, resourceId)); + } + + private AuthorizationRequest userResourceRequest(SubjectContext subject, String resource, String action, + SysUser owner, String resourceId) { + if (subject == null || owner == null || owner.getId() == null) { + throw new ResourceNotFoundException("目标用户不存在"); + } + return AuthorizationRequest.builder().subject(subject).resource(resource).action(action) + .resourceContext(ResourceContext.builder().resourceType(resource).resourceId(resourceId) + .tenantId(owner.getTenantId()).organizationId(owner.getOrganizationId()) + .ownerId(owner.getId()).departmentId(owner.getDepartmentId()).build()) + .build(); + } + + private AuthorizationRequest applicationRequest(Long actorId, String resource, String action, + ReimApplication application) { + if (application == null) throw new ResourceNotFoundException("报销申请不存在"); + SubjectContext subject = subject(actorId); + SysUser owner = users.findById(application.getApplicantId()) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + return AuthorizationRequest.builder() + .subject(subject).resource(resource).action(action) + .resourceContext(ResourceContext.builder().resourceType(resource) + .resourceId(String.valueOf(application.getId())) + .tenantId(application.getTenantId()) + .ownerId(application.getApplicantId()) + .currentApproverId(application.getCurrentApproverId()) + .departmentId(application.getDepartmentId()) + .organizationId(owner.getOrganizationId()).build()) + .build(); + } + + public AuthorizationDecision checkProspectiveApprover(Long actorId, ReimApplication application) { + SubjectContext subject = subject(actorId); + SysUser owner = users.findById(application.getApplicantId()) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + return authorizationService.check(AuthorizationRequest.builder().subject(subject) + .resource("finance.approval").action("decide") + .resourceContext(ResourceContext.builder().resourceType("finance.approval") + .resourceId(String.valueOf(application.getId())).ownerId(application.getApplicantId()) + .tenantId(application.getTenantId()) + .currentApproverId(actorId).departmentId(application.getDepartmentId()) + .organizationId(owner.getOrganizationId()).build()).build()); + } + + public SubjectContext subject(Long actorId) { + if (actorId == null) throw new UnauthorizedException("未登录"); + SysUser user = users.findById(actorId).orElseThrow(() -> new UnauthorizedException("当前用户不存在")); + if (user.getStatus() != null && !"ACTIVE".equalsIgnoreCase(user.getStatus())) { + throw new UnauthorizedException("当前用户已停用"); + } + SubjectContext base = authorizationService.subject(UserPrincipal.builder().id(user.getId()) + .employeeNo(user.getEmployeeNo()).realName(user.getRealName()) + .userType(user.getUserType()).feishuOpenId(user.getFeishuOpenId()) + .tenantId(user.getTenantId()).organizationId(user.getOrganizationId()) + .departmentId(user.getDepartmentId()).build()); + SubjectContext.SubjectContextBuilder result = SubjectContext.builder().userId(base.getUserId()) + .tenantId(base.getTenantId()).organizationId(base.getOrganizationId()) + .departmentId(base.getDepartmentId()); + for (Long departmentId : base.safeDepartmentTreeIds()) result.departmentTreeId(departmentId); + userRoles.findByIdUserId(actorId).forEach(link -> { + if (link != null && link.getId() != null && link.getId().getRoleId() != null) + result.roleId(link.getId().getRoleId()); + }); + return result.build(); + } + +} diff --git a/src/main/java/com/finance/system/security/finance/FinanceFieldProjection.java b/src/main/java/com/finance/system/security/finance/FinanceFieldProjection.java new file mode 100644 index 0000000..554512c --- /dev/null +++ b/src/main/java/com/finance/system/security/finance/FinanceFieldProjection.java @@ -0,0 +1,126 @@ +package com.finance.system.security.finance; + +import com.finance.system.authorization.AuthorizationDecision; +import com.finance.system.authorization.FieldAccess; +import com.finance.system.dto.PaymentDetailDto; +import com.finance.system.dto.PaymentRecordDto; +import com.finance.system.dto.PaymentTaskDto; +import com.finance.system.dto.ReimApplicationDetail; +import com.finance.system.dto.ReimApplicationSummary; +import org.springframework.stereotype.Component; + +/** Applies backend-only field obligations. Nulls are omitted by finance DTO JSON contracts. */ +@Component +public class FinanceFieldProjection { + + public ReimApplicationDetail application(ReimApplicationDetail value, AuthorizationDecision decision) { + if (hidden(decision, "applicantId")) value.setApplicantId(null); + 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, "currentApproverId")) value.setCurrentApproverId(null); + if (!readable(decision, "payeeName")) value.setPayeeName(null); + else if (masked(decision, "payeeName")) value.setPayeeName(mask(value.getPayeeName())); + // payeeBankId is never serialized, even with EDIT access. + value.setPayeeBankId(null); + if (!readable(decision, "bankAccount")) { + value.setBankName(null); + value.setBankAccountMask(null); + } else if (masked(decision, "bankAccount")) { + value.setBankName(null); + } + if (!readable(decision, "returnReason")) value.setReturnReason(null); + else if (masked(decision, "returnReason")) value.setReturnReason(mask(value.getReturnReason())); + if (!readable(decision, "attachments")) value.setAttachments(null); + if (!readable(decision, "approvalRecords")) value.setApprovalRecords(null); + if (!readable(decision, "payments")) value.setPayments(null); + if (!readable(decision, "formSnapshot")) value.setFormSnapshot(null); + return value; + } + + 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, "returnReason")) value.setReturnReason(null); + else if (masked(decision, "returnReason")) value.setReturnReason(mask(value.getReturnReason())); + return value; + } + + public PaymentTaskDto payment(PaymentTaskDto value, AuthorizationDecision decision) { + 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); + } + if (!readable(decision, "bankAccount")) { + value.setBankName(null); value.setBankAccountMask(null); + } else if (masked(decision, "bankAccount")) value.setBankName(null); + return value; + } + + public PaymentDetailDto payment(PaymentDetailDto value, AuthorizationDecision decision) { + 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); + } + if (!readable(decision, "bankAccount")) { + value.setBankName(null); value.setBranchName(null); value.setBankAccountMask(null); + } else if (masked(decision, "bankAccount")) { + value.setBranchName(null); + } + if (!readable(decision, "paymentHistory")) value.setPaymentHistory(null); + if (!readable(decision, "approvalRecords")) value.setApprovalRecords(null); + return value; + } + + public PaymentRecordDto payment(PaymentRecordDto value, AuthorizationDecision decision) { + if (!readable(decision, "amount")) { + value.setPaymentAmount(null); value.setTotalAmount(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, "remark")) value.setRemark(null); + else if (masked(decision, "remark")) value.setRemark(mask(value.getRemark())); + return value; + } + + public static String maskBankAccount(String raw) { + if (raw == null) return null; + String compact = raw.replaceAll("\\s+", ""); + if (compact.length() <= 4) return "****"; + return "****" + compact.substring(compact.length() - 4); + } + + public static String maskIdentityNumber(String raw) { + if (raw == null) return null; + String compact = raw.trim(); + if (compact.length() <= 7) return "****"; + return compact.substring(0, 3) + "***********" + + compact.substring(compact.length() - 4); + } + + private boolean hidden(AuthorizationDecision decision, String field) { + return decision == null || decision.accessFor(field) == FieldAccess.HIDDEN; + } + + private boolean readable(AuthorizationDecision decision, String field) { + return !hidden(decision, field); + } + + private boolean masked(AuthorizationDecision decision, String field) { + return decision != null && decision.accessFor(field) == FieldAccess.MASKED; + } + + private String mask(String value) { + if (value == null) return null; + if (value.length() <= 4) return "****"; + return value.substring(0, 2) + "****" + value.substring(value.length() - 2); + } +} diff --git a/src/main/java/com/finance/system/security/finance/FinanceScope.java b/src/main/java/com/finance/system/security/finance/FinanceScope.java new file mode 100644 index 0000000..fb6b7e1 --- /dev/null +++ b/src/main/java/com/finance/system/security/finance/FinanceScope.java @@ -0,0 +1,18 @@ +package com.finance.system.security.finance; + +import com.finance.system.authorization.DataScope; +import lombok.Value; + +import java.util.List; + +@Value +public class FinanceScope { + DataScope dataScope; + Long actorId; + List departmentIds; + String tenantId; + + public String code() { + return dataScope.name(); + } +} diff --git a/src/main/java/com/finance/system/security/integration/IntegrationAccess.java b/src/main/java/com/finance/system/security/integration/IntegrationAccess.java new file mode 100644 index 0000000..b24a8c4 --- /dev/null +++ b/src/main/java/com/finance/system/security/integration/IntegrationAccess.java @@ -0,0 +1,25 @@ +package com.finance.system.security.integration; + +import com.finance.system.authorization.DataScope; +import lombok.Value; + +@Value +public class IntegrationAccess { + String tenantId; + Long actorId; + DataScope dataScope; + + public IntegrationAccess(String tenantId, Long actorId, DataScope dataScope) { + this.tenantId = tenantId; + this.actorId = actorId; + this.dataScope = dataScope; + } + + public IntegrationAccess(String tenantId, Long actorId) { + this(tenantId, actorId, DataScope.ALL); + } + + public boolean isAll() { + return dataScope == DataScope.ALL || dataScope == DataScope.GLOBAL; + } +} diff --git a/src/main/java/com/finance/system/security/integration/IntegrationAuthorization.java b/src/main/java/com/finance/system/security/integration/IntegrationAuthorization.java new file mode 100644 index 0000000..3ab5927 --- /dev/null +++ b/src/main/java/com/finance/system/security/integration/IntegrationAuthorization.java @@ -0,0 +1,66 @@ +package com.finance.system.security.integration; + +import com.finance.system.authorization.AuthorizationRequest; +import com.finance.system.authorization.AuthorizationDecision; +import com.finance.system.authorization.AuthorizationService; +import com.finance.system.authorization.ResourceContext; +import com.finance.system.authorization.SubjectContext; +import com.finance.system.exception.UnauthorizedException; +import com.finance.system.security.UserPrincipal; +import com.finance.system.util.AuditUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.StringUtils; + +/** Canonical integration-management authorization using only trusted principal context. */ +@Component +@RequiredArgsConstructor +public class IntegrationAuthorization { + private final AuthorizationService authorizationService; + @Value("${observability.tenant-id:default}") + private String systemTenant = "default"; + + public IntegrationAccess require(String resource, String action) { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null || principal.getId() == null) throw new UnauthorizedException("未登录"); + SubjectContext subject = authorizationService.subject(principal); + if (subject == null || !StringUtils.hasText(subject.getTenantId()) + || subject.getOrganizationId() == null) { + throw new AccessDeniedException("缺少集成配置隔离边界"); + } + requireSystemTenant(subject); + ResourceContext context = ResourceContext.builder().resourceType(resource) + .tenantId(subject.getTenantId()).organizationId(subject.getOrganizationId()) + .ownerId(subject.getUserId()).build(); + AuthorizationDecision decision = authorizationService.check(AuthorizationRequest.builder().subject(subject) + .resource(resource).action(action).resourceContext(context).build()); + return new IntegrationAccess(subject.getTenantId(), subject.getUserId(), decision.getResolvedScope()); + } + + public IntegrationAccess requireOwnOrAll(String resource, String allAction, String ownAction) { + UserPrincipal principal = AuditUtil.getCurrentUser(); + if (principal == null || principal.getId() == null) throw new UnauthorizedException("未登录"); + SubjectContext subject = authorizationService.subject(principal); + if (subject == null || !StringUtils.hasText(subject.getTenantId()) + || subject.getOrganizationId() == null) throw new AccessDeniedException("缺少集成配置隔离边界"); + requireSystemTenant(subject); + ResourceContext context = ResourceContext.builder().resourceType(resource) + .tenantId(subject.getTenantId()).organizationId(subject.getOrganizationId()) + .ownerId(subject.getUserId()).build(); + AuthorizationDecision decision = authorizationService.evaluate(AuthorizationRequest.builder() + .subject(subject).resource(resource).action(allAction).resourceContext(context).build()); + if (!decision.isAllowed()) { + decision = authorizationService.check(AuthorizationRequest.builder().subject(subject) + .resource(resource).action(ownAction).resourceContext(context).build()); + } + return new IntegrationAccess(subject.getTenantId(), subject.getUserId(), decision.getResolvedScope()); + } + + private void requireSystemTenant(SubjectContext subject) { + if (!StringUtils.hasText(systemTenant) || !systemTenant.equals(subject.getTenantId())) { + throw new AccessDeniedException("集成管理仅允许当前部署映射的租户"); + } + } +} diff --git a/src/main/java/com/finance/system/service/ApiAccessLogService.java b/src/main/java/com/finance/system/service/ApiAccessLogService.java index 3d9ea9b..ded8ece 100644 --- a/src/main/java/com/finance/system/service/ApiAccessLogService.java +++ b/src/main/java/com/finance/system/service/ApiAccessLogService.java @@ -1,7 +1,9 @@ package com.finance.system.service; import com.finance.system.entity.SysApiAccessLog; +import com.finance.system.observability.LogText; import com.finance.system.repository.SysApiAccessLogRepository; +import com.finance.system.audit.query.CursorPage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.PageRequest; @@ -9,8 +11,10 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import org.springframework.beans.factory.annotation.Value; import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -27,74 +31,148 @@ public class ApiAccessLogService { private static final int MAX_LIST = 500; private final SysApiAccessLogRepository repository; + @Value("${observability.tenant-id:default}") + private String compatibilityTenant; + @Value("${observability.organization-id:1}") + private Long compatibilityOrganization; @Async("apiAccessLogExecutor") @Transactional public void recordAsync(SysApiAccessLog entry) { try { + if (entry.getOrganizationId() == null || entry.getOrganizationId() <= 0) { + throw new IllegalArgumentException("ACCESS_LOG_ORGANIZATION_REQUIRED"); + } if (entry.getCreatedAt() == null) { - entry.setCreatedAt(LocalDateTime.now()); + entry.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC)); } repository.save(entry); - } catch (Exception e) { - log.warn("Failed to persist API access log: {} {}", entry.getHttpMethod(), entry.getRequestPath(), e); + } catch (Exception ignored) { + log.warn("接口访问日志保存失败 | 接口名称={} | 请求方式={} | 路由={} | 请求编号={} | 诊断=数据库保存失败", + LogText.apiOperation(entry.getHttpMethod(), entry.getRequestRoute()), + LogText.method(entry.getHttpMethod()), entry.getRequestRoute(), entry.getRequestId()); } } @Transactional(readOnly = true) - public List> list(String category, String operator, int limit) { + public List> list(String category, Long actorId, String operator, int limit) { + return list(safeTenant(compatibilityTenant), safeOrganization(compatibilityOrganization), + category, actorId, operator, limit); + } + + @Transactional(readOnly = true) + public List> list(String tenantId, Long organizationId, + String category, Long actorId, + String operator, int limit) { int pageSize = Math.max(1, Math.min(limit > 0 ? limit : 50, MAX_LIST)); List rows = repository.search( + safeTenant(tenantId), + safeOrganization(organizationId), StringUtils.hasText(category) ? category.trim() : null, + actorId, StringUtils.hasText(operator) ? operator.trim() : null, PageRequest.of(0, pageSize)); List> result = new ArrayList<>(rows.size()); for (SysApiAccessLog row : rows) { + requireBoundary(row, tenantId, organizationId); result.add(toView(row)); } return result; } + @Transactional(readOnly = true) + public CursorPage> cursor(String tenantId, Long organizationId, + String category, Long actorId, + String operator, String outcome, LocalDateTime cursorTime, Long cursorId, Integer requestedLimit) { + if ((cursorTime == null) != (cursorId == null)) + throw new IllegalArgumentException("cursorTime 与 cursorId 必须同时提供"); + int limit = requestedLimit == null ? 50 : Math.max(1, Math.min(requestedLimit, 100)); + List rows = repository.searchCursor(safeTenant(tenantId), + safeOrganization(organizationId), clean(category), actorId, + clean(operator), clean(outcome), cursorTime, cursorId, PageRequest.of(0, limit + 1)); + boolean more = rows.size() > limit; + List> items = new ArrayList<>(); + for (int i = 0; i < Math.min(limit, rows.size()); i++) { + SysApiAccessLog row = rows.get(i); + requireBoundary(row, tenantId, organizationId); + items.add(toView(row)); + } + SysApiAccessLog last = more && !items.isEmpty() ? rows.get(limit - 1) : null; + return CursorPage.>builder().items(items).hasMore(more) + .nextEventTime(last == null ? null : last.getCreatedAt()) + .nextId(last == null ? null : last.getId()).build(); + } + public static String categorize(String path) { String value = path == null ? "" : path.toLowerCase(Locale.ROOT); if (value.startsWith("/api/logs")) return "系统日志"; if (value.startsWith("/api/auth") || value.contains("/login") || value.contains("/callback")) return "认证登录"; - if (value.startsWith("/api/applications") || value.startsWith("/api/reim") || value.contains("/attachment")) return "报销申请"; - if (value.startsWith("/api/payments") || value.contains("/payment")) return "付款操作"; - if (value.contains("/finance") || value.contains("/receipt")) return "收单操作"; + if (value.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 "财务处理"; if (value.contains("/feishu/directory")) return "飞书通讯录"; if (value.startsWith("/api/feishu")) return "飞书集成"; if (value.contains("/integration") || value.contains("/kingdee")) return "配置管理"; if (value.contains("/group") || value.contains("/role") || value.contains("/permission") || value.contains("/users")) return "人员权限"; - if (value.contains("/expense-type") || value.contains("/payee") || value.contains("/source")) return "主数据"; + if (value.startsWith("/api/business-config") || value.contains("/expense-type") + || value.contains("/payee") || value.contains("/source")) return "业务配置"; if (value.contains("/scheduled")) return "自动任务"; return "接口访问"; } private Map toView(SysApiAccessLog row) { Map view = new LinkedHashMap<>(); - String action = row.getHttpMethod() + " " + row.getRequestPath(); - String detail = "状态 " + row.getStatusCode() - + " · 耗时 " + row.getDurationMs() + "ms" - + (StringUtils.hasText(row.getClientIp()) ? " · IP " + row.getClientIp() : "") - + (StringUtils.hasText(row.getQueryString()) ? " · " + row.getQueryString() : "") - + (StringUtils.hasText(row.getErrorMessage()) ? " · " + row.getErrorMessage() : ""); + String route = StringUtils.hasText(row.getRequestRoute()) ? row.getRequestRoute() : row.getRequestPath(); + String operation = LogText.apiOperation(row.getHttpMethod(), route); + String action = operation + "(" + row.getHttpMethod() + " " + route + ")"; + String detail = LogText.status(row.getStatusCode()) + + " · 执行结果:" + LogText.outcome(row.getOutcome()) + + " · 耗时:" + row.getDurationMs() + "毫秒" + + (StringUtils.hasText(row.getErrorCode()) ? " · " + LogText.error(row.getErrorCode()) : ""); view.put("id", row.getId()); view.put("requestId", row.getRequestId()); + view.put("clientRequestId", row.getClientRequestId()); + view.put("traceId", row.getTraceId()); view.put("operator", row.getOperatorName()); view.put("operatorId", row.getOperatorId()); + view.put("operation", operation); view.put("action", action); view.put("detail", detail); view.put("category", row.getCategory()); view.put("method", row.getHttpMethod()); + view.put("methodLabel", LogText.method(row.getHttpMethod())); view.put("path", row.getRequestPath()); - view.put("query", row.getQueryString()); + view.put("route", row.getRequestRoute()); view.put("statusCode", row.getStatusCode()); + view.put("statusLabel", LogText.status(row.getStatusCode())); view.put("durationMs", row.getDurationMs()); - view.put("clientIp", row.getClientIp()); - view.put("userAgent", row.getUserAgent()); - view.put("errorMessage", row.getErrorMessage()); + view.put("outcome", row.getOutcome()); + view.put("outcomeLabel", LogText.outcome(row.getOutcome())); + view.put("errorCode", row.getErrorCode()); + view.put("errorLabel", StringUtils.hasText(row.getErrorCode()) ? LogText.error(row.getErrorCode()) : ""); view.put("time", row.getCreatedAt() == null ? "" : TIME_FORMAT.format(row.getCreatedAt())); return view; } + + private String clean(String value) { return StringUtils.hasText(value) ? value.trim() : null; } + + private String safeTenant(String value) { + if (!StringUtils.hasText(value) || !value.matches("[A-Za-z0-9._-]{1,64}")) + throw new IllegalArgumentException("invalid tenant"); + return value; + } + + private Long safeOrganization(Long value) { + if (value == null || value <= 0) throw new IllegalArgumentException("invalid organization"); + return value; + } + + private void requireBoundary(SysApiAccessLog row, String tenantId, Long organizationId) { + if (row == null || !safeTenant(tenantId).equals(row.getTenantId()) + || !safeOrganization(organizationId).equals(row.getOrganizationId())) { + throw new org.springframework.security.access.AccessDeniedException("访问日志组织边界不匹配"); + } + } } diff --git a/src/main/java/com/finance/system/service/BankAccountPaymentSecretService.java b/src/main/java/com/finance/system/service/BankAccountPaymentSecretService.java new file mode 100644 index 0000000..a38922b --- /dev/null +++ b/src/main/java/com/finance/system/service/BankAccountPaymentSecretService.java @@ -0,0 +1,71 @@ +package com.finance.system.service; + +import com.finance.system.entity.ReimApplication; +import com.finance.system.entity.SysBankAccount; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.exception.UnauthorizedException; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.repository.ReimApplicationRepository; +import com.finance.system.repository.SysBankAccountRepository; +import com.finance.system.security.finance.BankAccountProtection; +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 java.util.Collections; + +/** Internal-only, authorized and audited access to a full account number for payment execution. */ +@Service +public class BankAccountPaymentSecretService { + private final ReimApplicationRepository applications; + private final SysBankAccountRepository accounts; + private final FinanceAuthorization authorization; + private final BankAccountProtection protection; + private final FinanceAuditEvents audit; + + public BankAccountPaymentSecretService(ReimApplicationRepository applications, + SysBankAccountRepository accounts, + FinanceAuthorization authorization, + BankAccountProtection protection, + FinanceAuditEvents audit) { + this.applications = applications; + this.accounts = accounts; + this.authorization = authorization; + this.protection = protection; + this.audit = audit; + } + + @Transactional + public String decryptForPaymentExecution(Long actorId, Long applicationId) { + if (actorId == null || !actorId.equals(AuditUtil.getCurrentUserId())) { + throw new UnauthorizedException("无权使用其他用户身份读取付款账号"); + } + ReimApplication application = applications.findById(applicationId) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + if (Boolean.TRUE.equals(application.getDeleted())) { + throw new ResourceNotFoundException("报销申请不存在"); + } + authorization.checkApplication(actorId, "finance.payment", "register", application); + if (!"APPROVED".equals(application.getApprovalStatus()) + || !"RECEIVED".equals(application.getReceiptStatus())) { + throw new BusinessException("报销申请尚未满足付款条件", 409); + } + if (application.getPayeeBankId() == null) { + throw new BusinessException("报销申请未指定收款账户", 409); + } + SysBankAccount account = accounts.findById(application.getPayeeBankId()) + .orElseThrow(() -> new ResourceNotFoundException("收款账户不存在")); + if (!"ACTIVE".equalsIgnoreCase(account.getStatus())) { + throw new BusinessException("收款账户已停用", 409); + } + if (account.getAccountNoCiphertext() == null) { + throw new BusinessException("收款账户尚未完成加密回填", 409); + } + String plaintext = protection.decryptForPaymentExecution(account.getAccountNoCiphertext()); + audit.business("finance.payment.bank-account.decrypt", actorId, "SYS_BANK_ACCOUNT", account.getId(), + "READ", null, Collections.singletonMap("applicationId", applicationId)); + return plaintext; + } +} diff --git a/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java b/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java index 4187458..04416e4 100644 --- a/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java +++ b/src/main/java/com/finance/system/service/IntegrationConfigCrypto.java @@ -2,9 +2,11 @@ package com.finance.system.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; +import javax.annotation.PostConstruct; import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; @@ -22,14 +24,25 @@ public class IntegrationConfigCrypto { private static final String CIPHER = "AES/GCM/NoPadding"; private static final int NONCE_BYTES = 12; private static final int TAG_BITS = 128; + private static final int MINIMUM_KEY_BYTES = 32; + private static final String REPOSITORY_DEVELOPMENT_DEFAULT_SHA256 = + "2cbd479c8d1a3bd8ac7433f51ca53593ee49c92193cda28efd14e3e62cd082e7"; private final String encryptionKey; + private final boolean localProfile; private final SecureRandom secureRandom = new SecureRandom(); @Autowired public IntegrationConfigCrypto( - @Value("${app.integration-encryption-key:${APP_INTEGRATION_ENCRYPTION_KEY:}}") String encryptionKey) { + @Value("${app.integration-encryption-key:${APP_INTEGRATION_ENCRYPTION_KEY:}}") String encryptionKey, + Environment environment) { this.encryptionKey = encryptionKey; + this.localProfile = hasLocalProfile(environment); + } + + @PostConstruct + void validateAtStartup() { + requireKey(); } public String encrypt(String plaintext) { @@ -91,7 +104,35 @@ public class IntegrationConfigCrypto { private void requireKey() { if (!StringUtils.hasText(encryptionKey)) { - throw new IllegalStateException("未配置 APP_INTEGRATION_ENCRYPTION_KEY,不能读写加密集成配置"); + throw new IllegalStateException("INTEGRATION_ENCRYPTION_KEY_REQUIRED"); + } + if (encryptionKey.getBytes(StandardCharsets.UTF_8).length < MINIMUM_KEY_BYTES) { + throw new IllegalStateException("INTEGRATION_ENCRYPTION_KEY_MUST_HAVE_32_BYTES"); + } + if (!localProfile && REPOSITORY_DEVELOPMENT_DEFAULT_SHA256.equals(sha256(encryptionKey))) { + throw new IllegalStateException("INTEGRATION_ENCRYPTION_DEVELOPMENT_KEY_FORBIDDEN"); + } + } + + private static boolean hasLocalProfile(Environment environment) { + if (environment == null) return false; + String[] activeProfiles = environment.getActiveProfiles(); + if (activeProfiles.length == 0) return false; + for (String profile : activeProfiles) { + if (!"local".equalsIgnoreCase(profile)) return false; + } + return true; + } + + private static String sha256(String value) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(64); + for (byte current : digest) result.append(String.format("%02x", current & 0xff)); + return result.toString(); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("INTEGRATION_ENCRYPTION_KEY_VALIDATION_FAILED", e); } } } diff --git a/src/main/java/com/finance/system/service/IntegrationConfigReader.java b/src/main/java/com/finance/system/service/IntegrationConfigReader.java index ff2c63f..6e1a8ca 100644 --- a/src/main/java/com/finance/system/service/IntegrationConfigReader.java +++ b/src/main/java/com/finance/system/service/IntegrationConfigReader.java @@ -4,6 +4,7 @@ import com.finance.system.adapter.feishu.FeishuConfig; import com.finance.system.adapter.kingdee.KingdeeConfig; import com.finance.system.entity.SysIntegrationConfig; import com.finance.system.repository.SysIntegrationConfigRepository; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @@ -13,18 +14,21 @@ import java.util.Map; import java.util.Optional; /** - * Feishu/Kingdee system credentials come from application.yml / env. - * Only the Feishu approval definition code may be overridden from - * {@code sys_integration_config} via 配置管理. + * Feishu runtime credentials come from application properties. Only the + * approval definition code may be overridden by tenant-scoped database data. */ @Component public class IntegrationConfigReader { /** Internal persistence key retained for compatibility with older callers. */ public static final String INTERNAL_ENABLED_KEY = "__enabled"; - + private static final String FEISHU = "FEISHU"; + private static final String KINGDEE = "KINGDEE"; + private static final String DEFAULT_TENANT = "default"; private final FeishuConfig feishuConfig; private final KingdeeConfig kingdeeConfig; private final SysIntegrationConfigRepository integrationConfigRepository; + @Value("${observability.tenant-id:default}") + private String systemTenantId = "default"; public IntegrationConfigReader( FeishuConfig feishuConfig, @@ -47,32 +51,33 @@ public class IntegrationConfigReader { result.put("syncOrgEnabled", String.valueOf(feishuConfig.isSyncOrgEnabled())); FeishuConfig.Approval approval = feishuConfig.getApproval(); if (approval != null) { - result.put("approvalCode", resolveApprovalCode(approval.getApprovalCode())); + result.put("approvalCode", resolveStoredCode(systemTenant(), "approvalCode", approval.getApprovalCode())); + result.put("travelApprovalCode", resolveStoredCode(systemTenant(), "travelApprovalCode", null)); result.put("verificationToken", approval.getVerificationToken()); result.put("encryptKey", approval.getEncryptKey()); } else { - result.put("approvalCode", resolveApprovalCode(null)); + result.put("approvalCode", resolveStoredCode(systemTenant(), "approvalCode", null)); + result.put("travelApprovalCode", resolveStoredCode(systemTenant(), "travelApprovalCode", null)); } - result.put(INTERNAL_ENABLED_KEY, String.valueOf(isEnabled("FEISHU"))); + result.put(INTERNAL_ENABLED_KEY, String.valueOf(isEnabled(FEISHU))); return result; } public String get(String provider, String key) { - String normalized = normalize(provider); - if ("FEISHU".equals(normalized) && "approvalCode".equals(key)) { - return resolveApprovalCode(environmentValue(normalized, key)); - } - return environmentValue(normalized, key); + return get(systemTenant(), provider, key); } - /** DB override wins when present; otherwise fall back to yml/env. */ - private String resolveApprovalCode(String envFallback) { - Optional stored = integrationConfigRepository - .findByProviderAndConfigKey("FEISHU", "approvalCode"); - if (stored.isPresent() && StringUtils.hasText(stored.get().getConfigValue())) { - return stored.get().getConfigValue().trim(); + public String get(String tenantId, String provider, String key) { + String tenant = requireTenant(tenantId); + String normalized = normalize(provider); + if (FEISHU.equals(normalized)) { + if ("enabled".equals(key) || INTERNAL_ENABLED_KEY.equals(key)) { + return String.valueOf(isEnabled(tenant, normalized)); + } + if ("approvalCode".equals(key) || "travelApprovalCode".equals(key)) + return resolveStoredCode(tenant, key, environmentValue(normalized, key)); } - return StringUtils.hasText(envFallback) ? envFallback.trim() : envFallback; + return environmentValue(normalized, key); } public boolean getBoolean(String provider, String key, boolean defaultValue) { @@ -81,9 +86,14 @@ public class IntegrationConfigReader { } public boolean isEnabled(String provider) { + return isEnabled(systemTenant(), provider); + } + + public boolean isEnabled(String tenantId, String provider) { + requireTenant(tenantId); String normalized = normalize(provider); - if ("KINGDEE".equals(normalized)) return kingdeeConfig.isEnabled(); - if ("FEISHU".equals(normalized)) { + if (KINGDEE.equals(normalized)) return kingdeeConfig.isEnabled(); + if (FEISHU.equals(normalized)) { return feishuConfig.isEnabled() && StringUtils.hasText(feishuConfig.getAppId()) && StringUtils.hasText(feishuConfig.getAppSecret()); @@ -91,19 +101,28 @@ public class IntegrationConfigReader { return false; } + private String resolveStoredCode(String tenantId, String key, String fallback) { + Optional stored = integrationConfigRepository + .findByTenantIdAndProviderAndConfigKey(tenantId, FEISHU, key); + if (stored.isPresent() && StringUtils.hasText(stored.get().getConfigValue())) + return stored.get().getConfigValue().trim(); + return StringUtils.hasText(fallback) ? fallback.trim() : fallback; + } + private String environmentValue(String provider, String key) { - if ("FEISHU".equals(provider)) { + if (FEISHU.equals(provider)) { if ("appId".equals(key)) return feishuConfig.getAppId(); if ("appSecret".equals(key)) return feishuConfig.getAppSecret(); if ("redirectUri".equals(key)) return feishuConfig.getRedirectUri(); if ("syncOrgEnabled".equals(key)) return String.valueOf(feishuConfig.isSyncOrgEnabled()); - if ("enabled".equals(key) || INTERNAL_ENABLED_KEY.equals(key)) return String.valueOf(isEnabled("FEISHU")); + if ("enabled".equals(key) || INTERNAL_ENABLED_KEY.equals(key)) + return String.valueOf(feishuConfig.isEnabled()); FeishuConfig.Approval approval = feishuConfig.getApproval(); if (approval == null) return null; if ("approvalCode".equals(key)) return approval.getApprovalCode(); if ("verificationToken".equals(key)) return approval.getVerificationToken(); if ("encryptKey".equals(key)) return approval.getEncryptKey(); - } else if ("KINGDEE".equals(provider)) { + } else if (KINGDEE.equals(provider)) { if ("enabled".equals(key) || INTERNAL_ENABLED_KEY.equals(key)) return String.valueOf(kingdeeConfig.isEnabled()); if ("baseUrl".equals(key)) return kingdeeConfig.getBaseUrl(); if ("clientId".equals(key)) return kingdeeConfig.getClientId(); @@ -116,4 +135,18 @@ public class IntegrationConfigReader { private String normalize(String provider) { return provider == null ? "" : provider.trim().toUpperCase(Locale.ROOT); } + + private String systemTenant() { + return validTenant(systemTenantId) ? systemTenantId.trim() : DEFAULT_TENANT; + } + + private String requireTenant(String tenantId) { + if (!validTenant(tenantId)) throw new IllegalArgumentException("INTEGRATION_TENANT_INVALID"); + return tenantId.trim(); + } + + private boolean validTenant(String tenantId) { + return StringUtils.hasText(tenantId) + && tenantId.trim().matches("[A-Za-z0-9._-]{1,64}"); + } } diff --git a/src/main/java/com/finance/system/service/IntegrationConfigService.java b/src/main/java/com/finance/system/service/IntegrationConfigService.java index 0f2ee08..7129e2b 100644 --- a/src/main/java/com/finance/system/service/IntegrationConfigService.java +++ b/src/main/java/com/finance/system/service/IntegrationConfigService.java @@ -4,6 +4,7 @@ import com.finance.system.adapter.feishu.FeishuAuthService; import com.finance.system.adapter.kingdee.KingdeeClient; import com.finance.system.entity.SysIntegrationConfig; import com.finance.system.exception.BadRequestException; +import com.finance.system.integration.audit.IntegrationAuditEvents; import com.finance.system.repository.SysIntegrationConfigRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -17,7 +18,7 @@ import java.net.URISyntaxException; import java.util.*; /** - * 配置管理仅开放飞书「审批定义编码」;飞书/金蝶系统凭证来自 application.yml。 + * 配置管理仅开放飞书「审批定义编码」;不扩大系统凭证的 UI 写入面。 */ @Service public class IntegrationConfigService { @@ -25,8 +26,10 @@ public class IntegrationConfigService { private static final String FEISHU = "FEISHU"; private static final String KINGDEE = "KINGDEE"; private static final String APPROVAL_CODE_KEY = "approvalCode"; + private static final String TRAVEL_APPROVAL_CODE_KEY = "travelApprovalCode"; private final SysIntegrationConfigRepository repository; + private final IntegrationAuditEvents auditEvents; private FeishuAuthService feishuAuthService; private KingdeeClient kingdeeClient; private IntegrationConfigReader integrationConfigReader; @@ -35,21 +38,26 @@ public class IntegrationConfigService { @Value("${kingdee.allowed-hosts:app.kingdee.com}") private String kingdeeAllowedHosts; - public IntegrationConfigService(SysIntegrationConfigRepository repository) { this.repository = repository; } + public IntegrationConfigService(SysIntegrationConfigRepository repository, IntegrationAuditEvents auditEvents) { + this.repository = repository; + this.auditEvents = auditEvents; + } @Autowired(required = false) public void setFeishuAuthService(FeishuAuthService value) { this.feishuAuthService = value; } @Autowired(required = false) public void setKingdeeClient(KingdeeClient value) { this.kingdeeClient = value; } @Autowired(required = false) public void setIntegrationConfigReader(IntegrationConfigReader value) { this.integrationConfigReader = value; } @Transactional(readOnly = true) - public Map view() { + public Map view(String tenantId) { + tenantId = tenant(tenantId); Map result = new LinkedHashMap<>(); - result.put("feishu", feishuApprovalView()); + result.put("feishu", feishuApprovalView(tenantId)); return result; } @Transactional(propagation = org.springframework.transaction.annotation.Propagation.REQUIRES_NEW, isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED, timeout = 30) - public void update(Map body) { + public void update(Map body, String tenantId, Long actorId) { + tenantId = tenant(tenantId); String provider = provider(body == null ? null : body.get("provider")); if (KINGDEE.equals(provider)) { throw new BadRequestException("金蝶系统账号由后端配置文件维护;员工账号请在「员工金蝶账号绑定」中维护"); @@ -58,42 +66,38 @@ public class IntegrationConfigService { ? Collections.emptyMap() : (Map) body.get("values"); if (values.isEmpty()) throw new BadRequestException("请填写审批定义编码"); for (Object rawKey : values.keySet()) { - if (!APPROVAL_CODE_KEY.equals(String.valueOf(rawKey))) { - throw new BadRequestException("配置管理仅支持保存审批定义编码"); + String key = String.valueOf(rawKey); + if (!APPROVAL_CODE_KEY.equals(key) && !TRAVEL_APPROVAL_CODE_KEY.equals(key)) { + throw new BadRequestException("配置管理仅支持保存飞书审批定义编码"); } } - Object raw = values.get(APPROVAL_CODE_KEY); - String approvalCode = raw == null ? "" : String.valueOf(raw).trim(); - if (!StringUtils.hasText(approvalCode)) { - throw new BadRequestException("审批定义编码不能为空"); + List changedKeys = new ArrayList<>(); + for (Map.Entry entry : values.entrySet()) { + String key = String.valueOf(entry.getKey()); + String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue()).trim(); + if (!StringUtils.hasText(value)) throw new BadRequestException("审批定义编码不能为空"); + if (value.length() > 200) throw new BadRequestException("审批定义编码过长"); + saveEditableCode(tenantId, key, value); + changedKeys.add(key); } - if (approvalCode.length() > 200) { - throw new BadRequestException("审批定义编码过长"); - } - SysIntegrationConfig config = repository.findByProviderAndConfigKey(FEISHU, APPROVAL_CODE_KEY) - .orElseGet(SysIntegrationConfig::new); - if (config.getId() != null) entityManager.refresh(config); - config.setProvider(FEISHU); - config.setConfigKey(APPROVAL_CODE_KEY); - config.setConfigValue(approvalCode); - config.setSecret(false); - config.setEnabled(true); - repository.saveAndFlush(config); - jdbc.update("DELETE FROM sys_integration_config WHERE provider = ? AND config_key = ?", - FEISHU, "syncApprovalEnabled"); + jdbc.update("DELETE FROM sys_integration_config WHERE tenant_id = ? AND provider = ? AND config_key = ?", + tenantId, FEISHU, "syncApprovalEnabled"); + auditEvents.configUpdated(tenantId, actorId, FEISHU, changedKeys); } - @Transactional(readOnly = true) - public Map test(String requestedProvider) { + @Transactional + public Map test(String requestedProvider, String tenantId, Long actorId) { + tenantId = tenant(tenantId); String provider = provider(requestedProvider); Map result = new LinkedHashMap<>(); result.put("provider", provider); - boolean configured = integrationConfigReader != null && integrationConfigReader.isEnabled(provider) - && hasRequiredConfiguration(provider); + boolean configured = integrationConfigReader != null && integrationConfigReader.isEnabled(tenantId, provider) + && hasRequiredConfiguration(provider, tenantId); result.put("configured", configured); if (!configured) { result.put("success", false); result.put("message", "集成未配置或未启用,未执行外部连接"); + auditEvents.configTested(tenantId, actorId, provider, "NOT_CONFIGURED"); return result; } try { @@ -101,65 +105,105 @@ public class IntegrationConfigService { feishuAuthService.getTenantAccessToken(); result.put("success", true); result.put("message", "连接测试成功"); + auditEvents.configTested(tenantId, actorId, provider, "SUCCESS"); return result; } if (KINGDEE.equals(provider) && kingdeeClient != null && kingdeeClient.isEnabled()) { kingdeeClient.login(); result.put("success", true); result.put("message", "连接测试成功"); + auditEvents.configTested(tenantId, actorId, provider, "SUCCESS"); return result; } } catch (Exception ignored) { result.put("success", false); result.put("message", "外部连接测试失败"); + auditEvents.configTested(tenantId, actorId, provider, "CONNECTION_FAILED"); return result; } result.put("success", false); result.put("message", "连接测试客户端未配置"); + auditEvents.configTested(tenantId, actorId, provider, "CLIENT_UNAVAILABLE"); return result; } - private Map feishuApprovalView() { - boolean enabled = integrationConfigReader != null && integrationConfigReader.isEnabled(FEISHU); + private Map feishuApprovalView(String tenantId) { + boolean enabled = integrationConfigReader != null && integrationConfigReader.isEnabled(tenantId, FEISHU); String approvalCode = integrationConfigReader == null - ? null : integrationConfigReader.get(FEISHU, APPROVAL_CODE_KEY); - boolean fromDb = repository.findByProviderAndConfigKey(FEISHU, APPROVAL_CODE_KEY) + ? null : integrationConfigReader.get(tenantId, FEISHU, APPROVAL_CODE_KEY); + boolean paymentCodeFromDb = repository.findByTenantIdAndProviderAndConfigKey( + tenantId, FEISHU, APPROVAL_CODE_KEY) .map(row -> StringUtils.hasText(row.getConfigValue())) .orElse(false); - Map field = new LinkedHashMap<>(); - field.put("key", APPROVAL_CODE_KEY); - field.put("label", "审批定义编码"); - field.put("inputType", "text"); - field.put("placeholder", "例如:8A0D2B3C-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); - field.put("helpText", "填写飞书审批管理后台目标审批定义的 approval_code;保存后点击「验证并同步飞书审批」拉取流程并订阅事件。"); - field.put("secret", false); - field.put("readOnly", false); - field.put("value", approvalCode == null ? "" : approvalCode); - field.put("configured", StringUtils.hasText(approvalCode)); + String travelApprovalCode = integrationConfigReader == null + ? null : integrationConfigReader.get(tenantId, FEISHU, TRAVEL_APPROVAL_CODE_KEY); + boolean travelCodeFromDb = repository.findByTenantIdAndProviderAndConfigKey( + tenantId, FEISHU, TRAVEL_APPROVAL_CODE_KEY) + .map(row -> StringUtils.hasText(row.getConfigValue())) + .orElse(false); + List> fields = new ArrayList<>(); + fields.add(codeField(APPROVAL_CODE_KEY, "付款审批定义编码", + "填写飞书审批管理后台付款审批定义的 approval_code;保存后可验证并同步流程。", approvalCode)); + fields.add(codeField(TRAVEL_APPROVAL_CODE_KEY, "出差审批定义编码", + "填写飞书出差申请审批定义的 approval_code;供后续只读同步任务使用。", travelApprovalCode)); Map result = new LinkedHashMap<>(); result.put("enabled", enabled); result.put("readOnly", false); - result.put("source", fromDb ? "database" : "application.yml"); - result.put("fields", Collections.singletonList(field)); + result.put("source", paymentCodeFromDb || travelCodeFromDb ? "database" : "application.yml"); + result.put("fields", fields); return result; } - private boolean hasRequiredConfiguration(String provider) { + private void saveEditableCode(String tenantId, String key, String value) { + SysIntegrationConfig config = repository.findByTenantIdAndProviderAndConfigKey( + tenantId, FEISHU, key).orElseGet(SysIntegrationConfig::new); + if (config.getId() != null) entityManager.refresh(config); + config.setTenantId(tenantId); + config.setProvider(FEISHU); + config.setConfigKey(key); + config.setConfigValue(value); + config.setSecret(false); + config.setEnabled(true); + repository.saveAndFlush(config); + } + + private Map codeField(String key, String label, String helpText, String value) { + Map field = new LinkedHashMap<>(); + field.put("key", key); + field.put("label", label); + field.put("inputType", "text"); + field.put("placeholder", "例如:8A0D2B3C-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); + field.put("helpText", helpText); + field.put("secret", false); + field.put("readOnly", false); + field.put("value", value == null ? "" : value); + field.put("configured", StringUtils.hasText(value)); + return field; + } + + private boolean hasRequiredConfiguration(String provider, String tenantId) { if (integrationConfigReader == null) return false; if (FEISHU.equals(provider)) { - return present(integrationConfigReader.get(provider, "appId")) - && present(integrationConfigReader.get(provider, "appSecret")); + return present(integrationConfigReader.get(tenantId, provider, "appId")) + && present(integrationConfigReader.get(tenantId, provider, "appSecret")); } - return safeKingdeeUrl(integrationConfigReader.get(provider, "baseUrl")) - && present(integrationConfigReader.get(provider, "clientId")) - && present(integrationConfigReader.get(provider, "clientSecret")) - && present(integrationConfigReader.get(provider, "dbId")); + return safeKingdeeUrl(integrationConfigReader.get(tenantId, provider, "baseUrl")) + && present(integrationConfigReader.get(tenantId, provider, "clientId")) + && present(integrationConfigReader.get(tenantId, provider, "clientSecret")) + && present(integrationConfigReader.get(tenantId, provider, "dbId")); } private boolean present(String value) { return StringUtils.hasText(value); } + private String tenant(String value) { + if (!StringUtils.hasText(value) || !value.matches("[A-Za-z0-9._-]{1,64}")) { + throw new BadRequestException("tenant 边界无效"); + } + return value; + } + private String provider(Object value) { String result = value == null ? "" : String.valueOf(value).trim().toUpperCase(Locale.ROOT); if (!FEISHU.equals(result) && !KINGDEE.equals(result)) { diff --git a/src/main/java/com/finance/system/service/KingdeeAccountBindingService.java b/src/main/java/com/finance/system/service/KingdeeAccountBindingService.java index 77ab951..fa0a693 100644 --- a/src/main/java/com/finance/system/service/KingdeeAccountBindingService.java +++ b/src/main/java/com/finance/system/service/KingdeeAccountBindingService.java @@ -7,6 +7,8 @@ import com.finance.system.exception.BadRequestException; import com.finance.system.exception.BusinessException; import com.finance.system.repository.SysUserKingdeeAccountRepository; import com.finance.system.repository.SysUserRepository; +import com.finance.system.integration.audit.IntegrationAuditEvents; +import com.finance.system.security.integration.IntegrationAccess; import org.springframework.context.annotation.Lazy; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.access.AccessDeniedException; @@ -38,7 +40,7 @@ public class KingdeeAccountBindingService { private final IntegrationConfigCrypto crypto; private final KingdeeClient kingdeeClient; private final JdbcTemplate jdbc; - private final RoleService roleService; + private final IntegrationAuditEvents auditEvents; public KingdeeAccountBindingService( SysUserKingdeeAccountRepository bindingRepository, @@ -46,69 +48,75 @@ public class KingdeeAccountBindingService { IntegrationConfigCrypto crypto, @Lazy KingdeeClient kingdeeClient, JdbcTemplate jdbc, - RoleService roleService) { + IntegrationAuditEvents auditEvents) { this.bindingRepository = bindingRepository; this.userRepository = userRepository; this.crypto = crypto; this.kingdeeClient = kingdeeClient; this.jdbc = jdbc; - this.roleService = roleService; + this.auditEvents = auditEvents; } @Transactional(readOnly = true) - public List> listBindings(Long actorId) { - if (actorId == null) throw new AccessDeniedException("未登录"); - boolean viewAll = roleService.hasPermission(actorId, VIEW_ALL); - boolean viewOwn = roleService.hasPermission(actorId, VIEW_OWN) - || roleService.hasPermission(actorId, "page.kingdee-account-binding"); - if (!viewAll && !viewOwn) throw new AccessDeniedException("无权查看金蝶账号绑定"); - - Set eligibleIds = eligibleUserIds(); - Map byUser = bindingRepository.findAll().stream() - .collect(Collectors.toMap(SysUserKingdeeAccount::getUserId, x -> x, (a, b) -> a)); - return userRepository.findAll().stream() + public List> listBindings(IntegrationAccess access) { + Set eligibleIds = eligibleUserIds(access.getTenantId()); + return userRepository.findByTenantId(access.getTenantId()).stream() .filter(user -> eligibleIds.contains(user.getId())) - .filter(user -> viewAll || Objects.equals(user.getId(), actorId)) + .filter(user -> userRepository.countActiveDirectoryEmployee(user.getFeishuOpenId()) > 0) + .filter(user -> access.isAll() || Objects.equals(user.getId(), access.getActorId())) .sorted(Comparator.comparing(SysUser::getRealName, Comparator.nullsLast(String::compareToIgnoreCase))) - .map(user -> toView(user, byUser.get(user.getId()))) + .map(user -> toView(user, bindingFor(user, access.getTenantId()).orElse(null))) .collect(Collectors.toList()); } @Transactional(readOnly = true) - public Map myBinding(Long userId) { - SysUser user = userRepository.findById(userId) + public Map myBinding(IntegrationAccess access) { + Long userId = access.getActorId(); + SysUser user = userRepository.findByIdAndTenantId(userId, access.getTenantId()) .orElseThrow(() -> new BadRequestException("用户不存在")); - return toView(user, bindingRepository.findById(userId).orElse(null)); + if (userRepository.countActiveDirectoryEmployee(user.getFeishuOpenId()) == 0) { + throw new BadRequestException("仅可为在职通讯录员工绑定金蝶账号"); + } + return toView(user, bindingFor(user, access.getTenantId()).orElse(null)); } @Transactional(readOnly = true) - public boolean isBound(Long userId) { - return userId != null && bindingRepository.existsByUserId(userId); + public boolean isBound(Long userId, String trustedTenantId) { + if (userId == null || !StringUtils.hasText(trustedTenantId)) return false; + return userRepository.findByIdAndTenantId(userId, trustedTenantId) + .map(user -> bindingFor(user, trustedTenantId).isPresent()).orElse(false); } @Transactional(readOnly = true) - public KingdeeCredentials requireCredentials(Long userId) { + public KingdeeCredentials requireCredentials(Long userId, String trustedTenantId) { if (userId == null) throw new BusinessException("未登录,无法使用员工金蝶账号"); - SysUserKingdeeAccount binding = bindingRepository.findById(userId) + if (!StringUtils.hasText(trustedTenantId)) throw new BusinessException("无效的租户边界", 403); + SysUser user = userRepository.findByIdAndTenantId(userId, trustedTenantId) + .orElseThrow(() -> new BusinessException("当前用户不存在", 404)); + SysUserKingdeeAccount binding = bindingFor(user, trustedTenantId) .orElseThrow(() -> new BusinessException("请先在「配置管理 · 金蝶账号绑定」中绑定金蝶账号后,再变更金蝶云星空财务单据")); return new KingdeeCredentials(binding.getKingdeeUsername(), crypto.decrypt(binding.getKingdeePassword())); } @Transactional - public Map bind(Long userId, String username, String password, Long operatorId, boolean verifyLogin) { - assertCanMutate(operatorId, userId, BIND_ALL, BIND_OWN, "绑定"); + public Map bind(Long userId, String username, String password, + IntegrationAccess access, boolean verifyLogin) { + assertCanMutate(access, userId, "绑定"); if (userId == null) throw new BadRequestException("用户不能为空"); - SysUser user = userRepository.findById(userId) + SysUser user = userRepository.findByIdAndTenantId(userId, access.getTenantId()) .orElseThrow(() -> new BadRequestException("用户不存在")); - if (!eligibleUserIds().contains(userId)) { + if (userRepository.countActiveDirectoryEmployee(user.getFeishuOpenId()) == 0) { + throw new BadRequestException("仅可为在职通讯录员工绑定金蝶账号"); + } + if (!eligibleUserIds(access.getTenantId()).contains(userId)) { throw new BadRequestException("仅可为财务角色,或已授予「变更金蝶财务单据」权限的人员绑定金蝶账号"); } String normalizedUser = normalizeUsername(username); if (!StringUtils.hasText(password)) throw new BadRequestException("金蝶密码不能为空"); crypto.assertConfigured(); - bindingRepository.findByKingdeeUsername(normalizedUser).ifPresent(existing -> { - if (!Objects.equals(existing.getUserId(), userId)) { + bindingRepository.findByTenantIdAndKingdeeUsername(access.getTenantId(), normalizedUser).ifPresent(existing -> { + if (!Objects.equals(bindingOpenId(existing), user.getFeishuOpenId())) { throw new BadRequestException("该金蝶账号已绑定到其他员工"); } }); @@ -117,79 +125,102 @@ public class KingdeeAccountBindingService { kingdeeClient.validateUserCredentials(normalizedUser, password); } - SysUserKingdeeAccount binding = bindingRepository.findById(userId).orElseGet(SysUserKingdeeAccount::new); + SysUserKingdeeAccount binding = bindingFor(user, access.getTenantId()) + .orElseGet(SysUserKingdeeAccount::new); binding.setUserId(userId); + binding.setEmployeeOpenId(user.getFeishuOpenId()); + binding.setTenantId(access.getTenantId()); binding.setKingdeeUsername(normalizedUser); binding.setKingdeePassword(crypto.encrypt(password.trim())); - binding.setBoundBy(operatorId); + binding.setBoundBy(access.getActorId()); if (binding.getBoundAt() == null) binding.setBoundAt(LocalDateTime.now()); bindingRepository.save(binding); + auditEvents.management(access.getTenantId(), access.getActorId(), + "integration.kingdee.account.bind", "KINGDEE_ACCOUNT_BINDING", userId, + "BOUND", Collections.singletonList("bindingStatus")); return toView(user, binding); } @Transactional - public void unbind(Long userId, Long operatorId) { - assertCanMutate(operatorId, userId, UNBIND_ALL, UNBIND_OWN, "解绑"); - if (userId == null || !bindingRepository.existsByUserId(userId)) { + public void unbind(Long userId, IntegrationAccess access) { + assertCanMutate(access, userId, "解绑"); + SysUser user = userRepository.findByIdAndTenantId(userId, access.getTenantId()).orElse(null); + if (user == null) throw new BadRequestException("用户不存在"); + SysUserKingdeeAccount binding = bindingFor(user, access.getTenantId()).orElse(null); + if (binding == null) { throw new BadRequestException("该员工尚未绑定金蝶账号"); } - bindingRepository.deleteById(userId); + bindingRepository.delete(binding); + auditEvents.management(access.getTenantId(), access.getActorId(), + "integration.kingdee.account.unbind", "KINGDEE_ACCOUNT_BINDING", userId, + "UNBOUND", Collections.singletonList("bindingStatus")); } - @Transactional(readOnly = true) - public Map testBinding(Long userId, Long operatorId) { - assertCanMutate(operatorId, userId, BIND_ALL, BIND_OWN, "验证"); - KingdeeCredentials credentials = requireCredentials(userId); - kingdeeClient.validateUserCredentials(credentials.getUsername(), credentials.getPassword()); + @Transactional + public Map testBinding(Long userId, IntegrationAccess access) { + assertCanMutate(access, userId, "验证"); + KingdeeCredentials credentials = requireCredentials(userId, access.getTenantId()); + try { + kingdeeClient.validateUserCredentials(credentials.getUsername(), credentials.getPassword()); + } catch (RuntimeException failure) { + auditEvents.failed(access.getTenantId(), access.getActorId(), + "integration.kingdee.account.test", "KINGDEE_ACCOUNT_BINDING", userId, + "LOGIN_FAILED"); + Map result = new LinkedHashMap<>(); + result.put("success", false); + result.put("resultCode", "LOGIN_FAILED"); + result.put("message", "金蝶账号验证失败"); + return result; + } + auditEvents.management(access.getTenantId(), access.getActorId(), + "integration.kingdee.account.test", "KINGDEE_ACCOUNT_BINDING", userId, + "SUCCESS", Collections.emptyList()); Map result = new LinkedHashMap<>(); result.put("success", true); + result.put("resultCode", "SUCCESS"); result.put("message", "金蝶账号验证成功"); return result; } - private void assertCanMutate(Long operatorId, Long targetUserId, String allCode, String ownCode, String action) { - if (operatorId == null) throw new AccessDeniedException("未登录"); - boolean canAll = roleService.hasEditPermission(operatorId, allCode); - boolean canOwn = roleService.hasEditPermission(operatorId, ownCode); - if (!canAll && !canOwn) throw new AccessDeniedException("无权" + action + "金蝶账号"); - if (!canAll && !Objects.equals(operatorId, targetUserId)) { + private void assertCanMutate(IntegrationAccess access, Long targetUserId, String action) { + if (access == null || access.getActorId() == null) throw new AccessDeniedException("未登录"); + if (!access.isAll() && !Objects.equals(access.getActorId(), targetUserId)) { throw new AccessDeniedException("当前权限仅可" + action + "本人的金蝶账号"); } } /** FINANCE role ∪ document.write EDIT holders ∪ already bound. */ - private Set eligibleUserIds() { + private Set eligibleUserIds(String tenantId) { List ids = jdbc.queryForList( "SELECT DISTINCT m.user_id " + "FROM sys_user_group_member m " + + "JOIN sys_user u ON u.id=m.user_id AND u.tenant_id=? " + "JOIN sys_user_group_role gr ON gr.group_id = m.group_id " + "JOIN sys_role r ON r.id = gr.role_id " + "WHERE r.role_code = 'FINANCE' " + "UNION " + "SELECT DISTINCT m.user_id " + "FROM sys_user_group_member m " + + "JOIN sys_user u ON u.id=m.user_id AND u.tenant_id=? " + "JOIN sys_user_group_role gr ON gr.group_id = m.group_id " + "JOIN sys_role_permission rp ON rp.role_id = gr.role_id " + "JOIN sys_permission p ON p.id = rp.permission_id " + "WHERE p.permission_code = ? AND rp.access_level = 'EDIT' " + "UNION " - + "SELECT user_id FROM sys_user_kingdee_account", + + "SELECT user_id FROM sys_user_kingdee_account WHERE tenant_id=?", Long.class, - DOCUMENT_WRITE); + tenantId, tenantId, DOCUMENT_WRITE, tenantId); return new LinkedHashSet<>(ids); } private Map toView(SysUser user, SysUserKingdeeAccount binding) { Map view = new LinkedHashMap<>(); - view.put("userId", user.getId()); + view.put("employeeOpenId", user.getFeishuOpenId()); view.put("realName", user.getRealName()); - view.put("employeeNo", user.getEmployeeNo()); - view.put("status", user.getStatus()); view.put("bound", binding != null); view.put("kingdeeUsername", binding == null ? null : binding.getKingdeeUsername()); view.put("boundAt", binding == null ? null : binding.getBoundAt()); view.put("updatedAt", binding == null ? null : binding.getUpdatedAt()); - view.put("boundBy", binding == null ? null : binding.getBoundBy()); return view; } @@ -200,6 +231,27 @@ public class KingdeeAccountBindingService { return value; } + public Long resolveEmployeeId(String openId, IntegrationAccess access) { + if (!StringUtils.hasText(openId)) throw new BadRequestException("员工OpenID不能为空"); + SysUser user = userRepository.findByFeishuOpenId(openId); + if (user == null || !Objects.equals(user.getTenantId(), access.getTenantId())) { + throw new BadRequestException("用户不存在"); + } + return user.getId(); + } + + private Optional bindingFor(SysUser user, String tenantId) { + if (!StringUtils.hasText(user.getFeishuOpenId())) return Optional.empty(); + Optional canonical = bindingRepository.findByEmployeeOpenIdAndTenantId(user.getFeishuOpenId(), tenantId); + return canonical.isPresent() ? canonical : bindingRepository.findByUserIdAndTenantId(user.getId(), tenantId) + .filter(binding -> !StringUtils.hasText(binding.getEmployeeOpenId())); + } + + private String bindingOpenId(SysUserKingdeeAccount binding) { + if (StringUtils.hasText(binding.getEmployeeOpenId())) return binding.getEmployeeOpenId(); + return userRepository.findById(binding.getUserId()).map(SysUser::getFeishuOpenId).orElse(null); + } + @lombok.Value public static class KingdeeCredentials { String username; diff --git a/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java b/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java index 9cd0b15..33b0ed1 100644 --- a/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java +++ b/src/main/java/com/finance/system/service/KingdeeAsyncSyncService.java @@ -10,6 +10,7 @@ import com.finance.system.repository.SysKingdeeSyncConfigRepository; import com.finance.system.repository.SysKingdeeSyncFieldRepository; import com.finance.system.repository.SysKingdeeSyncFilterRepository; import com.finance.system.repository.SysKingdeeSyncRunRepository; +import com.finance.system.integration.audit.IntegrationAuditEvents; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @@ -46,6 +47,7 @@ public class KingdeeAsyncSyncService { private final ThreadPoolTaskScheduler heartbeatScheduler; private final ThreadPoolTaskScheduler deadlineScheduler; private final TransactionTemplate transaction; + private final IntegrationAuditEvents auditEvents; public KingdeeAsyncSyncService(SysKingdeeSyncConfigRepository configRepository, SysKingdeeSyncFieldRepository fieldRepository, @@ -57,7 +59,8 @@ public class KingdeeAsyncSyncService { @Qualifier("kingdeeSyncExecutor") ThreadPoolTaskExecutor executor, @Qualifier("kingdeeSyncHeartbeatScheduler") ThreadPoolTaskScheduler heartbeatScheduler, @Qualifier("kingdeeSyncDeadlineScheduler") ThreadPoolTaskScheduler deadlineScheduler, - PlatformTransactionManager transactionManager) { + PlatformTransactionManager transactionManager, + IntegrationAuditEvents auditEvents) { this.configRepository = configRepository; this.fieldRepository = fieldRepository; this.filterRepository = filterRepository; @@ -68,14 +71,15 @@ public class KingdeeAsyncSyncService { this.executor = executor; this.heartbeatScheduler = heartbeatScheduler; this.deadlineScheduler = deadlineScheduler; + this.auditEvents = auditEvents; this.transaction = new TransactionTemplate(transactionManager); this.transaction.setTimeout(30); } - public Map start(Long configId) { + public Map start(Long configId, String tenantId, Long actorId) { final ReservedWork work; try { - work = transaction.execute(status -> reserve(configId)); + work = transaction.execute(status -> reserve(configId, tenantId, actorId)); } catch (DataIntegrityViolationException e) { throw new BusinessException("该同步规则已有任务正在运行", 409); } @@ -116,12 +120,13 @@ public class KingdeeAsyncSyncService { return runMap(work.run); } - private ReservedWork reserve(Long configId) { + private ReservedWork reserve(Long configId, String tenantId, Long actorId) { if (configId == null) throw new ResourceNotFoundException("金蝶同步配置不存在"); - SysKingdeeSyncConfig config = configRepository.findByIdForUpdate(configId) + SysKingdeeSyncConfig config = configRepository.findByIdAndTenantIdForUpdate(configId, tenantId) .orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + configId)); SysKingdeeSyncRun active = runRepository - .findFirstByConfigIdAndStatusOrderByStartedAtDesc(configId, "RUNNING").orElse(null); + .findFirstByTenantIdAndConfigIdAndStatusOrderByStartedAtDesc( + tenantId, configId, "RUNNING").orElse(null); if (active != null && runRepository.failExpiredRun(active.getId(), KingdeeSyncRunStateService.TIMEOUT_MESSAGE) == 1) active = null; if (active != null) throw new BusinessException("该同步规则已有任务正在运行", 409); @@ -132,7 +137,8 @@ public class KingdeeAsyncSyncService { String filterString = documentSyncService.compileFilter(filters); LocalDateTime now = runRepository.currentDatabaseTime(); String token = UUID.randomUUID().toString(); - SysKingdeeSyncRun run = SysKingdeeSyncRun.builder().configId(configId).status("RUNNING") + SysKingdeeSyncRun run = SysKingdeeSyncRun.builder().tenantId(tenantId).configId(configId) + .initiatedBy(actorId).status("RUNNING") .filterString(filterString).fetchedCount(0).insertedCount(0).updatedCount(0).failedCount(0) .startedAt(now).executionToken(token).heartbeatAt(now) .leaseUntil(now.plus(KingdeeFencedRowWriteService.LEASE_DURATION)).build(); @@ -145,8 +151,14 @@ public class KingdeeAsyncSyncService { KingdeeDocumentSyncService.ExecutionResult result = documentSyncService.execute( work.aggregate, work.run.getId(), work.run.getExecutionToken()); stateService.finish(work.run.getId(), work.run.getExecutionToken(), result); + auditEvents.management(work.run.getTenantId(), work.run.getInitiatedBy(), + "integration.kingdee.sync.result", "KINGDEE_SYNC_RUN", work.run.getId(), + "COMPLETED", java.util.Collections.emptyList()); } catch (RuntimeException e) { stateService.fail(work.run.getId(), work.run.getExecutionToken(), "同步处理失败"); + auditEvents.failed(work.run.getTenantId(), work.run.getInitiatedBy(), + "integration.kingdee.sync.result", "KINGDEE_SYNC_RUN", work.run.getId(), + "SYNC_FAILED"); } finally { if (work.heartbeat != null) work.heartbeat.cancel(false); if (work.deadlineTask != null) work.deadlineTask.cancel(false); @@ -156,9 +168,9 @@ public class KingdeeAsyncSyncService { private Map runMap(SysKingdeeSyncRun run) { Map result = new LinkedHashMap<>(); result.put("id", run.getId()); result.put("configId", run.getConfigId()); result.put("status", run.getStatus()); - result.put("filterString", run.getFilterString()); result.put("fetchedCount", run.getFetchedCount()); + result.put("fetchedCount", run.getFetchedCount()); result.put("insertedCount", run.getInsertedCount()); result.put("updatedCount", run.getUpdatedCount()); - result.put("failedCount", run.getFailedCount()); result.put("errorMessage", run.getErrorMessage()); + result.put("failedCount", run.getFailedCount()); result.put("startedAt", run.getStartedAt()); result.put("finishedAt", run.getFinishedAt()); result.put("heartbeatAt", run.getHeartbeatAt()); result.put("leaseUntil", run.getLeaseUntil()); return result; diff --git a/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java b/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java index 0da46df..efb10e3 100644 --- a/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java +++ b/src/main/java/com/finance/system/service/KingdeeSyncConfigService.java @@ -11,6 +11,7 @@ import com.finance.system.repository.SysKingdeeSyncConfigRepository; import com.finance.system.repository.SysKingdeeSyncFieldRepository; import com.finance.system.repository.SysKingdeeSyncFilterRepository; import com.finance.system.repository.SysKingdeeSyncRunRepository; +import com.finance.system.integration.audit.IntegrationAuditEvents; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -44,18 +45,21 @@ public class KingdeeSyncConfigService { private final SysKingdeeSyncFilterRepository filterRepository; private final SysKingdeeSyncRunRepository runRepository; private final KingdeeDocumentSyncService documentSyncService; + private final IntegrationAuditEvents auditEvents; private KingdeeAsyncSyncService asyncSyncService; public KingdeeSyncConfigService(SysKingdeeSyncConfigRepository configRepository, SysKingdeeSyncFieldRepository fieldRepository, SysKingdeeSyncFilterRepository filterRepository, SysKingdeeSyncRunRepository runRepository, - KingdeeDocumentSyncService documentSyncService) { + KingdeeDocumentSyncService documentSyncService, + IntegrationAuditEvents auditEvents) { this.configRepository = configRepository; this.fieldRepository = fieldRepository; this.filterRepository = filterRepository; this.runRepository = runRepository; this.documentSyncService = documentSyncService; + this.auditEvents = auditEvents; } @Autowired @@ -64,25 +68,31 @@ public class KingdeeSyncConfigService { } @Transactional(readOnly = true) - public List> list() { + public List> list(String tenantId) { List> result = new ArrayList<>(); - for (SysKingdeeSyncConfig config : configRepository.findAll()) result.add(toMap(config, true)); + for (SysKingdeeSyncConfig config : configRepository.findByTenantIdOrderByIdAsc(tenant(tenantId))) + result.add(toMap(config, true)); return result; } @Transactional(readOnly = true) - public Map get(Long id) { - return toMap(load(id), true); + public Map get(Long id, String tenantId) { + return toMap(load(id, tenant(tenantId)), true); } @Transactional - public Map create(ConfigRequest request) { - validate(request, null); + public Map create(ConfigRequest request, String tenantId, Long actorId) { + String tenant = tenant(tenantId); + validate(request, null, tenant); SysKingdeeSyncConfig config = new SysKingdeeSyncConfig(); + config.setTenantId(tenant); copyConfig(request, config); try { config = configRepository.saveAndFlush(config); replaceChildren(config.getId(), request); + auditEvents.management(tenant, actorId, "integration.kingdee.sync-config.create", + "KINGDEE_SYNC_CONFIG", config.getId(), "CREATED", + Arrays.asList("configName", "formId", "targetTableName", "enabled", "maxRowsPerRun")); return toMap(config, true); } catch (DataIntegrityViolationException e) { throw new BusinessException("目标表名已被使用", 409); @@ -90,14 +100,18 @@ public class KingdeeSyncConfigService { } @Transactional - public Map update(Long id, ConfigRequest request) { - validate(request, id); - SysKingdeeSyncConfig config = loadForUpdate(id); - rejectActiveRun(id, "同步任务正在运行,不能修改配置"); + public Map update(Long id, ConfigRequest request, String tenantId, Long actorId) { + String tenant = tenant(tenantId); + validate(request, id, tenant); + SysKingdeeSyncConfig config = loadForUpdate(id, tenant); + rejectActiveRun(id, tenant, "同步任务正在运行,不能修改配置"); copyConfig(request, config); try { configRepository.saveAndFlush(config); replaceChildren(id, request); + auditEvents.management(tenant, actorId, "integration.kingdee.sync-config.update", + "KINGDEE_SYNC_CONFIG", id, "UPDATED", + Arrays.asList("configName", "formId", "targetTableName", "enabled", "maxRowsPerRun")); return toMap(config, true); } catch (DataIntegrityViolationException e) { throw new BusinessException("目标表名已被使用", 409); @@ -105,43 +119,53 @@ public class KingdeeSyncConfigService { } @Transactional - public void delete(Long id) { - SysKingdeeSyncConfig config = loadForUpdate(id); - rejectActiveRun(id, "同步任务正在运行,不能删除配置"); + public void delete(Long id, String tenantId, Long actorId) { + String tenant = tenant(tenantId); + SysKingdeeSyncConfig config = loadForUpdate(id, tenant); + rejectActiveRun(id, tenant, "同步任务正在运行,不能删除配置"); runRepository.deleteByConfigId(config.getId()); fieldRepository.deleteByConfigId(config.getId()); filterRepository.deleteByConfigId(config.getId()); configRepository.delete(config); + auditEvents.management(tenant, actorId, "integration.kingdee.sync-config.delete", + "KINGDEE_SYNC_CONFIG", id, "DELETED", Collections.emptyList()); } - public Map preview(Long id) { - return documentSyncService.preview(loadAggregate(id)); + public Map preview(Long id, String tenantId) { + return documentSyncService.preview(loadAggregate(id, tenant(tenantId), false)); } @Transactional - public Map prepareTable(Long id) { - Aggregate aggregate = loadAggregate(id, true); - rejectActiveRun(id, "同步任务正在运行,不能准备目标表"); + public Map prepareTable(Long id, String tenantId) { + String tenant = tenant(tenantId); + Aggregate aggregate = loadAggregate(id, tenant, true); + rejectActiveRun(id, tenant, "同步任务正在运行,不能准备目标表"); return documentSyncService.prepareTable(aggregate); } - public Map sync(Long id) { + public Map sync(Long id, String tenantId, Long actorId) { + String tenant = tenant(tenantId); if (asyncSyncService == null) throw new IllegalStateException("金蝶异步同步服务未初始化"); - return asyncSyncService.start(id); + Map result = asyncSyncService.start(id, tenant, actorId); + auditEvents.management(tenant, actorId, "integration.kingdee.sync.trigger", + "KINGDEE_SYNC_CONFIG", id, "QUEUED", Collections.emptyList()); + return result; } @Transactional(readOnly = true) - public List> runs(Long id) { - load(id); + public List> runs(Long id, String tenantId) { + String tenant = tenant(tenantId); + load(id, tenant); List> result = new ArrayList<>(); - for (SysKingdeeSyncRun run : runRepository.findTop100ByConfigIdOrderByStartedAtDescIdDesc(id)) result.add(runMap(run)); + for (SysKingdeeSyncRun run : runRepository + .findTop100ByTenantIdAndConfigIdOrderByStartedAtDescIdDesc(tenant, id)) result.add(runMap(run)); return result; } /** Exposed for focused unit tests and for callers that validate before persistence. */ - public void validate(ConfigRequest request) { validate(request, null); } + public void validate(ConfigRequest request) { validate(request, null, "default"); } - private void validate(ConfigRequest request, Long id) { + private void validate(ConfigRequest request, Long id, String tenantId) { if (request == null) throw new BadRequestException("请求体不能为空"); required(request.configName, "configName", 200); text(request.formId, "formId", 120); @@ -156,7 +180,8 @@ public class KingdeeSyncConfigService { throw new BadRequestException("targetTableComment 长度不能超过500"); if (request.maxRowsPerRun != null && (request.maxRowsPerRun < 1 || request.maxRowsPerRun > 100000)) throw new BadRequestException("maxRowsPerRun 必须在1到100000之间"); - if (configRepository.existsByTargetTableNameAndIdNot(table, id == null ? -1L : id)) + if (configRepository.existsByTenantIdAndTargetTableNameAndIdNot( + tenantId, table, id == null ? -1L : id)) throw new BusinessException("目标表名已被使用", 409); if (request.fields == null || request.fields.isEmpty()) throw new BadRequestException("至少配置一个同步字段"); @@ -238,27 +263,27 @@ public class KingdeeSyncConfigService { filterRepository.saveAll(filters); } - private Aggregate loadAggregate(Long id) { return loadAggregate(id, false); } - - private Aggregate loadAggregate(Long id, boolean forUpdate) { - SysKingdeeSyncConfig config = forUpdate ? loadForUpdate(id) : load(id); + private Aggregate loadAggregate(Long id, String tenantId, boolean forUpdate) { + SysKingdeeSyncConfig config = forUpdate ? loadForUpdate(id, tenantId) : load(id, tenantId); return new Aggregate(config, fieldRepository.findByConfigIdOrderBySortOrderAscIdAsc(id), filterRepository.findByConfigIdOrderBySortOrderAscIdAsc(id)); } - private SysKingdeeSyncConfig load(Long id) { + private SysKingdeeSyncConfig load(Long id, String tenantId) { if (id == null) throw new ResourceNotFoundException("金蝶同步配置不存在"); - return configRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + id)); - } - - private SysKingdeeSyncConfig loadForUpdate(Long id) { - if (id == null) throw new ResourceNotFoundException("金蝶同步配置不存在"); - return configRepository.findByIdForUpdate(id) + return configRepository.findByIdAndTenantId(id, tenantId) .orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + id)); } - private void rejectActiveRun(Long id, String message) { - if (runRepository.findFirstByConfigIdAndStatusOrderByStartedAtDesc(id, "RUNNING").isPresent()) + private SysKingdeeSyncConfig loadForUpdate(Long id, String tenantId) { + if (id == null) throw new ResourceNotFoundException("金蝶同步配置不存在"); + return configRepository.findByIdAndTenantIdForUpdate(id, tenantId) + .orElseThrow(() -> new ResourceNotFoundException("金蝶同步配置不存在: " + id)); + } + + private void rejectActiveRun(Long id, String tenantId, String message) { + if (runRepository.findFirstByTenantIdAndConfigIdAndStatusOrderByStartedAtDesc( + tenantId, id, "RUNNING").isPresent()) throw new BusinessException(message, 409); } @@ -290,10 +315,10 @@ public class KingdeeSyncConfigService { private Map runMap(SysKingdeeSyncRun run) { Map result = new LinkedHashMap<>(); result.put("id", run.getId()); result.put("configId", run.getConfigId()); - result.put("status", run.getStatus()); result.put("filterString", run.getFilterString()); + result.put("status", run.getStatus()); result.put("fetchedCount", run.getFetchedCount()); result.put("insertedCount", run.getInsertedCount()); result.put("updatedCount", run.getUpdatedCount()); result.put("failedCount", run.getFailedCount()); - result.put("errorMessage", run.getErrorMessage()); result.put("startedAt", run.getStartedAt()); result.put("finishedAt", run.getFinishedAt()); + result.put("startedAt", run.getStartedAt()); result.put("finishedAt", run.getFinishedAt()); result.put("heartbeatAt", run.getHeartbeatAt()); result.put("leaseUntil", run.getLeaseUntil()); return result; } @@ -305,6 +330,12 @@ public class KingdeeSyncConfigService { } private String upper(String value) { return value == null ? "" : value.trim().toUpperCase(Locale.ROOT); } + private String tenant(String value) { + if (value == null || !value.matches("[A-Za-z0-9._-]{1,64}")) + throw new org.springframework.security.access.AccessDeniedException("无效租户边界"); + return value; + } + @Data @NoArgsConstructor @AllArgsConstructor public static class ConfigRequest { private String configName; private String formId; private String targetTableName; private String targetTableComment; diff --git a/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java b/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java index 38deff6..9f34226 100644 --- a/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java +++ b/src/main/java/com/finance/system/service/KingdeeSyncRunRecovery.java @@ -23,6 +23,6 @@ public class KingdeeSyncRunRecovery { @Scheduled(fixedDelay = 30000L) public void reapExpiredLeases() { int count = stateService.reapExpiredLeases(); - if (count > 0) log.warn("Marked {} expired Kingdee sync runs as FAILED", count); + if (count > 0) log.warn("已将 {} 条过期的金蝶同步运行记录标记为失败(FAILED)", count); } } diff --git a/src/main/java/com/finance/system/service/PayeeAccountService.java b/src/main/java/com/finance/system/service/PayeeAccountService.java new file mode 100644 index 0000000..bb220a3 --- /dev/null +++ b/src/main/java/com/finance/system/service/PayeeAccountService.java @@ -0,0 +1,400 @@ +package com.finance.system.service; + +import com.finance.system.authorization.SubjectContext; +import com.finance.system.dto.PayeeAccountDto; +import com.finance.system.dto.PayeeAccountRequest; +import com.finance.system.dto.PayeeUserDto; +import com.finance.system.entity.SysBankAccount; +import com.finance.system.entity.SysDepartment; +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.repository.SysBankAccountRepository; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.security.finance.FinanceAuthorization; +import com.finance.system.security.finance.BankAccountProtection; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.PersistenceContext; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +public class PayeeAccountService { + private static final String RESOURCE = "payee.account"; + private static final String REIMBURSEMENT_RESOURCE = "reimbursement.application"; + private static final String ACTIVE = "ACTIVE"; + private static final String INACTIVE = "INACTIVE"; + + private final SysBankAccountRepository accounts; + private final SysUserRepository users; + private final SysDepartmentRepository departments; + private final FinanceAuthorization authorization; + private final FinanceAuditEvents audit; + private final PayeeSubjectService payeeSubjects; + private final BankAccountProtection bankAccountProtection; + + @PersistenceContext + private EntityManager entityManager; + + public PayeeAccountService(SysBankAccountRepository accounts, SysUserRepository users, + SysDepartmentRepository departments, FinanceAuthorization authorization, + FinanceAuditEvents audit, PayeeSubjectService payeeSubjects, + BankAccountProtection bankAccountProtection) { + this.accounts = accounts; + this.users = users; + this.departments = departments; + this.authorization = authorization; + this.audit = audit; + this.payeeSubjects = payeeSubjects; + this.bankAccountProtection = bankAccountProtection; + } + + /** + * Reimbursement form selector. This is intentionally independent from payee-master-data + * permissions: the employee may select only their own active account when they can create + * or edit a reimbursement application. + */ + @Transactional(readOnly = true) + public List listOwnActiveForReimbursement(Long actorId, String keyword) { + SubjectContext subject = authorization.subject(actorId); + SysUser actor = users.findById(actorId) + .orElseThrow(() -> new AccessDeniedException("当前用户不存在")); + if (!isActive(actor.getStatus()) || users.countActiveDirectoryEmployee(actor.getFeishuOpenId()) == 0 + || !sameBoundary(actor, subject)) { + throw new AccessDeniedException("当前用户边界无效"); + } + boolean canCreate = authorization.canUserResource(subject, REIMBURSEMENT_RESOURCE, + "create", actor, String.valueOf(actor.getId())); + boolean canEdit = authorization.canUserResource(subject, REIMBURSEMENT_RESOURCE, + "edit", actor, String.valueOf(actor.getId())); + if (!canCreate && !canEdit) { + throw new AccessDeniedException("当前账号没有发起或编辑报销权限"); + } + Map departmentNames = departmentNames(Collections.singletonList(actor)); + return accounts.findByUserId(actorId).stream() + .filter(account -> Objects.equals(account.getUserId(), actorId)) + .filter(account -> isActive(account.getStatus())) + .map(account -> toDto(account, actor, departmentNames.get(actor.getDepartmentId()))) + .filter(value -> matches(value, keyword)) + .sorted(accountOrder()) + .collect(Collectors.toList()); + } + + /** Management list is still constrained by canonical tenant/organization/data scope. */ + @Transactional(readOnly = true) + public List list(Long actorId, String keyword) { + Access access = access(actorId); + List visibleUsers = users.findByTenantId(access.subject.getTenantId()).stream() + .filter(user -> users.countActiveDirectoryEmployee(user.getFeishuOpenId()) > 0) + .filter(user -> authorization.canUserResource(access.subject, RESOURCE, "read", user, + String.valueOf(user.getId()))) + .collect(Collectors.toList()); + if (visibleUsers.isEmpty()) return Collections.emptyList(); + Map byId = visibleUsers.stream().collect(Collectors.toMap(SysUser::getId, + Function.identity(), (left, right) -> left, LinkedHashMap::new)); + Map departmentNames = departmentNames(visibleUsers); + Map manageable = visibleUsers.stream().collect(Collectors.toMap(SysUser::getId, + user -> authorization.canUserResource(access.subject, RESOURCE, "manage", user, + String.valueOf(user.getId())))); + return accounts.findByUserIdIn(new ArrayList<>(byId.keySet())).stream() + .map(account -> { + SysUser user = byId.get(account.getUserId()); + return user == null ? null : toDto(account, user, departmentNames.get(user.getDepartmentId()), + Boolean.TRUE.equals(manageable.get(user.getId()))); + }) + .filter(Objects::nonNull) + .filter(value -> matches(value, keyword)) + .sorted(accountOrder()) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public List eligibleUsers(Long actorId) { + Access access = access(actorId); + List visibleUsers = users.findByTenantId(access.subject.getTenantId()).stream() + .filter(user -> isActive(user.getStatus())) + .filter(user -> users.countActiveDirectoryEmployee(user.getFeishuOpenId()) > 0) + .filter(user -> authorization.canUserResource(access.subject, RESOURCE, "manage", user, + String.valueOf(user.getId()))) + .collect(Collectors.toList()); + return visibleUsers.stream().map(user -> PayeeUserDto.builder().openId(user.getFeishuOpenId()) + .realName(users.findActiveDirectoryEmployeeName(user.getFeishuOpenId())).build()) + .sorted(Comparator.comparing(PayeeUserDto::getRealName, + Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)) + .thenComparing(PayeeUserDto::getOpenId)) + .collect(Collectors.toList()); + } + + @Transactional + public PayeeAccountDto create(Long actorId, PayeeAccountRequest request) { + Access access = access(actorId); + SysUser user = lockActiveTarget(request.getUserId(), access); + List existing = accounts.findByUserIdForUpdate(user.getId()); + String accountNo = normalizeAccountNo(request.getAccountNo(), true); + BankAccountProtection.ProtectedValue protectedValue = bankAccountProtection.protect(accountNo); + assertNoDuplicate(existing, null, request.getBankName(), protectedValue.getFingerprint()); + String status = normalizeStatus(request.getStatus()); + SysBankAccount account = new SysBankAccount(); + account.setUserId(user.getId()); + account.setPayeeId(payeeSubjects.ensureEmployeePayee(user).getId()); + apply(account, request, protectedValue, status); + if (Boolean.TRUE.equals(account.getIsDefault())) clearOtherDefaults(existing, null); + try { + account = accounts.saveAndFlush(account); + } catch (DataIntegrityViolationException conflict) { + throw new BusinessException("付款对象数据冲突,请刷新后重试", 409); + } + audit.business("payee.account.create", actorId, "SYS_BANK_ACCOUNT", account.getId(), + account.getStatus(), null, changes("userId", "bankName", "branchName", + "accountNo", "isDefault", "status")); + return toDto(account, user, departmentName(user.getDepartmentId()), true); + } + + @Transactional + public PayeeAccountDto update(Long actorId, Long accountId, PayeeAccountRequest request) { + Access access = access(actorId); + SysBankAccount initial = accounts.findById(accountId) + .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); + } + entityManager.refresh(initial, LockModeType.PESSIMISTIC_WRITE); + if (!Objects.equals(initial.getUserId(), originalUserId)) { + throw new BusinessException("付款对象数据已变化,请刷新后重试", 409); + } + List existing = accounts.findByUserIdForUpdate(originalUserId); + SysBankAccount account = existing.stream().filter(value -> Objects.equals(value.getId(), accountId)) + .findFirst().orElseThrow(() -> new ResourceNotFoundException("付款对象不存在")); + if (account.getPayeeId() == null) { + account.setPayeeId(payeeSubjects.ensureEmployeePayee(user).getId()); + } + String requestedAccountNo = normalizeAccountNo(request.getAccountNo(), false); + BankAccountProtection.ProtectedValue protectedValue = requestedAccountNo == null + ? null : bankAccountProtection.protect(requestedAccountNo); + String fingerprint = protectedValue == null + ? requireProtectedFingerprint(account) : protectedValue.getFingerprint(); + assertNoDuplicate(existing, account.getId(), request.getBankName(), fingerprint); + String status = normalizeStatus(request.getStatus()); + apply(account, request, protectedValue, status); + if (Boolean.TRUE.equals(account.getIsDefault())) clearOtherDefaults(existing, account.getId()); + account = accounts.save(account); + audit.business("payee.account.update", actorId, "SYS_BANK_ACCOUNT", account.getId(), + account.getStatus(), null, changes("bankName", "branchName", + "accountNo", "isDefault", "status")); + return toDto(account, user, departmentName(user.getDepartmentId()), true); + } + + @Transactional + public PayeeAccountDto deactivate(Long actorId, Long accountId) { + Access access = access(actorId); + SysBankAccount initial = accounts.findById(accountId) + .orElseThrow(() -> new ResourceNotFoundException("付款对象不存在")); + SysUser user = lockActiveTarget(initial.getUserId(), access); + entityManager.refresh(initial, LockModeType.PESSIMISTIC_WRITE); + List existing = accounts.findByUserIdForUpdate(user.getId()); + SysBankAccount account = existing.stream().filter(value -> Objects.equals(value.getId(), accountId)) + .findFirst().orElseThrow(() -> new ResourceNotFoundException("付款对象不存在")); + account.setStatus(INACTIVE); + account.setIsDefault(false); + account = accounts.save(account); + audit.business("payee.account.deactivate", actorId, "SYS_BANK_ACCOUNT", account.getId(), + INACTIVE, null, changes("isDefault", "status")); + return toDto(account, user, departmentName(user.getDepartmentId()), true); + } + + private Access access(Long actorId) { + SubjectContext subject = authorization.subject(actorId); + if (subject == null || !StringUtils.hasText(subject.getTenantId()) + || subject.getOrganizationId() == null) { + throw new AccessDeniedException("付款对象访问边界无效"); + } + return new Access(subject); + } + + private SysUser lockActiveTarget(Long userId, Access access) { + if (userId == null) throw new BusinessException("所属员工不能为空", 400); + SysUser user = users.findByIdForUpdate(userId) + .orElseThrow(() -> new ResourceNotFoundException("所属员工不存在")); + entityManager.refresh(user, LockModeType.PESSIMISTIC_WRITE); + if (!isActive(user.getStatus())) throw new BusinessException("所属员工不存在或已停用", 400); + authorization.checkUserResource(access.subject, RESOURCE, "manage", user, String.valueOf(user.getId())); + return user; + } + + private boolean sameBoundary(SysUser user, SubjectContext subject) { + return Objects.equals(user.getTenantId(), subject.getTenantId()) + && Objects.equals(user.getOrganizationId(), subject.getOrganizationId()); + } + + private void apply(SysBankAccount account, PayeeAccountRequest request, + BankAccountProtection.ProtectedValue protectedValue, String status) { + account.setBankName(requiredText(request.getBankName(), "银行名称", 200)); + account.setBranchName(optionalText(request.getBranchName(), "支行名称", 200)); + if (protectedValue != null) { + account.setAccountNo(null); + account.setAccountNoCiphertext(protectedValue.getCiphertext()); + account.setAccountFingerprint(protectedValue.getFingerprint()); + account.setAccountNoMask(protectedValue.getMask()); + account.setEncryptionKeyVersion(protectedValue.getKeyVersion()); + } + account.setStatus(status); + account.setIsDefault(ACTIVE.equals(status) && Boolean.TRUE.equals(request.getIsDefault())); + } + + private void clearOtherDefaults(List existing, Long keepId) { + for (SysBankAccount value : existing) { + if (Objects.equals(value.getId(), keepId) || !Boolean.TRUE.equals(value.getIsDefault())) continue; + value.setIsDefault(false); + accounts.save(value); + } + } + + private void assertNoDuplicate(List existing, Long currentId, + String bankName, String fingerprint) { + String bankIdentity = canonicalBankIdentity(bankName); + boolean duplicate = existing.stream().anyMatch(value -> !Objects.equals(value.getId(), currentId) + && Objects.equals(canonicalBankIdentity(value.getBankName()), bankIdentity) + && Objects.equals(value.getAccountFingerprint(), fingerprint)); + if (duplicate) throw new BusinessException("该员工已存在相同付款账户", 409); + } + + private String requireProtectedFingerprint(SysBankAccount account) { + if (!StringUtils.hasText(account.getAccountFingerprint()) + || !StringUtils.hasText(account.getAccountNoCiphertext())) { + throw new BusinessException("该账户尚未完成敏感数据迁移,请先执行银行账号加密迁移", 409); + } + return account.getAccountFingerprint(); + } + + private String canonicalBankIdentity(String value) { + if (!StringUtils.hasText(value)) return null; + return value.trim().replaceAll("\\s+", " ").toUpperCase(Locale.ROOT); + } + + private String normalizeStoredAccountNo(String value) { + if (value == null) return null; + return value.trim().replaceAll("[\\s-]+", "").toUpperCase(Locale.ROOT); + } + + private String normalizeAccountNo(String value, boolean required) { + if (!StringUtils.hasText(value)) { + if (required) throw new BusinessException("银行账号不能为空", 400); + return null; + } + String normalized = normalizeStoredAccountNo(value); + if (normalized == null || !normalized.matches("[A-Z0-9]{6,100}")) { + throw new BusinessException("银行账号格式不正确", 400); + } + return normalized; + } + + private String normalizeStatus(String value) { + if (!StringUtils.hasText(value)) return ACTIVE; + String normalized = value.trim().toUpperCase(Locale.ROOT); + if (!ACTIVE.equals(normalized) && !INACTIVE.equals(normalized)) { + throw new BusinessException("账户状态必须为ACTIVE或INACTIVE", 400); + } + return normalized; + } + + private String requiredText(String value, String label, int max) { + String normalized = optionalText(value, label, max); + if (!StringUtils.hasText(normalized)) throw new BusinessException(label + "不能为空", 400); + return normalized; + } + + private String optionalText(String value, String label, int max) { + if (!StringUtils.hasText(value)) return null; + String normalized = value.trim(); + if (normalized.length() > max) throw new BusinessException(label + "过长", 400); + return normalized; + } + + private PayeeAccountDto toDto(SysBankAccount account, SysUser user, String departmentName) { + return toDto(account, user, departmentName, null); + } + + private PayeeAccountDto toDto(SysBankAccount account, SysUser user, String departmentName, + Boolean manageable) { + return PayeeAccountDto.builder().id(account.getId()).payeeId(account.getPayeeId()) + .payeeType("EMPLOYEE").userId(user.getId()) + .name(user.getRealName()).employeeNo(user.getEmployeeNo()).department(departmentName) + .bankName(account.getBankName()) + .branchName(account.getBranchName()) + .bankAccountMask(account.getAccountNoMask()) + .isDefault(Boolean.TRUE.equals(account.getIsDefault())) + .status(isActive(account.getStatus()) ? ACTIVE : INACTIVE) + .manageable(manageable) + .updatedAt(account.getUpdatedAt()).build(); + } + + private Map departmentNames(List values) { + Set ids = values.stream().map(SysUser::getDepartmentId).filter(Objects::nonNull) + .collect(Collectors.toSet()); + if (ids.isEmpty()) return Collections.emptyMap(); + return departments.findAllById(ids).stream().collect(Collectors.toMap(SysDepartment::getId, + SysDepartment::getDeptName, (left, right) -> left)); + } + + private String departmentName(Long departmentId) { + return departmentId == null ? null : departments.findById(departmentId) + .map(SysDepartment::getDeptName).orElse(null); + } + + private boolean matches(PayeeAccountDto value, String keyword) { + if (!StringUtils.hasText(keyword)) return true; + String search = keyword.trim().toLowerCase(Locale.ROOT); + return contains(value.getName(), search) || contains(value.getEmployeeNo(), search) + || contains(value.getBankName(), search) + || contains(value.getBranchName(), search) || contains(value.getBankAccountMask(), search); + } + + private boolean contains(String value, String search) { + return value != null && value.toLowerCase(Locale.ROOT).contains(search); + } + + private Comparator accountOrder() { + return Comparator.comparing(PayeeAccountDto::getName, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)) + .thenComparing(PayeeAccountDto::getIsDefault, Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(PayeeAccountDto::getId, Comparator.nullsLast(Comparator.naturalOrder())); + } + + private boolean isActive(String status) { + return ACTIVE.equalsIgnoreCase(status); + } + + private Map changes(String... fields) { + Map result = new LinkedHashMap<>(); + result.put("changedFields", java.util.Arrays.asList(fields)); + return result; + } + + private static final class Access { + private final SubjectContext subject; + + private Access(SubjectContext subject) { + this.subject = subject; + } + } +} diff --git a/src/main/java/com/finance/system/service/PayeeSubjectService.java b/src/main/java/com/finance/system/service/PayeeSubjectService.java new file mode 100644 index 0000000..d046614 --- /dev/null +++ b/src/main/java/com/finance/system/service/PayeeSubjectService.java @@ -0,0 +1,576 @@ +package com.finance.system.service; + +import com.finance.system.authorization.SubjectContext; +import com.finance.system.dto.PayeeAccountDto; +import com.finance.system.dto.PayeeAccountRequest; +import com.finance.system.dto.PayeeSubjectDto; +import com.finance.system.dto.PayeeSubjectRequest; +import com.finance.system.entity.SysBankAccount; +import com.finance.system.entity.SysDepartment; +import com.finance.system.entity.SysPayee; +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.finance.rules.FinancialBusinessRules; +import com.finance.system.repository.SysBankAccountRepository; +import com.finance.system.repository.SysDepartmentRepository; +import com.finance.system.repository.SysPayeeRepository; +import com.finance.system.repository.SysUserRepository; +import com.finance.system.security.finance.FinanceAuthorization; +import com.finance.system.security.finance.FinanceFieldProjection; +import com.finance.system.security.finance.BankAccountProtection; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +@Service +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 ACTIVE = "ACTIVE"; + private static final String INACTIVE = "INACTIVE"; + + private final SysPayeeRepository payees; + private final SysBankAccountRepository accounts; + private final SysUserRepository users; + private final SysDepartmentRepository departments; + private final FinanceAuthorization authorization; + private final FinanceAuditEvents audit; + private final BankAccountProtection bankAccountProtection; + + public PayeeSubjectService(SysPayeeRepository payees, SysBankAccountRepository accounts, + SysUserRepository users, SysDepartmentRepository departments, + FinanceAuthorization authorization, FinanceAuditEvents audit, + BankAccountProtection bankAccountProtection) { + this.payees = payees; + this.accounts = accounts; + this.users = users; + this.departments = departments; + this.authorization = authorization; + this.audit = audit; + this.bankAccountProtection = bankAccountProtection; + } + + @Transactional(readOnly = true) + public List list(Long actorId, String keyword) { + Access access = access(actorId); + String search = StringUtils.hasText(keyword) ? keyword.trim().toLowerCase(Locale.ROOT) : null; + return payees.findByTenantIdAndOrganizationIdOrderByDisplayNameAscIdAsc( + access.subject.getTenantId(), access.subject.getOrganizationId()).stream() + .filter(this::hasActiveEmployeeReference) + .filter(payee -> can(access, payee, "read")) + .map(payee -> toSubjectDto(payee, can(access, payee, "manage"))) + .filter(dto -> search == null || contains(dto.getDisplayName(), search) + || contains(dto.getIdentityNumber(), search) + || contains(dto.getSupplierCreditCode(), search)) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public PayeeSubjectDto get(Long actorId, Long payeeId) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "read", false); + return toSubjectDto(payee, can(access, payee, "manage")); + } + + @Transactional + public PayeeSubjectDto create(Long actorId, PayeeSubjectRequest request) { + Access access = access(actorId); + if (request.getInitialAccount() == null) { + throw new BusinessException("首个收款账户不能为空", 400); + } + String initialBankName = text(request.getInitialAccount().getBankName(), "银行名称", 200, true); + String initialAccountNo = accountNo(request.getInitialAccount().getAccountNo(), true); + BankAccountProtection.ProtectedValue protectedAccount = bankAccountProtection.protect(initialAccountNo); + String initialBranchName = text(request.getInitialAccount().getBranchName(), "支行名称", 200, false); + String type = normalizeType(request.getPayeeType()); + SysPayee payee; + if (EMPLOYEE.equals(type)) { + SysUser employee = requireEmployee(request.getEmployeeOpenId(), access); + 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); + employee.setIdentityNumber(identityNumber(request.getIdentityNumber())); + users.save(employee); + payee.setTenantId(employee.getTenantId()); + payee.setOrganizationId(employee.getOrganizationId()); + payee.setEmployeeOpenId(employee.getFeishuOpenId()); + payee.setEmployeeUserId(employee.getId()); // Legacy FK mirror; business identity is openId. + payee.setDisplayName(employee.getRealName()); + } else { + rejectSupplierIdentityNumber(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.setPayeeType(type); + payee.setStatus(normalizeStatus(request.getStatus())); + validatePayee(payee); + try { + payee = payees.saveAndFlush(payee); + } catch (DataIntegrityViolationException conflict) { + throw new BusinessException("付款对象主体数据冲突,请刷新后重试", 409); + } + audit.business("payee.subject.create", actorId, "SYS_PAYEE", payee.getId(), + payee.getStatus(), null, changes("payeeType", "displayName", "employeeOpenId", + "identityNumber", "supplierCreditCode", "status")); + SysBankAccount initialAccount = new SysBankAccount(); + initialAccount.setPayeeId(payee.getId()); + initialAccount.setUserId(employeeId(payee)); + initialAccount.setBankName(initialBankName); + initialAccount.setBranchName(initialBranchName); + applyProtected(initialAccount, protectedAccount); + initialAccount.setStatus(ACTIVE); + initialAccount.setIsDefault(true); + initialAccount = accounts.saveAndFlush(initialAccount); + audit.business("payee.account.create", actorId, "SYS_BANK_ACCOUNT", initialAccount.getId(), + initialAccount.getStatus(), null, changes("payeeId", "bankName", "branchName", + "accountNo", "isDefault", "status")); + return toSubjectDto(payee, true); + } + + @Transactional + public PayeeSubjectDto update(Long actorId, Long payeeId, PayeeSubjectRequest request) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "manage", true); + String requestedType = normalizeType(request.getPayeeType()); + if (!requestedType.equals(payee.getPayeeType())) { + 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); + } + SysUser employee = requireEmployee(employeeOpenId(payee), access); + if (request.getIdentityNumber() != null) { + employee.setIdentityNumber(identityNumber(request.getIdentityNumber())); + users.save(employee); + } + payee.setEmployeeOpenId(employee.getFeishuOpenId()); + payee.setDisplayName(employee.getRealName()); + } else { + rejectSupplierIdentityNumber(request); + payee.setDisplayName(text(request.getDisplayName(), "供应商名称", 200, true)); + payee.setSupplierCreditCode(creditCode(request.getSupplierCreditCode())); + assertSupplierCodeAvailable(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")); + return toSubjectDto(payee, true); + } + + @Transactional + public PayeeSubjectDto deactivate(Long actorId, Long payeeId) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "manage", true); + payee.setStatus(INACTIVE); + validatePayee(payee); + accounts.findByPayeeIdForUpdate(payeeId).forEach(account -> { + account.setStatus(INACTIVE); + account.setIsDefault(false); + accounts.save(account); + }); + payee = payees.save(payee); + audit.business("payee.subject.deactivate", actorId, "SYS_PAYEE", payee.getId(), + INACTIVE, null, changes("status")); + return toSubjectDto(payee, true); + } + + @Transactional(readOnly = true) + public List listAccounts(Long actorId, Long payeeId) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "read", false); + boolean manageable = can(access, payee, "manage"); + return accounts.findByPayeeId(payeeId).stream() + .map(account -> toAccountDto(account, payee, manageable)) + .sorted(Comparator.comparing(PayeeAccountDto::getIsDefault, + Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(PayeeAccountDto::getId)) + .collect(Collectors.toList()); + } + + @Transactional + public PayeeAccountDto createAccount(Long actorId, Long payeeId, PayeeAccountRequest request) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "manage", true); + if (!ACTIVE.equalsIgnoreCase(payee.getStatus())) { + throw new BusinessException("付款对象主体已停用", 400); + } + List existing = accounts.findByPayeeIdForUpdate(payeeId); + String accountNo = accountNo(request.getAccountNo(), true); + BankAccountProtection.ProtectedValue protectedValue = bankAccountProtection.protect(accountNo); + assertNoDuplicate(existing, null, request.getBankName(), protectedValue.getFingerprint()); + SysBankAccount account = new SysBankAccount(); + account.setPayeeId(payeeId); + account.setUserId(employeeId(payee)); + applyAccount(account, request, protectedValue); + if (Boolean.TRUE.equals(account.getIsDefault())) clearDefaults(existing, null); + account = accounts.saveAndFlush(account); + audit.business("payee.account.create", actorId, "SYS_BANK_ACCOUNT", account.getId(), + account.getStatus(), null, changes("payeeId", "bankName", "branchName", + "accountNo", "isDefault", "status")); + return toAccountDto(account, payee, true); + } + + @Transactional + public PayeeAccountDto updateAccount(Long actorId, Long payeeId, Long accountId, + PayeeAccountRequest request) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "manage", true); + List existing = accounts.findByPayeeIdForUpdate(payeeId); + SysBankAccount account = existing.stream().filter(value -> Objects.equals(value.getId(), accountId)) + .findFirst().orElseThrow(() -> new ResourceNotFoundException("收款账户不存在")); + String requested = accountNo(request.getAccountNo(), false); + BankAccountProtection.ProtectedValue protectedValue = requested == null + ? null : bankAccountProtection.protect(requested); + String fingerprint = protectedValue == null + ? requireProtectedFingerprint(account) : protectedValue.getFingerprint(); + assertNoDuplicate(existing, accountId, request.getBankName(), fingerprint); + applyAccount(account, request, protectedValue); + if (Boolean.TRUE.equals(account.getIsDefault())) clearDefaults(existing, accountId); + account = accounts.save(account); + audit.business("payee.account.update", actorId, "SYS_BANK_ACCOUNT", account.getId(), + account.getStatus(), null, changes("bankName", "branchName", + "accountNo", "isDefault", "status")); + return toAccountDto(account, payee, true); + } + + @Transactional + public PayeeAccountDto setDefaultAccount(Long actorId, Long payeeId, Long accountId) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "manage", true); + if (!ACTIVE.equalsIgnoreCase(payee.getStatus())) { + throw new BusinessException("付款对象主体已停用", 400); + } + List existing = accounts.findByPayeeIdForUpdate(payeeId); + SysBankAccount account = existing.stream() + .filter(value -> Objects.equals(value.getId(), accountId)) + .findFirst().orElseThrow(() -> new ResourceNotFoundException("收款账户不存在")); + if (!ACTIVE.equalsIgnoreCase(account.getStatus())) { + throw new BusinessException("已停用的收款账户不能设为默认账户", 400); + } + clearDefaults(existing, accountId); + account.setIsDefault(true); + account = accounts.save(account); + audit.business("payee.account.set-default", actorId, "SYS_BANK_ACCOUNT", account.getId(), + account.getStatus(), null, changes("isDefault")); + return toAccountDto(account, payee, true); + } + + @Transactional + public PayeeAccountDto deactivateAccount(Long actorId, Long payeeId, Long accountId) { + Access access = access(actorId); + SysPayee payee = requirePayee(payeeId, access, "manage", true); + SysBankAccount account = accounts.findByPayeeIdForUpdate(payeeId).stream() + .filter(value -> Objects.equals(value.getId(), accountId)).findFirst() + .orElseThrow(() -> new ResourceNotFoundException("收款账户不存在")); + account.setStatus(INACTIVE); + account.setIsDefault(false); + account = accounts.save(account); + audit.business("payee.account.deactivate", actorId, "SYS_BANK_ACCOUNT", account.getId(), + INACTIVE, null, changes("isDefault", "status")); + return toAccountDto(account, payee, true); + } + + @Transactional + public SysPayee ensureEmployeePayee(SysUser employee) { + if (!StringUtils.hasText(employee.getFeishuOpenId()) + || users.countActiveDirectoryEmployee(employee.getFeishuOpenId()) == 0) { + throw new BusinessException("关联员工不在在职通讯录中", 400); + } + java.util.Optional existing = payees.findByEmployeeOpenId(employee.getFeishuOpenId()); + if (!existing.isPresent()) existing = payees.findByEmployeeUserId(employee.getId()) + .filter(value -> !StringUtils.hasText(value.getEmployeeOpenId())); + if (existing.isPresent()) { + SysPayee value = existing.get(); + if (!StringUtils.hasText(value.getEmployeeOpenId())) { + value.setEmployeeOpenId(employee.getFeishuOpenId()); + validatePayee(value); + return payees.saveAndFlush(value); + } + return value; + } + return existing.orElseGet(() -> { + SysPayee value = SysPayee.builder().tenantId(employee.getTenantId()) + .organizationId(employee.getOrganizationId()).payeeType(EMPLOYEE) + .displayName(employee.getRealName()).employeeOpenId(employee.getFeishuOpenId()) + .employeeUserId(employee.getId()) + .status(ACTIVE).build(); + validatePayee(value); + try { + return payees.saveAndFlush(value); + } catch (DataIntegrityViolationException conflict) { + return payees.findByEmployeeOpenId(employee.getFeishuOpenId()).orElseThrow(() -> conflict); + } + }); + } + + private void validatePayee(SysPayee payee) { + FinancialBusinessRules.payee(payee.getPayeeType(), payee.getEmployeeUserId(), payee.getSupplierCreditCode()); + } + + 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("付款对象访问边界无效"); + } + 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("付款对象主体不存在"); + if (EMPLOYEE.equals(payee.getPayeeType())) { + SysUser owner = java.util.Optional.ofNullable(employee(payee)) + .orElseThrow(() -> new ResourceNotFoundException("付款对象主体不存在")); + authorization.checkUserResource(access.subject, RESOURCE, action, owner, String.valueOf(id)); + } else { + checkSupplierAccess(access, action, String.valueOf(id)); + } + return payee; + } + + private boolean can(Access access, SysPayee payee, String action) { + if (!sameBoundary(payee, access.subject)) return false; + if (EMPLOYEE.equals(payee.getPayeeType())) { + return java.util.Optional.ofNullable(employee(payee)) + .map(owner -> authorization.canUserResource(access.subject, RESOURCE, action, + owner, String.valueOf(payee.getId()))).orElse(false); + } + return authorization.canUserResource(access.subject, RESOURCE, action, access.actor, + String.valueOf(payee.getId())); + } + + private void checkSupplierAccess(Access access, String action, String resourceId) { + authorization.checkUserResource(access.subject, RESOURCE, action, access.actor, + resourceId == null ? "new-supplier" : resourceId); + } + + private SysUser requireEmployee(String openId, Access access) { + if (!StringUtils.hasText(openId)) throw new BusinessException("关联员工不能为空", 400); + if (users.countActiveDirectoryEmployee(openId) == 0) throw new BusinessException("关联员工不在在职通讯录中", 400); + SysUser resolved = users.findByFeishuOpenId(openId); + if (resolved == null) throw new ResourceNotFoundException("关联员工不存在"); + SysUser user = users.findByIdForUpdate(resolved.getId()) + .orElseThrow(() -> new ResourceNotFoundException("关联员工不存在")); + if (!ACTIVE.equalsIgnoreCase(user.getStatus())) throw new BusinessException("关联员工已停用", 400); + authorization.checkUserResource(access.subject, RESOURCE, "manage", user, openId); + return user; + } + + private boolean hasActiveEmployeeReference(SysPayee payee) { + return !EMPLOYEE.equalsIgnoreCase(payee.getPayeeType()) + || users.countActiveDirectoryEmployee(employeeOpenId(payee)) > 0; + } + + private SysUser employee(SysPayee payee) { + if (StringUtils.hasText(payee.getEmployeeOpenId())) return users.findByFeishuOpenId(payee.getEmployeeOpenId()); + return payee.getEmployeeUserId() == null ? null : users.findById(payee.getEmployeeUserId()).orElse(null); + } + + private String employeeOpenId(SysPayee payee) { + SysUser user = employee(payee); + return user == null ? payee.getEmployeeOpenId() : user.getFeishuOpenId(); + } + + private Long employeeId(SysPayee payee) { + SysUser user = employee(payee); + return user == null ? null : user.getId(); + } + + private PayeeSubjectDto toSubjectDto(SysPayee payee, boolean manageable) { + SysUser employee = employee(payee); + return PayeeSubjectDto.builder().id(payee.getId()).payeeType(payee.getPayeeType()) + .displayName(payee.getDisplayName()).employeeOpenId(employeeOpenId(payee)) + .identityNumber(employee == null ? null + : FinanceFieldProjection.maskIdentityNumber(employee.getIdentityNumber())) + .supplierCreditCode(payee.getSupplierCreditCode()).status(payee.getStatus()) + .accountCount(accounts.findByPayeeId(payee.getId()).size()).manageable(manageable) + .updatedAt(payee.getUpdatedAt()).build(); + } + + private PayeeAccountDto toAccountDto(SysBankAccount account, SysPayee payee, boolean manageable) { + SysUser employee = employee(payee); + String department = employee == null || employee.getDepartmentId() == null ? null + : departments.findById(employee.getDepartmentId()).map(SysDepartment::getDeptName).orElse(null); + return PayeeAccountDto.builder().id(account.getId()).payeeId(payee.getId()) + .payeeType(payee.getPayeeType()).userId(employeeId(payee)) + .name(payee.getDisplayName()).employeeNo(employee == null ? null : employee.getEmployeeNo()) + .department(department).supplierCreditCode(payee.getSupplierCreditCode()) + .bankName(account.getBankName()) + .branchName(account.getBranchName()) + .bankAccountMask(account.getAccountNoMask()) + .isDefault(Boolean.TRUE.equals(account.getIsDefault())).status(account.getStatus()) + .manageable(manageable).updatedAt(account.getUpdatedAt()).build(); + } + + private void applyAccount(SysBankAccount account, PayeeAccountRequest request, + BankAccountProtection.ProtectedValue protectedValue) { + String status = normalizeStatus(request.getStatus()); + account.setBankName(text(request.getBankName(), "银行名称", 200, true)); + account.setBranchName(text(request.getBranchName(), "支行名称", 200, false)); + if (protectedValue != null) applyProtected(account, protectedValue); + account.setStatus(status); + account.setIsDefault(ACTIVE.equals(status) && Boolean.TRUE.equals(request.getIsDefault())); + } + + private void applyProtected(SysBankAccount account, BankAccountProtection.ProtectedValue value) { + account.setAccountNo(null); + account.setAccountNoCiphertext(value.getCiphertext()); + account.setAccountFingerprint(value.getFingerprint()); + account.setAccountNoMask(value.getMask()); + account.setEncryptionKeyVersion(value.getKeyVersion()); + } + + private void clearDefaults(List existing, Long keepId) { + existing.stream().filter(value -> !Objects.equals(value.getId(), keepId) + && Boolean.TRUE.equals(value.getIsDefault())) + .forEach(value -> { value.setIsDefault(false); accounts.save(value); }); + } + + private void assertNoDuplicate(List existing, Long currentId, + String bankName, String fingerprint) { + String bank = canonical(bankName); + 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); + } + + private String requireProtectedFingerprint(SysBankAccount account) { + if (!StringUtils.hasText(account.getAccountFingerprint()) + || !StringUtils.hasText(account.getAccountNoCiphertext())) { + throw new BusinessException("该账户尚未完成敏感数据迁移,请先执行银行账号加密迁移", 409); + } + return account.getAccountFingerprint(); + } + + private void assertSupplierCodeAvailable(SysPayee payee) { + long excludedId = payee.getId() == null ? -1L : payee.getId(); + if (payees.existsByTenantIdAndSupplierCreditCodeAndIdNot( + payee.getTenantId(), payee.getSupplierCreditCode(), excludedId)) { + 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}")) { + throw new BusinessException("统一社会信用代码格式不正确", 400); + } + return code; + } + + private String identityNumber(String value) { + String number = text(value, "身份证号", 18, false); + if (number == null) return null; + if (!number.matches("[0-9]{15}|[0-9]{17}[0-9Xx]")) { + throw new BusinessException("身份证号格式不正确,请填写15位或18位居民身份证号", 400); + } + return number.toUpperCase(Locale.ROOT); + } + + private void rejectSupplierIdentityNumber(PayeeSubjectRequest request) { + if (request.getIdentityNumber() != null) { + throw new BusinessException("供应商付款对象不能填写身份证号", 400); + } + } + + private String accountNo(String value, boolean required) { + if (!StringUtils.hasText(value)) { + if (required) throw new BusinessException("银行账号不能为空", 400); + return null; + } + String normalized = canonicalAccount(value); + if (!normalized.matches("[A-Z0-9]{6,100}")) throw new BusinessException("银行账号格式不正确", 400); + return normalized; + } + + private String canonicalAccount(String value) { + return value == null ? null : value.trim().replaceAll("[\\s-]+", "").toUpperCase(Locale.ROOT); + } + + private String canonical(String value) { + return value == null ? null : value.trim().replaceAll("\\s+", " ").toUpperCase(Locale.ROOT); + } + + 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); + } + return type; + } + + private String normalizeStatus(String value) { + if (!StringUtils.hasText(value)) return ACTIVE; + String status = value.trim().toUpperCase(Locale.ROOT); + if (!ACTIVE.equals(status) && !INACTIVE.equals(status)) { + throw new BusinessException("状态必须为ACTIVE或INACTIVE", 400); + } + return status; + } + + private String text(String value, String label, int max, boolean required) { + if (!StringUtils.hasText(value)) { + if (required) throw new BusinessException(label + "不能为空", 400); + return null; + } + String result = value.trim(); + if (result.length() > max) throw new BusinessException(label + "过长", 400); + return result; + } + + private boolean sameBoundary(SysPayee payee, SubjectContext subject) { + return Objects.equals(payee.getTenantId(), subject.getTenantId()) + && Objects.equals(payee.getOrganizationId(), subject.getOrganizationId()); + } + + private boolean contains(String value, String search) { + return value != null && value.toLowerCase(Locale.ROOT).contains(search); + } + + private Map changes(String... fields) { + Map result = new LinkedHashMap<>(); + result.put("changedFields", java.util.Arrays.asList(fields)); + return result; + } + + private static final class Access { + private final SubjectContext subject; + private final SysUser actor; + + private Access(SubjectContext subject, SysUser actor) { + this.subject = subject; + this.actor = actor; + } + } +} diff --git a/src/main/java/com/finance/system/service/PrototypeBusinessConfigService.java b/src/main/java/com/finance/system/service/PrototypeBusinessConfigService.java new file mode 100644 index 0000000..59aaa73 --- /dev/null +++ b/src/main/java/com/finance/system/service/PrototypeBusinessConfigService.java @@ -0,0 +1,639 @@ +package com.finance.system.service; + +import com.finance.system.exception.BadRequestException; +import com.finance.system.exception.ResourceNotFoundException; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.finance.rules.FinancialBusinessRules; +import com.finance.system.security.PermissionChecker; +import com.finance.system.util.AuditUtil; +import com.finance.system.util.Sha256; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Year; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** Business-configuration application service modeled after the approved prototype. */ +@Service +@RequiredArgsConstructor +public class PrototypeBusinessConfigService { + private static final Pattern CREDIT_CODE = Pattern.compile("[0-9A-Z]{18}"); + private static final Pattern ACCOUNT_NO = Pattern.compile("[0-9A-Za-z]{6,64}"); + private static final Set MASTER_RESOURCES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "legal-entities", "cost-centers", "currencies", "payment-methods", "payment-accounts"))); + + private final JdbcTemplate jdbc; + private final PermissionChecker permissionChecker; + private final IntegrationConfigCrypto crypto; + private final FinanceAuditEvents audit; + + public List> list(String resource, Authentication authentication) { + assertMasterResource(resource); + List> rows; + switch (resource) { + case "legal-entities": + rows = jdbc.queryForList("SELECT t.id,t.code,t.name,t.credit_code creditCode,t.status FROM biz_legal_entity t ORDER BY t.code,t.id"); + break; + case "cost-centers": + rows = jdbc.queryForList("SELECT t.id,t.code,t.name,t.legal_entity_id legalEntityId,le.name legalEntityName,du.name managerName,t.status FROM biz_cost_center t JOIN biz_legal_entity le ON le.id=t.legal_entity_id LEFT JOIN feishu_directory_user du ON du.open_id=t.manager_open_id AND du.employment_status='ACTIVE' AND du.eligible=1 ORDER BY t.code,t.id"); + break; + case "currencies": + rows = jdbc.queryForList("SELECT t.id,t.code,t.name,t.symbol,t.decimal_places decimalPlaces,t.status FROM biz_currency t ORDER BY t.code,t.id"); + break; + case "payment-methods": + rows = jdbc.queryForList("SELECT t.id,t.code,t.name,t.description,t.status FROM biz_payment_method t ORDER BY t.code,t.id"); + break; + case "payment-accounts": + rows = jdbc.queryForList("SELECT t.id,t.code,t.legal_entity_id legalEntityId,le.name legalEntityName,t.bank_name bankName,t.branch_name branchName,t.account_no_mask accountNoMask,t.currency_code currencyCode,t.status FROM biz_payment_account t JOIN biz_legal_entity le ON le.id=t.legal_entity_id ORDER BY t.code,t.id"); + attachPaymentMethods(rows); + break; + default: + throw new ResourceNotFoundException("不支持的业务配置资源"); + } + return filterListFields(resource, rows, authentication); + } + + @Transactional + public Map create(String resource, Map body, Authentication authentication) { + if (body == null) throw new BadRequestException("请求体不能为空"); + switch (resource) { + case "legal-entities": return createLegalEntity(body, authentication); + case "cost-centers": return createCostCenter(body, authentication); + case "payment-methods": return createPaymentMethod(body, authentication); + case "payment-accounts": return createPaymentAccount(body, authentication); + case "currencies": throw new BadRequestException("币种由系统预置,本期不提供新增操作"); + default: throw new ResourceNotFoundException("不支持的业务配置资源"); + } + } + + public Map references(Authentication authentication) { + Map result = new LinkedHashMap<>(); + boolean costCenterPage = permissionChecker.has(authentication, "page.cost-centers"); + boolean paymentAccountPage = permissionChecker.has(authentication, "page.payment-accounts"); + boolean budgetPage = permissionChecker.has(authentication, "page.budgets"); + if (costCenterPage) { + result.put("employees", jdbc.queryForList("SELECT open_id openId,name FROM feishu_directory_user WHERE employment_status='ACTIVE' AND eligible=1 ORDER BY name,open_id")); + } + if (costCenterPage || paymentAccountPage || budgetPage) { + result.put("legalEntities", jdbc.queryForList("SELECT id,code,name,status FROM biz_legal_entity WHERE status='ACTIVE' ORDER BY code")); + } + if (budgetPage) { + result.put("costCenters", jdbc.queryForList("SELECT id,code,name,legal_entity_id legalEntityId,status FROM biz_cost_center WHERE status='ACTIVE' ORDER BY code")); + } + if (paymentAccountPage || budgetPage) { + result.put("currencies", jdbc.queryForList("SELECT id,code,name,symbol,decimal_places decimalPlaces,status FROM biz_currency WHERE status='ACTIVE' ORDER BY code")); + } + if (paymentAccountPage) { + result.put("paymentMethods", jdbc.queryForList("SELECT id,code,name,description,status FROM biz_payment_method WHERE status='ACTIVE' ORDER BY code")); + } + return result; + } + + @Transactional + public Map changeStatus(String resource, Long id, Map body, + Authentication authentication) { + assertMasterResource(resource); + if ("currencies".equals(resource)) throw new BadRequestException("预置币种不允许在页面启停"); + String status = enumValue(body, "status", "状态", "ACTIVE", "INACTIVE"); + String table = table(resource); + requireId(table, id, "业务配置不存在"); + if ("INACTIVE".equals(status)) ensureCanDeactivate(resource, id); + jdbc.update("UPDATE " + table + " SET status=?,updated_at=CURRENT_TIMESTAMP(6) WHERE id=?", status, id); + audit.business("business.config.master.status-change", AuditUtil.getCurrentUserId(), + table.toUpperCase(Locale.ROOT), id, status, null, null); + return findMaster(resource, id, authentication); + } + + public Map budgetOverview(Authentication authentication) { + Map result = new LinkedHashMap<>(); + List> 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"); + List> ledgers = jdbc.queryForList( + "SELECT l.id,l.fiscal_year fiscalYear,l.legal_entity_id legalEntityId,le.name legalEntityName," + + "l.cost_center_id costCenterId,cc.code costCenterCode,cc.name costCenterName," + + "l.budget_subject_id subjectId,s.code subjectCode,s.name subjectName,p.code categoryCode,p.name categoryName," + + "l.currency_code currencyCode,l.limit_amount limitAmount,l.occupied_amount occupiedAmount," + + "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"); + for (Map ledger : ledgers) { + BigDecimal limit = decimalValue(ledger.get("limitAmount")); + BigDecimal committed = decimalValue(ledger.get("occupiedAmount")).add(decimalValue(ledger.get("executedAmount"))); + ledger.put("usagePercent", limit.signum() == 0 ? 0 : committed.multiply(new BigDecimal("100")).divide(limit, 0, RoundingMode.HALF_UP).min(new BigDecimal("100")).intValue()); + } + List> adjustments = jdbc.queryForList( + "SELECT a.id,a.request_no requestNo,a.created_at createdAt,l.fiscal_year fiscalYear,le.name legalEntityName," + + "cc.code costCenterCode,cc.name costCenterName,s.code subjectCode,s.name subjectName,p.name categoryName," + + "l.currency_code currencyCode,a.direction,a.amount,a.before_limit beforeLimit,a.after_limit afterLimit," + + "a.reason,a.approval_status approvalStatus,COALESCE(u.real_name,'系统') applicantName " + + "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"); + List> summary = budgetSummary(ledgers); + filterBudgetOverview(subjects, ledgers, adjustments, summary, authentication); + result.put("fiscalYear", Year.now().getValue()); + result.put("subjects", subjects); + result.put("ledgers", ledgers); + result.put("adjustments", adjustments); + result.put("summary", summary); + return result; + } + + @Transactional + public Map createBudgetSubject(Map 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.description", "适用说明"); + Long parentId = longValue(body.get("parentId"), "所属预算分类"); + Map 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("只能在启用的一级预算分类下新增二级科目"); + } + 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"))); + FinancialBusinessRules.subject(2); + jdbc.update("INSERT INTO biz_budget_subject(code,name,level,parent_id,description,status,created_at,updated_at) VALUES(?,?,2,?,?,'ACTIVE',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", + code, name, parentId, description); + Long id = jdbc.queryForObject("SELECT id FROM biz_budget_subject WHERE code=?", Long.class, code); + audit.business("business.config.budget-subject.create", AuditUtil.getCurrentUserId(), + "BIZ_BUDGET_SUBJECT", id, "ACTIVE", null, null); + return queryOne("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 JOIN biz_budget_subject p ON p.id=s.parent_id WHERE s.id=?", id); + } + + @Transactional + public Map changeBudgetSubjectStatus(Long id, Map body) { + String status = enumValue(body, "status", "状态", "ACTIVE", "INACTIVE"); + Map 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 ("INACTIVE".equals(status) && count("SELECT COUNT(*) FROM biz_budget_ledger WHERE budget_subject_id=? AND status='ACTIVE'", id) > 0) { + throw new BadRequestException("该预算科目仍存在启用中的预算台账,不能停用"); + } + jdbc.update("UPDATE biz_budget_subject SET status=?,updated_at=CURRENT_TIMESTAMP(6) WHERE id=?", status, id); + audit.business("business.config.budget-subject.status-change", AuditUtil.getCurrentUserId(), + "BIZ_BUDGET_SUBJECT", id, status, null, null); + return queryOne("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 JOIN biz_budget_subject p ON p.id=s.parent_id WHERE s.id=?", id); + } + + @Transactional + public Map requestBudgetAdjustment(Map body, Authentication authentication) { + assertBody(body, "fiscalYear", "legalEntityId", "costCenterId", "subjectId", "currencyCode", "direction", "amount", "reason"); + requireEditable(authentication, "dialog.budgets.adjust.fiscalYear", "年度"); + requireEditable(authentication, "dialog.budgets.adjust.legalEntityId", "法人主体"); + requireEditable(authentication, "dialog.budgets.adjust.costCenterId", "成本中心"); + requireEditable(authentication, "dialog.budgets.adjust.subjectId", "预算科目"); + requireEditable(authentication, "dialog.budgets.adjust.currencyCode", "币种"); + requireEditable(authentication, "dialog.budgets.adjust.direction", "调整方向"); + requireEditable(authentication, "dialog.budgets.adjust.amount", "调整额"); + requireEditable(authentication, "dialog.budgets.adjust.reason", "调整依据"); + Long requestedYear = longValue(body.get("fiscalYear"), "年度"); + if (requestedYear < 2000 || requestedYear > 2100) throw new BadRequestException("年度必须介于2000和2100"); + int year = requestedYear.intValue(); + FinancialBusinessRules.fiscalYear(year); + Long legalId = longValue(body.get("legalEntityId"), "法人主体"); + Long costId = longValue(body.get("costCenterId"), "成本中心"); + Long subjectId = longValue(body.get("subjectId"), "预算科目"); + String currency = text(body.get("currencyCode"), "币种", 50).toUpperCase(Locale.ROOT); + String direction = enumValue(body, "direction", "调整方向", "INCREASE", "DECREASE"); + BigDecimal amount = money(body.get("amount"), "调整额"); + FinancialBusinessRules.adjustment(direction, amount); + String reason = text(body.get("reason"), "调整依据", 1000); + 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_currency WHERE code=? AND status='ACTIVE'", currency) == 0) throw new BadRequestException("请选择启用的币种"); + Long ledgerId = findOrCreateLedger(year, legalId, costId, subjectId, currency); + Map ledger = queryOne("SELECT limit_amount limitAmount,occupied_amount occupiedAmount,executed_amount executedAmount FROM biz_budget_ledger WHERE id=? FOR UPDATE", ledgerId); + if (ledger == null) throw new BadRequestException("预算台账不存在"); + BigDecimal before = money(ledger.get("limitAmount"), "预算额度"); + BigDecimal occupied = money(ledger.get("occupiedAmount"), "已占用金额"); + BigDecimal executed = money(ledger.get("executedAmount"), "已执行金额"); + FinancialBusinessRules.ledger(year, before, occupied, executed); + BigDecimal signed = "DECREASE".equals(direction) ? amount.negate() : amount; + BigDecimal after = before.add(signed); + BigDecimal committed = occupied.add(executed); + if (after.compareTo(committed) < 0) throw new BadRequestException("审批生效后的预算额度不能低于已占用与已执行金额之和"); + FinancialBusinessRules.ledger(year, after, occupied, executed); + String requestNo = nextCode("BUDGET_ADJUSTMENT", "BADJ-", 8); + Long actorId = AuditUtil.getCurrentUserId(); + if (actorId == null) throw new AccessDeniedException("未登录"); + jdbc.update("INSERT INTO biz_budget_adjustment(request_no,budget_ledger_id,direction,amount,before_limit,after_limit,reason,applicant_user_id,approval_status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?, 'PENDING',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", + requestNo, ledgerId, direction, amount, before, after, reason, actorId); + Long id = jdbc.queryForObject("SELECT id FROM biz_budget_adjustment WHERE request_no=?", Long.class, requestNo); + audit.business("business.config.budget-adjustment.request", actorId, + "BIZ_BUDGET_ADJUSTMENT", id, "PENDING", amount, null); + return queryOne("SELECT id,request_no requestNo,direction,amount,before_limit beforeLimit,after_limit afterLimit,reason,approval_status approvalStatus,created_at createdAt FROM biz_budget_adjustment WHERE id=?", id); + } + + private Map createLegalEntity(Map body, Authentication authentication) { + assertBody(body, "name", "creditCode"); + requireEditable(authentication, "dialog.legal-entities.create.name", "法人主体名称"); + requireEditable(authentication, "dialog.legal-entities.create.creditCode", "统一社会信用代码"); + String name = text(body.get("name"), "法人主体名称", 200); + String credit = text(body.get("creditCode"), "统一社会信用代码", 18).toUpperCase(Locale.ROOT); + if (!CREDIT_CODE.matcher(credit).matches()) throw new BadRequestException("统一社会信用代码必须为18位大写字母或数字"); + if (count("SELECT COUNT(*) FROM biz_legal_entity WHERE name=? OR credit_code=?", name, credit) > 0) throw new BadRequestException("法人主体名称或统一社会信用代码已存在"); + String code = nextCode("LEGAL_ENTITY", "LE-", 3); + jdbc.update("INSERT INTO biz_legal_entity(code,name,credit_code,status,created_at,updated_at) VALUES(?,?,?,'ACTIVE',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", code, name, credit); + Long id = jdbc.queryForObject("SELECT id FROM biz_legal_entity WHERE code=?", Long.class, code); + audit.business("business.config.legal-entity.create", AuditUtil.getCurrentUserId(), + "BIZ_LEGAL_ENTITY", id, "ACTIVE", null, null); + return findMaster("legal-entities", id, authentication); + } + + private Map createCostCenter(Map body, Authentication authentication) { + assertBody(body, "name", "legalEntityId", "managerOpenId"); + requireEditable(authentication, "dialog.cost-centers.create.name", "成本中心名称"); + requireEditable(authentication, "dialog.cost-centers.create.legalEntityId", "法人主体"); + requireEditable(authentication, "dialog.cost-centers.create.managerName", "负责人"); + String name = text(body.get("name"), "成本中心名称", 200); + Long legalId = longValue(body.get("legalEntityId"), "法人主体"); + String managerOpenId = text(body.get("managerOpenId"), "负责人", 128); + List managers = jdbc.queryForList("SELECT name FROM feishu_directory_user WHERE open_id=? AND employment_status='ACTIVE' AND eligible=1", String.class, managerOpenId); + if (managers.isEmpty()) throw new BadRequestException("负责人必须是在职通讯录员工"); + requireActive("biz_legal_entity", legalId, "法人主体"); + if (count("SELECT COUNT(*) FROM biz_cost_center WHERE legal_entity_id=? AND name=?", legalId, name) > 0) throw new BadRequestException("该法人主体下已存在同名成本中心"); + String code = nextCode("COST_CENTER", "CC-", 3); + jdbc.update("INSERT INTO biz_cost_center(code,name,legal_entity_id,manager_open_id,status,created_at,updated_at) VALUES(?,?,?,?,'ACTIVE',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", code, name, legalId, managerOpenId); + Long id = jdbc.queryForObject("SELECT id FROM biz_cost_center WHERE code=?", Long.class, code); + audit.business("business.config.cost-center.create", AuditUtil.getCurrentUserId(), + "BIZ_COST_CENTER", id, "ACTIVE", null, null); + return findMaster("cost-centers", id, authentication); + } + + private Map createPaymentMethod(Map body, Authentication authentication) { + assertBody(body, "name", "description"); + requireEditable(authentication, "dialog.payment-methods.create.name", "付款方式"); + requireEditable(authentication, "dialog.payment-methods.create.description", "适用说明"); + String name = text(body.get("name"), "付款方式", 120); + String description = text(body.get("description"), "适用说明", 500); + if (count("SELECT COUNT(*) FROM biz_payment_method WHERE name=?", name) > 0) throw new BadRequestException("付款方式名称已存在"); + String code = nextCode("PAYMENT_METHOD", "PM-", 3); + jdbc.update("INSERT INTO biz_payment_method(code,name,description,status,created_at,updated_at) VALUES(?,?,?,'ACTIVE',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", code, name, description); + Long id = jdbc.queryForObject("SELECT id FROM biz_payment_method WHERE code=?", Long.class, code); + audit.business("business.config.payment-method.create", AuditUtil.getCurrentUserId(), + "BIZ_PAYMENT_METHOD", id, "ACTIVE", null, null); + return findMaster("payment-methods", id, authentication); + } + + private Map createPaymentAccount(Map body, Authentication authentication) { + assertBody(body, "legalEntityId", "bankName", "branchName", "accountNo", "currencyCode", "paymentMethodIds"); + requireEditable(authentication, "dialog.payment-accounts.create.legalEntityId", "法人主体"); + requireEditable(authentication, "dialog.payment-accounts.create.bankName", "开户银行"); + requireEditable(authentication, "dialog.payment-accounts.create.accountNo", "银行账号"); + requireEditable(authentication, "dialog.payment-accounts.create.currencyCode", "币种"); + requireEditable(authentication, "dialog.payment-accounts.create.paymentMethodIds", "允许付款方式"); + Long legalId = longValue(body.get("legalEntityId"), "法人主体"); + String bank = text(body.get("bankName"), "开户银行", 200); + String branchName = body.get("branchName") == null ? null : String.valueOf(body.get("branchName")).trim(); + if (!StringUtils.hasText(branchName)) { + branchName = null; + } else { + requireEditable(authentication, "dialog.payment-accounts.create.branchName", "所属分公司"); + if (branchName.length() > 200) throw new BadRequestException("所属分公司长度不能超过200个字符"); + } + String accountNo = normalizeAccount(text(body.get("accountNo"), "银行账号", 80)); + String currency = text(body.get("currencyCode"), "币种", 50).toUpperCase(Locale.ROOT); + List methodIds = longList(body.get("paymentMethodIds"), "允许付款方式"); + if (methodIds.isEmpty()) throw new BadRequestException("至少选择一种允许付款方式"); + requireActive("biz_legal_entity", legalId, "法人主体"); + if (count("SELECT COUNT(*) FROM biz_currency WHERE code=? AND status='ACTIVE'", currency) == 0) throw new BadRequestException("请选择启用的币种"); + String fingerprint = Sha256.hex(accountNo); + if (count("SELECT COUNT(*) FROM biz_payment_account WHERE legal_entity_id=? AND account_fingerprint=? AND currency_code=?", legalId, fingerprint, currency) > 0) throw new BadRequestException("该付款账户已存在"); + for (Long methodId : methodIds) requireActive("biz_payment_method", methodId, "付款方式"); + String code = nextCode("PAYMENT_ACCOUNT", "PA-", 3); + jdbc.update("INSERT INTO biz_payment_account(code,legal_entity_id,bank_name,branch_name,account_no_ciphertext,account_no_mask,account_fingerprint,currency_code,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,'ACTIVE',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", + code, legalId, bank, branchName, crypto.encrypt(accountNo), mask(accountNo), fingerprint, currency); + Long id = jdbc.queryForObject("SELECT id FROM biz_payment_account WHERE code=?", Long.class, code); + for (Long methodId : methodIds) jdbc.update("INSERT INTO biz_payment_account_method(payment_account_id,payment_method_id) VALUES(?,?)", id, methodId); + audit.business("business.config.payment-account.create", AuditUtil.getCurrentUserId(), + "BIZ_PAYMENT_ACCOUNT", id, "ACTIVE", null, + Collections.singletonMap("changedFields", Arrays.asList("legalEntityId", "bankName", + "branchName", "accountNo", "currencyCode", "paymentMethodIds", "status"))); + return findMaster("payment-accounts", id, authentication); + } + + private Map findMaster(String resource, Long id, Authentication authentication) { + List> rows; + switch (resource) { + case "legal-entities": + rows = jdbc.queryForList( + "SELECT id,code,name,credit_code creditCode,status FROM biz_legal_entity WHERE id=?", + id); + break; + case "cost-centers": + rows = jdbc.queryForList( + "SELECT t.id,t.code,t.name,t.legal_entity_id legalEntityId," + + "le.name legalEntityName,du.name managerName,t.status " + + "FROM biz_cost_center t JOIN biz_legal_entity le " + + "ON le.id=t.legal_entity_id LEFT JOIN feishu_directory_user du " + + "ON du.open_id=t.manager_open_id AND du.employment_status='ACTIVE' AND du.eligible=1 WHERE t.id=?", + id); + break; + case "payment-methods": + rows = jdbc.queryForList( + "SELECT id,code,name,description,status FROM biz_payment_method WHERE id=?", + id); + break; + case "payment-accounts": + rows = jdbc.queryForList( + "SELECT t.id,t.code,t.legal_entity_id legalEntityId," + + "le.name legalEntityName,t.bank_name bankName,t.branch_name branchName," + + "t.account_no_mask accountNoMask,t.currency_code currencyCode,t.status " + + "FROM biz_payment_account t JOIN biz_legal_entity le " + + "ON le.id=t.legal_entity_id WHERE t.id=?", + id); + attachPaymentMethods(rows); + break; + default: + throw new ResourceNotFoundException("不支持的业务配置资源"); + } + if (rows.isEmpty()) { + throw new ResourceNotFoundException("业务配置不存在"); + } + return filterListFields(resource, rows, authentication).get(0); + } + + private void attachPaymentMethods(List> accounts) { + for (Map account : accounts) { + Long accountId = longValue(account.get("id"), "付款账户"); + List> methods = jdbc.queryForList( + "SELECT m.id,m.code,m.name FROM biz_payment_account_method am " + + "JOIN biz_payment_method m ON m.id=am.payment_method_id " + + "WHERE am.payment_account_id=? ORDER BY m.code", + accountId); + account.put("paymentMethods", methods); + List ids = new ArrayList<>(); + for (Map method : methods) { + ids.add(longValue(method.get("id"), "付款方式")); + } + account.put("paymentMethodIds", ids); + } + } + + private List> filterListFields(String resource, List> rows, Authentication authentication) { + for (Map row : rows) { + Set keys = new HashSet<>(row.keySet()); + for (String key : keys) { + if ("id".equals(key) || (key.endsWith("Name") && !"branchName".equals(key)) + || "paymentMethods".equals(key) || "paymentMethodIds".equals(key)) { + continue; + } + String permissionField = "accountNoMask".equals(key) ? "accountNo" : key; + if (!permissionChecker.has(authentication, + "ui." + resource + ".column." + permissionField)) { + row.remove(key); + } + } + if (!row.containsKey("legalEntityId")) { + row.remove("legalEntityName"); + } + if (!permissionChecker.has(authentication, "ui." + resource + ".column.paymentMethodIds")) { + row.remove("paymentMethods"); row.remove("paymentMethodIds"); + } + } + return rows; + } + + private List> budgetSummary(List> ledgers) { + Map totals = new LinkedHashMap<>(); + for (Map row : ledgers) { + String currency = String.valueOf(row.get("currencyCode")); + BigDecimal[] values = totals.computeIfAbsent(currency, + ignored -> new BigDecimal[]{BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO}); + values[0] = values[0].add(decimalValue(row.get("limitAmount"))); + values[1] = values[1].add(decimalValue(row.get("occupiedAmount"))); + values[2] = values[2].add(decimalValue(row.get("executedAmount"))); + } + List> result = new ArrayList<>(); + for (Map.Entry entry : totals.entrySet()) { + Map item = new LinkedHashMap<>(); + BigDecimal[] values = entry.getValue(); + item.put("currencyCode", entry.getKey()); + item.put("limitAmount", values[0]); + item.put("occupiedAmount", values[1]); + item.put("executedAmount", values[2]); + item.put("availableAmount", values[0].subtract(values[1]).subtract(values[2])); + result.add(item); + } + return result; + } + + private void filterBudgetOverview(List> subjects, + List> ledgers, + List> adjustments, + List> summary, + Authentication authentication) { + for (Map subject : subjects) { + removeWithout(authentication, subject, "ui.budgets.column.code", "code"); + 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 ledger : ledgers) { + removeWithout(authentication, ledger, "ui.budgets.column.fiscalYear", "fiscalYear"); + removeWithout(authentication, ledger, "ui.budgets.column.legalEntityId", "legalEntityId", "legalEntityName"); + removeWithout(authentication, ledger, "ui.budgets.column.costCenterId", "costCenterId", "costCenterCode", "costCenterName"); + removeWithout(authentication, ledger, "ui.budgets.column.code", "subjectId", "subjectCode"); + removeWithout(authentication, ledger, "ui.budgets.column.name", "subjectName"); + removeWithout(authentication, ledger, "ui.budgets.column.category", "categoryCode", "categoryName"); + removeWithout(authentication, ledger, "ui.budgets.column.currencyCode", "currencyCode"); + removeWithout(authentication, ledger, "ui.budgets.column.totalAmount", "limitAmount"); + removeWithout(authentication, ledger, "ui.budgets.column.occupiedAmount", "occupiedAmount"); + removeWithout(authentication, ledger, "ui.budgets.column.usedAmount", "executedAmount"); + removeWithout(authentication, ledger, "ui.budgets.column.availableAmount", "availableAmount"); + removeWithout(authentication, ledger, "ui.budgets.column.usagePercent", "usagePercent"); + removeWithout(authentication, ledger, "ui.budgets.column.status", "status"); + } + for (Map adjustment : adjustments) { + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentNo", "requestNo"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentTime", "createdAt"); + removeWithout(authentication, adjustment, "ui.budgets.column.fiscalYear", "fiscalYear"); + removeWithout(authentication, adjustment, "ui.budgets.column.legalEntityId", "legalEntityName"); + removeWithout(authentication, adjustment, "ui.budgets.column.costCenterId", "costCenterCode", "costCenterName"); + removeWithout(authentication, adjustment, "ui.budgets.column.code", "subjectCode"); + removeWithout(authentication, adjustment, "ui.budgets.column.name", "subjectName"); + removeWithout(authentication, adjustment, "ui.budgets.column.category", "categoryName"); + removeWithout(authentication, adjustment, "ui.budgets.column.currencyCode", "currencyCode"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentDirection", "direction"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentAmount", "amount"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentChange", "beforeLimit", "afterLimit"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentReason", "reason"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentStatus", "approvalStatus"); + removeWithout(authentication, adjustment, "ui.budgets.column.adjustmentApplicant", "applicantName"); + } + for (Map item : summary) { + removeWithout(authentication, item, "ui.budgets.column.currencyCode", "currencyCode"); + removeWithout(authentication, item, "ui.budgets.column.totalAmount", "limitAmount"); + removeWithout(authentication, item, "ui.budgets.column.occupiedAmount", "occupiedAmount"); + removeWithout(authentication, item, "ui.budgets.column.usedAmount", "executedAmount"); + removeWithout(authentication, item, "ui.budgets.column.availableAmount", "availableAmount"); + } + } + + private void removeWithout(Authentication authentication, Map row, + String permission, String... fields) { + if (permissionChecker.has(authentication, permission)) return; + for (String field : fields) row.remove(field); + } + + private Long findOrCreateLedger(int year, Long legalId, Long costId, Long subjectId, String currency) { + FinancialBusinessRules.ledger(year, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); + List ids = jdbc.query("SELECT id FROM biz_budget_ledger WHERE fiscal_year=? AND legal_entity_id=? AND cost_center_id=? AND budget_subject_id=? AND currency_code=? FOR UPDATE", + (rs, row) -> rs.getLong(1), year, legalId, costId, subjectId, currency); + if (!ids.isEmpty()) return ids.get(0); + try { + jdbc.update("INSERT INTO biz_budget_ledger(fiscal_year,legal_entity_id,cost_center_id,budget_subject_id,currency_code,limit_amount,occupied_amount,executed_amount,status,created_at,updated_at) VALUES(?,?,?,?,?,0,0,0,'ACTIVE',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))", + year, legalId, costId, subjectId, currency); + } catch (DuplicateKeyException ignored) { } + return jdbc.queryForObject("SELECT id FROM biz_budget_ledger WHERE fiscal_year=? AND legal_entity_id=? AND cost_center_id=? AND budget_subject_id=? AND currency_code=?", Long.class, + year, legalId, costId, subjectId, currency); + } + + private String nextCode(String key, String prefix, int width) { + Map sequence = queryOne("SELECT next_value nextValue,prefix,code_width codeWidth FROM biz_config_sequence WHERE sequence_key=? FOR UPDATE", key); + if (sequence == null) { + jdbc.update("INSERT INTO biz_config_sequence(sequence_key,prefix,next_value,code_width,updated_at) VALUES(?,?,1,?,CURRENT_TIMESTAMP(6))", key, prefix, width); + sequence = queryOne("SELECT next_value nextValue,prefix,code_width codeWidth FROM biz_config_sequence WHERE sequence_key=? FOR UPDATE", key); + } + long value = number(sequence.get("nextValue")); + jdbc.update("UPDATE biz_config_sequence SET next_value=?,updated_at=CURRENT_TIMESTAMP(6) WHERE sequence_key=?", value + 1, key); + return String.valueOf(sequence.get("prefix")) + String.format("%0" + number(sequence.get("codeWidth")) + "d", value); + } + + private String nextSubjectCode(String parentCode) { + List codes = jdbc.query("SELECT code FROM biz_budget_subject WHERE code LIKE ?", (rs, row) -> rs.getString(1), parentCode + "-%"); + int max = 0; + for (String code : codes) { + String suffix = code.substring((parentCode + "-").length()); + try { max = Math.max(max, Integer.parseInt(suffix)); } catch (NumberFormatException ignored) { } + } + return parentCode + "-" + String.format("%03d", max + 1); + } + + private void ensureCanDeactivate(String resource, Long id) { + int references = 0; + if ("legal-entities".equals(resource)) { + references += count("SELECT COUNT(*) FROM biz_cost_center WHERE legal_entity_id=? AND status='ACTIVE'", id); + references += count("SELECT COUNT(*) FROM biz_budget_ledger WHERE legal_entity_id=? AND status='ACTIVE'", id); + references += count("SELECT COUNT(*) FROM biz_payment_account WHERE legal_entity_id=? AND status='ACTIVE'", id); + } else if ("cost-centers".equals(resource)) { + references += count("SELECT COUNT(*) FROM biz_budget_ledger WHERE cost_center_id=? AND status='ACTIVE'", id); + } + if (references > 0) throw new BadRequestException("当前配置仍被启用中的业务数据引用,不能停用"); + } + + private void requireEditable(Authentication authentication, String code, String label) { + if (!permissionChecker.hasEdit(authentication, code)) throw new AccessDeniedException("无权维护字段: " + label); + } + + private void requireActive(String table, Long id, String label) { + if (id == null || count("SELECT COUNT(*) FROM " + table + " WHERE id=? AND status='ACTIVE'", id) == 0) throw new BadRequestException(label + "不存在或已停用"); + } + + private void requireId(String table, Long id, String message) { + if (id == null || count("SELECT COUNT(*) FROM " + table + " WHERE id=?", id) == 0) throw new ResourceNotFoundException(message); + } + + private String table(String resource) { + switch (resource) { + case "legal-entities": return "biz_legal_entity"; + case "cost-centers": return "biz_cost_center"; + case "currencies": return "biz_currency"; + case "payment-methods": return "biz_payment_method"; + case "payment-accounts": return "biz_payment_account"; + default: throw new ResourceNotFoundException("不支持的业务配置资源"); + } + } + + private void assertMasterResource(String resource) { + if (!MASTER_RESOURCES.contains(resource)) throw new ResourceNotFoundException("不支持的业务配置资源"); + } + + private void assertBody(Map body, String... allowed) { + if (body == null) throw new BadRequestException("请求体不能为空"); + Set names = new HashSet<>(Arrays.asList(allowed)); + for (String key : body.keySet()) if (!names.contains(key)) throw new BadRequestException("不支持的字段: " + key); + } + + private String enumValue(Map body, String key, String label, String... allowed) { + if (body == null) throw new BadRequestException("请求体不能为空"); + String value = text(body.get(key), label, 32).toUpperCase(Locale.ROOT); + if (!Arrays.asList(allowed).contains(value)) throw new BadRequestException(label + "不正确"); + return value; + } + + private String text(Object raw, String label, int max) { + String value = raw == null ? null : String.valueOf(raw).trim(); + if (!StringUtils.hasText(value)) throw new BadRequestException(label + "不能为空"); + if (value.length() > max) throw new BadRequestException(label + "长度不能超过" + max + "个字符"); + return value; + } + + private Long longValue(Object raw, String label) { + if (raw == null || !StringUtils.hasText(String.valueOf(raw))) throw new BadRequestException(label + "不能为空"); + try { return new BigDecimal(String.valueOf(raw)).longValueExact(); } + catch (Exception exception) { throw new BadRequestException(label + "格式不正确"); } + } + + private List longList(Object raw, String label) { + if (!(raw instanceof Iterable)) throw new BadRequestException(label + "格式不正确"); + List values = new ArrayList<>(); + for (Object item : (Iterable) raw) values.add(longValue(item, label)); + return values; + } + + private BigDecimal money(Object raw, String label) { + if (raw == null || !StringUtils.hasText(String.valueOf(raw))) throw new BadRequestException(label + "不能为空"); + try { return new BigDecimal(String.valueOf(raw)).setScale(2, RoundingMode.UNNECESSARY); } + catch (Exception exception) { throw new BadRequestException(label + "必须为最多两位小数的金额"); } + } + + private String normalizeAccount(String value) { + String normalized = value.replaceAll("[\\s-]", ""); + if (!ACCOUNT_NO.matcher(normalized).matches()) throw new BadRequestException("银行账号格式不正确"); + return normalized; + } + + private String mask(String value) { + String tail = value.substring(Math.max(0, value.length() - 4)); + return "**** " + tail; + } + + private long number(Object value) { return value == null ? 0L : new BigDecimal(String.valueOf(value)).longValue(); } + private BigDecimal decimalValue(Object value) { return value == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(value)); } + + private int count(String sql, Object... args) { + Integer value = jdbc.queryForObject(sql, Integer.class, args); + return value == null ? 0 : value; + } + + private Map queryOne(String sql, Object... args) { + List> rows = jdbc.queryForList(sql, args); + return rows.isEmpty() ? null : rows.get(0); + } +} diff --git a/src/main/java/com/finance/system/service/ReimApplicationService.java b/src/main/java/com/finance/system/service/ReimApplicationService.java index 6cd7b24..0387d02 100644 --- a/src/main/java/com/finance/system/service/ReimApplicationService.java +++ b/src/main/java/com/finance/system/service/ReimApplicationService.java @@ -51,7 +51,7 @@ public interface ReimApplicationService { deleteApplication(id, com.finance.system.util.AuditUtil.getCurrentUserId()); } - Page getAccountsPayableTasks(String status, Pageable pageable); + Page getAccountsPayableTasks(Long actorId, String status, Pageable pageable); - Page getCashierTasks(String status, Pageable pageable); + Page getCashierTasks(Long actorId, String status, Pageable pageable); } diff --git a/src/main/java/com/finance/system/service/ReimPaymentService.java b/src/main/java/com/finance/system/service/ReimPaymentService.java index ff550d1..dd5e24e 100644 --- a/src/main/java/com/finance/system/service/ReimPaymentService.java +++ b/src/main/java/com/finance/system/service/ReimPaymentService.java @@ -23,6 +23,10 @@ public interface ReimPaymentService { PaymentResultDto processPartialPayment(Long applicationId, BigDecimal amount, Long operatorId, String paymentMethod, String referenceNo, String remark, String idempotencyKey); + PaymentResultDto verifyPayment(Long paymentId, Long checkerId); + + PaymentResultDto rejectPayment(Long paymentId, Long checkerId, String rejectionCode); + List getPaymentHistoryByOperator(Long operatorId); PaymentRecordDto getPaymentByNo(String paymentNo, Long operatorId); diff --git a/src/main/java/com/finance/system/service/ReimbursementApplicantDepartmentService.java b/src/main/java/com/finance/system/service/ReimbursementApplicantDepartmentService.java new file mode 100644 index 0000000..521f367 --- /dev/null +++ b/src/main/java/com/finance/system/service/ReimbursementApplicantDepartmentService.java @@ -0,0 +1,118 @@ +package com.finance.system.service; + +import com.finance.system.entity.SysUser; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.ApplicantDepartmentDirectoryRepository; +import com.finance.system.repository.FeishuDirectoryDepartmentBindingStore; +import com.finance.system.repository.SysUserRepository; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** Resolves a missing applicant department without replacing an explicit manual assignment. */ +@Service +public class ReimbursementApplicantDepartmentService { + private final ApplicantDepartmentDirectoryRepository directory; + private final FeishuDirectoryDepartmentBindingStore bindings; + private final SysUserRepository users; + private final String deploymentTenant; + private final Long deploymentOrganizationId; + + public ReimbursementApplicantDepartmentService( + ApplicantDepartmentDirectoryRepository directory, + FeishuDirectoryDepartmentBindingStore bindings, + SysUserRepository users, + @Value("${observability.tenant-id:default}") String deploymentTenant, + @Value("${observability.organization-id:1}") Long deploymentOrganizationId) { + this.directory = directory; + this.bindings = bindings; + this.users = users; + this.deploymentTenant = deploymentTenant; + this.deploymentOrganizationId = deploymentOrganizationId; + } + + public Long resolveForCreate(SysUser user, String requestTenant, String selectedOpenDepartmentId) { + return resolveForCreate(user, requestTenant, selectedOpenDepartmentId, true); + } + + public Long resolveForCreate(SysUser user, String requestTenant, String selectedOpenDepartmentId, + boolean externalDepartmentRequired) { + if (user == null || user.getId() == null) throw new BusinessException("申请人不存在", 404); + String selected = exactIdentifier(selectedOpenDepartmentId); + if (selectedOpenDepartmentId != null && selected == null) { + throw new BusinessException("所选飞书部门标识无效", 400); + } + if (user.getDepartmentId() != null && !externalDepartmentRequired) return user.getDepartmentId(); + if (!"ACTIVE".equalsIgnoreCase(user.getStatus())) { + throw new BusinessException("当前用户状态不可发起报销", 403); + } + if (!same(deploymentTenant, requestTenant) || !same(deploymentTenant, user.getTenantId()) + || !same(deploymentOrganizationId, user.getOrganizationId())) { + throw new BusinessException("当前用户不属于本部署组织", 403); + } + String openId = exactIdentifier(user.getFeishuOpenId()); + if (openId == null) { + throw new BusinessException("申请人未绑定可用的飞书身份,无法解析部门", 422); + } + + if (user.getDepartmentId() != null) { + // Legacy/manual compatibility boundary: a pre-existing local + // department remains the authorization/application owner. Only a + // V14-bound department participates in strong identity matching; + // an unbound manual department uses the current published Feishu + // membership solely for the external form snapshot and is never + // auto-claimed or rebound here. + java.util.Optional boundOpenDepartment = directory + .findBoundOpenDepartmentIdByLocalDepartment(user.getDepartmentId()); + ApplicantDepartmentDirectoryRepository.DirectoryDepartment external = + (boundOpenDepartment.isPresent() + ? directory.findPublishedEligibleNonRootMembershipByLocalDepartment( + openId, deploymentTenant, user.getDepartmentId()) + : selected == null + ? directory.findPreferredPublishedEligibleNonRootByOpenId( + openId, deploymentTenant) + : directory.findPublishedEligibleNonRootMembership( + openId, deploymentTenant, selected)) + .orElseThrow(() -> unavailable(selected)); + if (boundOpenDepartment.isPresent() + && selected != null && !selected.equals(external.getOpenDepartmentId())) { + throw new BusinessException("所选飞书部门与申请人已有本地部门不一致", 409); + } + return user.getDepartmentId(); + } + + ApplicantDepartmentDirectoryRepository.DirectoryDepartment remote = (selected == null + ? directory.findPreferredPublishedEligibleNonRootByOpenId(openId, deploymentTenant) + : directory.findPublishedEligibleNonRootMembership(openId, deploymentTenant, selected)) + .orElseThrow(() -> new BusinessException( + selected == null + ? "当前飞书通讯录中没有可用的申请人部门,请联系管理员完成通讯录同步" + : "所选飞书部门不属于申请人在当前通讯录中的有效部门", 422)); + FeishuDirectoryDepartmentBindingStore.Binding binding = bindings.resolveOrCreate( + remote.getOpenDepartmentId(), remote.getDisplayLabel()); + if (binding.getDepartmentId() == null + || !"ACTIVE".equalsIgnoreCase(binding.getDepartmentStatus())) { + throw new BusinessException("申请人对应的本地部门不可用,请联系管理员处理", 422); + } + if (user.getDepartmentId() != null && !user.getDepartmentId().equals(binding.getDepartmentId())) { + throw new BusinessException("所选飞书部门与申请人已有本地部门不一致", 409); + } + user.setDepartmentId(binding.getDepartmentId()); + users.save(user); + return binding.getDepartmentId(); + } + + private static BusinessException unavailable(String selected) { + return new BusinessException(selected == null + ? "当前飞书通讯录中没有可用的申请人部门,请联系管理员完成通讯录同步" + : "所选飞书部门不属于申请人在当前通讯录中的有效部门", 422); + } + + private static String exactIdentifier(String value) { + if (value == null || value.trim().isEmpty()) return null; + return value.equals(value.trim()) ? value : null; + } + + private static boolean same(Object expected, Object actual) { + return expected != null && expected.equals(actual); + } +} diff --git a/src/main/java/com/finance/system/service/ReimbursementAttachmentService.java b/src/main/java/com/finance/system/service/ReimbursementAttachmentService.java index 7d5b144..f44ce15 100644 --- a/src/main/java/com/finance/system/service/ReimbursementAttachmentService.java +++ b/src/main/java/com/finance/system/service/ReimbursementAttachmentService.java @@ -12,8 +12,16 @@ import com.finance.system.exception.BusinessException; import com.finance.system.exception.ResourceNotFoundException; import com.finance.system.repository.ReimApplicationRepository; import com.finance.system.repository.ReimAttachmentRepository; +import com.finance.system.storage.FileStorageCleanupService; +import com.finance.system.storage.FileStorageManager; +import com.finance.system.storage.StorageObjectKeyPolicy; +import com.finance.system.storage.StoredObject; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import com.finance.system.finance.audit.FinanceAuditEvents; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; @@ -27,6 +35,7 @@ import java.util.concurrent.ConcurrentHashMap; @Service @RequiredArgsConstructor +@Slf4j public class ReimbursementAttachmentService { public static final long MAX_FILE_BYTES = 50L * 1024L * 1024L; public static final long MAX_STAGED_BYTES = 500L * 1024L * 1024L; @@ -34,13 +43,22 @@ public class ReimbursementAttachmentService { public static final long MAX_DAILY_BYTES = 1024L * 1024L * 1024L; public static final long MAX_DAILY_COUNT = 100L; private static final String UPLOADED = "UPLOADED"; + private static final String PERSISTING = "PERSISTING"; private static final String DELETED = "DELETED"; private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai"); private final ReimbursementFormService forms; private final FeishuApprovalFileClient client; private final ReimAttachmentRepository attachments; private final ReimApplicationRepository applications; + private final FileStorageManager fileStorage; + private final FileStorageCleanupService storageCleanup; + private final StorageObjectKeyPolicy objectKeys; + private final TransactionTemplate transactions; private final Set uploadsInProgress = ConcurrentHashMap.newKeySet(); + private FinanceAuditEvents financeAudit; + + @Autowired(required = false) + public void setFinanceAudit(FinanceAuditEvents financeAudit) { this.financeAudit = financeAudit; } public AttachmentDto upload(MultipartFile file, String fingerprint, String controlId, Long userId) { if (userId == null) throw new BusinessException("未登录", 401); @@ -57,20 +75,70 @@ public class ReimbursementAttachmentService { catch (IOException e) { throw new BusinessException("无法读取附件", 400); } if (bytes.length == 0 || bytes.length > MAX_FILE_BYTES) throw new BusinessException("附件大小无效", 400); requireUploadCapacity(userId, bytes.length); - // No database transaction spans this network call. A timeout after the provider - // accepted the bytes has an unknown outcome, so it is surfaced and never retried - // automatically. A later local save failure can leave a provider-side orphan. - String fileCode = client.upload(name, contentType, bytes); - ReimAttachment row = ReimAttachment.builder().fileName(name).fileType("attachment") - .fileSize((long)bytes.length).contentType(contentType).uploaderId(userId) - .formControlId(control.getId()).formFingerprint(fingerprint) - .feishuFileCode(fileCode).uploadStatus(UPLOADED).build(); - return dto(attachments.save(row)); + String objectKey = objectKeys.randomKey("reimbursement/attachments", name); + StoredObject storedObject = new StoredObject(fileStorage.activeProviderCode(), objectKey); + ReimAttachment staged = createPersistingRow(name, contentType, bytes.length, userId, + fingerprint, control.getId(), storedObject); + try { + fileStorage.put(objectKey, contentType, bytes); + String fileCode = client.upload(name, contentType, bytes); + return finalizeUpload(staged.getId(), userId, fileCode); + } catch (RuntimeException failure) { + // The durable PERSISTING row is created before either remote call. If a remote + // call or final commit has an unknown outcome, the stale-upload scanner decides + // from committed database state whether cleanup is safe. Never delete here. + log.error("附件上传未完成,持久化记录将由清理任务核对: attachmentId={}, provider={}, objectKey={}", + staged.getId(), storedObject.getProvider(), storedObject.getObjectKey(), failure); + throw failure; + } } finally { uploadsInProgress.remove(userId); } } + private ReimAttachment createPersistingRow(String name, String contentType, int byteLength, + Long userId, String fingerprint, String controlId, + StoredObject storedObject) { + ReimAttachment staged = transactions.execute(status -> attachments.saveAndFlush( + ReimAttachment.builder().fileName(name).fileType("attachment") + .fileSize((long) byteLength).contentType(contentType).uploaderId(userId) + .formControlId(controlId).formFingerprint(fingerprint) + .storageProvider(storedObject.getProvider()) + .storageObjectKey(storedObject.getObjectKey()) + .uploadStatus(PERSISTING).build())); + if (staged == null || staged.getId() == null) throw new BusinessException("附件上传记录创建失败", 500); + return staged; + } + + private AttachmentDto finalizeUpload(Long attachmentId, Long userId, String fileCode) { + try { + AttachmentDto result = transactions.execute(status -> { + ReimAttachment row = attachments.findByIdForUpdate(attachmentId) + .orElseThrow(() -> new ResourceNotFoundException("附件上传记录不存在")); + if (!PERSISTING.equals(row.getUploadStatus())) + throw new BusinessException("附件上传状态已变化,请重新上传", 409); + row.setFeishuFileCode(fileCode); + row.setUploadStatus(UPLOADED); + ReimAttachment saved = attachments.saveAndFlush(row); + if (financeAudit != null) financeAudit.business("reimbursement.attachment.upload", userId, + "REIM_ATTACHMENT", saved.getId(), null, null, null); + return dto(saved); + }); + if (result == null) throw new BusinessException("附件上传记录保存失败", 500); + return result; + } catch (RuntimeException commitFailure) { + // A commit can succeed even when the client loses the acknowledgement. Re-read the + // authoritative row before reporting failure, and never compensate-delete blindly. + ReimAttachment committed = attachments.findById(attachmentId).orElse(null); + if (committed != null && UPLOADED.equals(committed.getUploadStatus()) + && fileCode.equals(committed.getFeishuFileCode())) { + log.warn("附件上传提交确认异常,但数据库已确认成功: attachmentId={}", attachmentId); + return dto(committed); + } + throw commitFailure; + } + } + private void requireStagedCapacity(Long userId, long incomingBytes) { long count = attachments.countByUploaderIdAndApplicationIdIsNullAndUploadStatus(userId, UPLOADED); Long stored = attachments.sumStagedBytes(userId, UPLOADED); @@ -112,6 +180,9 @@ public class ReimbursementAttachmentService { tombstone(row); attachments.save(row); attachments.flush(); + storageCleanup.enqueue(row, "用户主动删除附件"); + if (financeAudit != null) financeAudit.business("reimbursement.attachment.delete", userId, + "REIM_ATTACHMENT", row.getId(), null, null, null); if (claimedApplication != null) { claimedApplication.setFeishuFormDisplayValues(forms.buildDisplayValues(claimedApplication)); applications.save(claimedApplication); @@ -177,6 +248,7 @@ public class ReimbursementAttachmentService { if (userId.equals(row.getUploaderId()) && !retained.contains(row.getId())) { tombstone(row); attachments.save(row); + storageCleanup.enqueue(row, "保存申请时移除附件"); } } diff --git a/src/main/java/com/finance/system/service/ReimbursementFormService.java b/src/main/java/com/finance/system/service/ReimbursementFormService.java index 6706948..a4d6254 100644 --- a/src/main/java/com/finance/system/service/ReimbursementFormService.java +++ b/src/main/java/com/finance/system/service/ReimbursementFormService.java @@ -36,6 +36,10 @@ public class ReimbursementFormService { private final ReimExpenseItemRepository expenseItems; private final ReimAttachmentRepository attachments; private final ApplicantDepartmentDirectoryRepository applicantDepartments; + @org.springframework.beans.factory.annotation.Value("${observability.tenant-id:default}") + private String deploymentTenant = "default"; + @org.springframework.beans.factory.annotation.Value("${observability.organization-id:1}") + private Long deploymentOrganizationId = 1L; /** * Must run in a read-only transaction so {@code form_schema} LOB is materialized @@ -74,6 +78,31 @@ public class ReimbursementFormService { catch (Exception e) { throw new BusinessException("动态表单值无法保存", 400); } } + /** Returns the canonical explicit applicant-department picker value, when supplied. */ + public Optional selectedApplicantDepartment(PinnedForm pinned) { + Optional applicantDepartment = applicantDepartmentField(pinned); + if (!applicantDepartment.isPresent()) return Optional.empty(); + Object selected = parseValues(pinned.getValues()).get(applicantDepartment.get().getValueKey()); + return selected instanceof String && StringUtils.hasText((String) selected) + ? Optional.of((String) selected) : Optional.empty(); + } + + public boolean usesApplicantDepartment(PinnedForm pinned) { + return applicantDepartmentField(pinned).isPresent(); + } + + private Optional applicantDepartmentField(PinnedForm pinned) { + if (pinned == null || !StringUtils.hasText(pinned.getFingerprint())) return Optional.empty(); + List applicantDepartments = parseSchema(pinned.getSchema()).stream() + .filter(field -> "APPLICANT_DEPARTMENT".equals(field.getBinding()) + && "DEPARTMENT".equals(field.getType())) + .collect(java.util.stream.Collectors.toList()); + if (applicantDepartments.size() > 1) { + throw new BusinessException("飞书表单包含重复的申请人部门控件", 409); + } + return applicantDepartments.stream().findFirst(); + } + /** Validates upload staging against the currently synchronized attachment child. */ public ReimbursementFormField requireCurrentAttachmentControl(String fingerprint, String controlId) { ReimbursementFormField field = requireCurrentAttachmentControl(fingerprint); @@ -753,25 +782,62 @@ public class ReimbursementFormService { } private Map selectedDepartmentSnapshot(ReimApplication app, ReimbursementFormField field, SysUser user) { + requireApplicantDeploymentBoundary(app, user); Object supplied = parseValues(app.getFeishuFormValues()).get(field.getValueKey()); - if (supplied instanceof String && StringUtils.hasText((String) supplied)) { - ApplicantDepartmentDirectoryRepository.DirectoryDepartment department = applicantDepartments - .findByOpenDepartmentId(((String) supplied).trim()) - .orElseThrow(() -> new BusinessException("所选部门不在当前飞书组织架构中: " + field.getLabel(), 400)); - Map value = new LinkedHashMap<>(); - value.put("open_department_ids", Collections.singletonList(department.getOpenDepartmentId())); - value.put("display_label", department.getDisplayLabel()); - return value; + String selected = supplied instanceof String && StringUtils.hasText((String) supplied) + ? exactDepartmentIdentifier((String) supplied, field) : null; + requireApplicantOpenId(user); + if (app.getDepartmentId() == null) { + throw new BusinessException("申请没有可用的本地部门,无法保存报销人所属部门", 409); + } + Optional boundOpenDepartment = applicantDepartments + .findBoundOpenDepartmentIdByLocalDepartment(app.getDepartmentId()); + ApplicantDepartmentDirectoryRepository.DirectoryDepartment department; + if (boundOpenDepartment.isPresent()) { + department = applicantDepartments.findPublishedEligibleNonRootMembershipByLocalDepartment( + user.getFeishuOpenId(), deploymentTenant, app.getDepartmentId()) + .orElseThrow(() -> new BusinessException( + "申请部门与申请人当前飞书目录部门不一致,请联系管理员处理", 409)); + if (selected != null && !selected.equals(department.getOpenDepartmentId())) { + throw new BusinessException("所选飞书部门与申请已保存部门不一致,请重新选择", 409); + } + } else { + // Legacy/manual compatibility boundary: preserve app.department_id + // as the local authorization owner. A current, eligible applicant + // membership drives only the immutable Feishu form snapshot; it + // must not create a global binding or mutate the historical app. + department = (selected == null + ? applicantDepartments.findPreferredPublishedEligibleNonRootByOpenId( + user.getFeishuOpenId(), deploymentTenant) + : applicantDepartments.findPublishedEligibleNonRootMembership( + user.getFeishuOpenId(), deploymentTenant, selected)) + .orElseThrow(() -> new BusinessException( + selected == null + ? "申请人没有当前飞书目录的非根部门绑定,无法保存报销人所属部门" + : "所选部门不属于申请人在当前飞书通讯录中的有效部门: " + field.getLabel(), + 400)); + } + return departmentSnapshot(department); + } + + private void requireApplicantDeploymentBoundary(ReimApplication app, SysUser user) { + if (app == null || user == null + || !Objects.equals(deploymentTenant, app.getTenantId()) + || !Objects.equals(deploymentTenant, user.getTenantId()) + || !Objects.equals(deploymentOrganizationId, user.getOrganizationId())) { + throw new BusinessException("申请人与申请不属于本部署组织,无法解析报销人所属部门", 403); } - return applicantDepartmentSnapshot(user); } private Map applicantDepartmentSnapshot(SysUser user) { - if (user == null || !StringUtils.hasText(user.getFeishuOpenId())) - throw new BusinessException("申请人未绑定飞书 open_id,无法解析报销人所属部门", 400); + requireApplicantOpenId(user); ApplicantDepartmentDirectoryRepository.DirectoryDepartment department = applicantDepartments - .findPreferredNonRootByOpenId(user.getFeishuOpenId().trim()) + .findPreferredPublishedEligibleNonRootByOpenId(user.getFeishuOpenId(), deploymentTenant) .orElseThrow(() -> new BusinessException("申请人没有当前飞书目录的非根部门绑定,无法保存报销人所属部门", 400)); + return departmentSnapshot(department); + } + private Map departmentSnapshot( + ApplicantDepartmentDirectoryRepository.DirectoryDepartment department) { String openDepartmentId = department.getOpenDepartmentId(); String label = department.getDisplayLabel(); if (!StringUtils.hasText(openDepartmentId) || openDepartmentId.length() > 64 @@ -783,6 +849,17 @@ public class ReimbursementFormService { value.put("display_label", label); return value; } + private String exactDepartmentIdentifier(String value, ReimbursementFormField field) { + if (!value.equals(value.trim()) || value.length() > 64) { + throw new BusinessException("所选部门标识无效: " + field.getLabel(), 400); + } + return value; + } + private void requireApplicantOpenId(SysUser user) { + if (user == null || !StringUtils.hasText(user.getFeishuOpenId()) + || !user.getFeishuOpenId().equals(user.getFeishuOpenId().trim())) + throw new BusinessException("申请人未绑定飞书 open_id,无法解析报销人所属部门", 400); + } private void validateApplicantContactSnapshot(Object value, int status) { if (!(value instanceof Map) || ((Map) value).size() > 3) throw new BusinessException("报销人联系人展示快照结构无效", status); diff --git a/src/main/java/com/finance/system/service/RoleService.java b/src/main/java/com/finance/system/service/RoleService.java index eaacb9c..1262e4b 100644 --- a/src/main/java/com/finance/system/service/RoleService.java +++ b/src/main/java/com/finance/system/service/RoleService.java @@ -1,6 +1,8 @@ package com.finance.system.service; import com.finance.system.entity.*; +import com.finance.system.audit.AuditEventCommand; +import com.finance.system.audit.AuditPort; import com.finance.system.dto.MemberCandidateDto; import com.finance.system.dto.MemberCandidatesResponse; import com.finance.system.dto.DirectoryIdentityDto; @@ -14,9 +16,11 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.finance.system.util.AuditUtil; +import com.finance.system.authorization.AuthorizationRoleProfileVersionRepository; import java.util.*; import java.util.stream.Collectors; +import java.time.Instant; /** Application service for database-backed roles, permissions and groups. */ @Service @@ -36,6 +40,8 @@ public class RoleService { private static final int MAX_CANDIDATE_RESULTS = 200; private static final int MAX_DIRECTORY_IDENTITIES_PER_BIND = 200; private static final int MAX_MEMBER_IDS_PER_BIND = 5_000; + private static final int ADMIN_PRIVILEGE_TIER = 80; + private static final int SUPER_ADMIN_PRIVILEGE_TIER = 100; private final SysRoleRepository roles; private final SysPermissionRepository permissions; @@ -51,6 +57,10 @@ public class RoleService { private JdbcTemplate jdbc; @Autowired(required = false) private com.finance.system.adapter.feishu.FeishuDirectoryBindingProvisioner directoryBindingProvisioner; + @Autowired + private AuditPort auditPort; + @Autowired + private AuthorizationRoleProfileVersionRepository roleProfileVersions; public RoleService(SysRoleRepository roles, SysPermissionRepository permissions, SysRolePermissionRepository rolePermissions, SysUserRepository users, @@ -116,8 +126,9 @@ public class RoleService { if (id == null && roles.existsByRoleCode(code)) throw new BusinessException("角色编码已存在", 409); SysRole role = id == null ? new SysRole() : roles.findById(id) .orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + boolean superAdminActor = isSuperAdmin(actorId); String existingStatus = role.getStatus(); - if (id != null && Boolean.TRUE.equals(role.getBuiltIn()) && !isSuperAdmin(actorId)) { + if (id != null && Boolean.TRUE.equals(role.getBuiltIn()) && !superAdminActor) { throw new BusinessException("只有超级管理员可以修改内置角色", 403); } boolean privilegedBuiltIn = id != null && Boolean.TRUE.equals(role.getBuiltIn()) @@ -129,6 +140,11 @@ public class RoleService { if (id != null && Boolean.TRUE.equals(role.getBuiltIn()) && !code.equals(role.getRoleCode())) { throw new BusinessException("内置角色编码不可修改", 400); } + int requestedTier = requestedPrivilegeTier(body, role, code, superAdminActor); + if (!superAdminActor && (requestedTier >= ADMIN_PRIVILEGE_TIER + || ADMIN.equals(code) || SUPER_ADMIN.equals(code))) { + throw new BusinessException("普通管理员不能创建或修改管理员级角色", 403); + } role.setRoleCode(code); role.setRoleName(name); role.setDescription(text(body.get("description"))); @@ -142,14 +158,21 @@ public class RoleService { if (SUPER_ADMIN.equals(normalize(role.getRoleCode())) && "INACTIVE".equals(requestedStatus)) throw new BusinessException("超级管理员内置角色不可停用", 400); role.setStatus(requestedStatus); + role.setPrivilegeTier(requestedTier); if (role.getBuiltIn() == null) role.setBuiltIn(false); - return roles.save(role); + SysRole saved = roles.save(role); + auditIam(id == null ? "iam.role.create" : "iam.role.update", actorId, + "IAM_ROLE", saved.getId(), singletonAttribute("roleCode", saved.getRoleCode())); + return saved; } @Transactional public void deleteRole(Long id) { SysRole role = roles.findById(id).orElseThrow(() -> new ResourceNotFoundException("角色不存在")); if (Boolean.TRUE.equals(role.getBuiltIn())) throw new BusinessException("内置角色不可删除", 400); + if (isPrivilegedRole(role) && !isSuperAdmin(AuditUtil.getCurrentUserId())) { + throw new BusinessException("只有超级管理员可以删除管理员级角色", 403); + } if ((ADMIN.equals(role.getRoleCode()) || SUPER_ADMIN.equals(role.getRoleCode())) && countAdministratorAssignments(role.getId()) <= 1) { throw new BusinessException("不能删除最后一个管理员角色", 400); @@ -157,6 +180,8 @@ public class RoleService { rolePermissions.deleteByIdRoleId(id); groupRoles.deleteByIdRoleId(id); roles.delete(role); + auditIam("iam.role.delete", AuditUtil.getCurrentUserId(), "IAM_ROLE", id, + singletonAttribute("roleCode", role.getRoleCode())); } @Transactional(readOnly = true) @@ -168,8 +193,12 @@ public class RoleService { item.put("name", permission.getPermissionName()); item.put("type", permission.getPermissionType()); item.put("parentCode", permission.getParentCode()); + item.put("layer", permission.getPermissionLayer()); + item.put("sortOrder", permission.getSortOrder()); item.put("resource", permission.getResource()); item.put("defaultAccess", permission.getDefaultAccess()); + item.put("delegable", permission.getDelegable()); + item.put("riskLevel", permission.getRiskLevel()); result.add(item); } return result; @@ -221,6 +250,12 @@ public class RoleService { if (!superAdmin && Boolean.TRUE.equals(targetRole.getBuiltIn())) { throw new BusinessException("普通管理员不能修改内置角色权限", 403); } + if (!superAdmin && isPrivilegedRole(targetRole)) { + throw new BusinessException("只有超级管理员可以修改管理员级角色权限", 403); + } + if (!superAdmin && activeExplicitRoleIds(actorId).contains(roleId)) { + throw new BusinessException("不能修改授予当前操作者自身的角色权限", 403); + } if (body == null) throw new BusinessException("权限请求不能为空", 400); validatePermissionPayload(body); Map catalog = permissions.findAll().stream() @@ -240,6 +275,72 @@ public class RoleService { replacements.add(new SysRolePermission(roleId, catalog.get(entry.getKey()).getId(), entry.getValue())); } if (!replacements.isEmpty()) rolePermissions.saveAll(replacements); + Map attributes = new LinkedHashMap<>(); + attributes.put("roleCode", targetRole.getRoleCode()); + attributes.put("policyCount", replacements.size()); + auditIam("iam.role.permission.update", actorId, "IAM_ROLE", roleId, attributes); + if (roleProfileVersions != null) roleProfileVersions.bumpRoleVersion(roleId); + } + + /** + * Atomic authorization-profile write path. Unlike the legacy tree editor this + * method deliberately does not infer parent grants: page visibility, fields, + * and business buttons are independent layers and remain default-deny. + */ + @Transactional + public void replaceRoleProfilePermissions(Long roleId, Map permissionAccess, Long actorId) { + SysRole targetRole = roles.findByIdForUpdate(roleId) + .orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + boolean superAdmin = isSuperAdmin(actorId); + if (!superAdmin && !hasEditPermission(actorId, "system.role.permission.configure")) + throw new BusinessException("无权管理角色权限", 403); + if (!superAdmin && Boolean.TRUE.equals(targetRole.getBuiltIn())) + throw new BusinessException("普通管理员不能修改内置角色权限", 403); + if (!superAdmin && isPrivilegedRole(targetRole)) + throw new BusinessException("只有超级管理员可以修改管理员级角色权限", 403); + if (!superAdmin && activeExplicitRoleIds(actorId).contains(roleId)) + throw new BusinessException("不能修改授予当前操作者自身的角色权限", 403); + if (permissionAccess == null) throw new BusinessException("permissionAccess不能为空", 400); + + Map catalog = permissions.findAll().stream() + .collect(Collectors.toMap(SysPermission::getPermissionCode, p -> p)); + if (!permissionAccess.keySet().equals(catalog.keySet())) + throw new BusinessException("permissionAccess必须包含完整权限目录", 400); + LinkedHashMap requested = new LinkedHashMap<>(); + for (Map.Entry entry : permissionAccess.entrySet()) { + SysPermission permission = catalog.get(entry.getKey()); + String level = normalizedAccess(entry.getValue()); + if (permission == null || level == null) throw new BusinessException("权限档案包含无效项目", 400); + validateLayerAccess(permission, level); + requested.put(entry.getKey(), level); + } + addReadableAncestors(requested, catalog); + for (Map.Entry entry : requested.entrySet()) { + if (!superAdmin && !canDelegatePermission(actorId, catalog.get(entry.getKey()), entry.getValue())) + throw new BusinessException("不能授予超出操作者自身有效权限的权限", 403); + } + rolePermissions.deleteByIdRoleId(roleId); + List replacements = new ArrayList<>(); + for (Map.Entry entry : requested.entrySet()) { + if (!"HIDDEN".equals(entry.getValue())) + replacements.add(new SysRolePermission(roleId, catalog.get(entry.getKey()).getId(), entry.getValue())); + } + if (!replacements.isEmpty()) rolePermissions.saveAll(replacements); + Map attributes = new LinkedHashMap<>(); + attributes.put("roleCode", targetRole.getRoleCode()); + attributes.put("permissionCount", replacements.size()); + auditIam("iam.role.authorization-profile.update", actorId, "IAM_ROLE", roleId, attributes); + } + + private void validateLayerAccess(SysPermission permission, String level) { + String layer = permission.getPermissionLayer() == null + ? "COMPAT" : permission.getPermissionLayer().trim().toUpperCase(Locale.ROOT); + if (("MENU".equals(layer) || "PAGE".equals(layer) || "LIST_FIELD".equals(layer) + || "DIALOG".equals(layer)) && "EDIT".equals(level)) { + throw new BusinessException("菜单、页面、列表字段和弹窗仅支持HIDDEN或READ", 400); + } + // Buttons/actions deliberately keep READ as a visibility-only state. + // Mutating endpoints and enabled controls must still require EDIT. } @Transactional(readOnly = true) @@ -445,6 +546,7 @@ public class RoleService { @Transactional public SysUserGroup saveGroup(Long id, Map body) { + Long actorId = AuditUtil.getCurrentUserId(); String code = requiredCode(body, "groupCode"); String name = requiredText(body, "groupName"); if (id == null && groups.existsByGroupCode(code)) throw new BusinessException("用户组编码已存在", 409); @@ -454,7 +556,7 @@ public class RoleService { throw new BusinessException("默认用户组不可修改", 409); } boolean privileged = id != null && containsPrivilegedGroupRole(id); - if (privileged && !isSuperAdmin(AuditUtil.getCurrentUserId())) + if (privileged && !isSuperAdmin(actorId)) throw new BusinessException("只有超级管理员可以修改管理员用户组", 403); if (id != null && !code.equals(group.getGroupCode()) && groups.existsByGroupCode(code)) { throw new BusinessException("用户组编码已存在", 409); @@ -463,26 +565,31 @@ public class RoleService { if (id != null && !isActiveStatus(group.getStatus()) && "ACTIVE".equals(requestedStatus)) { Set assigned = groupRoleIdSet(id); validateRoleIds(assigned); - validateDelegatedRolesFromExplicitGroups(AuditUtil.getCurrentUserId(), assigned); + validateDelegatedRolesFromExplicitGroups(actorId, assigned); } group.setGroupCode(code); group.setGroupName(name); group.setDescription(text(body.get("description"))); group.setStatus(requestedStatus); if (group.getBuiltIn() == null) group.setBuiltIn(false); SysUserGroup saved = groups.save(group); if (privileged && "INACTIVE".equalsIgnoreCase(saved.getStatus())) ensureActiveSuperAdminRemains(); + auditIam(id == null ? "iam.group.create" : "iam.group.update", actorId, + "IAM_GROUP", saved.getId(), singletonAttribute("groupCode", saved.getGroupCode())); return saved; } @Transactional public void deleteGroup(Long id) { + Long actorId = AuditUtil.getCurrentUserId(); lockPrivilegeChanges(); SysUserGroup target = requireGroupForUpdate(id); if (isDefaultGroup(target)) throw new BusinessException("默认用户组不可删除", 409); boolean privileged = containsPrivilegedGroupRole(id); - if (privileged && !isSuperAdmin(AuditUtil.getCurrentUserId())) + if (privileged && !isSuperAdmin(actorId)) throw new BusinessException("只有超级管理员可以删除管理员用户组", 403); members.deleteByIdGroupId(id); groupRoles.deleteByIdGroupId(id); groups.deleteById(id); if (privileged) ensureActiveSuperAdminRemains(); + auditIam("iam.group.delete", actorId, "IAM_GROUP", id, + singletonAttribute("groupCode", target.getGroupCode())); } @Transactional(readOnly = true) @@ -492,6 +599,66 @@ public class RoleService { .orElseThrow(() -> new BusinessException("内置 EMPLOYEE 角色不存在", 409)).getId()); return safe(groupRoles.findByIdGroupId(id)).stream().map(x -> x.getId().getRoleId()).collect(Collectors.toList()); } + + @Transactional(readOnly = true) + public List roleGroupIds(Long id) { + SysRole role = requireRole(id); + Set result = new TreeSet<>(); + for (SysUserGroupRole assignment : safe(groupRoles.findByIdRoleId(id))) { + if (assignment.getId() != null && assignment.getId().getGroupId() != null) { + result.add(assignment.getId().getGroupId()); + } + } + if (EMPLOYEE.equals(normalize(role.getRoleCode()))) { + groups.findByGroupCode(DEFAULT_EMPLOYEE_GROUP).ifPresent(group -> result.add(group.getId())); + } + return new ArrayList<>(result); + } + + @Transactional + public void replaceRoleGroups(Long id, Collection groupIds, Collection expectedGroupIds, Long actorId) { + if (groupIds == null || expectedGroupIds == null) throw new BusinessException("必须提供用户组和原始用户组列表", 400); + lockPrivilegeChanges(); + SysRole role = roles.findByIdForUpdate(id).orElseThrow(() -> new ResourceNotFoundException("角色不存在")); + if (!isActiveStatus(role.getStatus())) throw new BusinessException("只能绑定启用角色", 400); + Set requested = strictMemberIds(groupIds, "groupIds"); + Set expected = strictMemberIds(expectedGroupIds, "expectedGroupIds"); + Set current = new LinkedHashSet<>(roleGroupIds(id)); + if (!current.equals(expected)) throw new BusinessException("角色用户组已被其他管理员修改,请刷新后重试", 409); + Set added = new LinkedHashSet<>(requested); + added.removeAll(current); + if (!isActiveStatus(role.getStatus()) && !added.isEmpty()) throw new BusinessException("停用角色不能新增用户组授权", 400); + SysUserGroup defaultGroup = groups.findByGroupCode(DEFAULT_EMPLOYEE_GROUP).orElse(null); + if (EMPLOYEE.equals(normalize(role.getRoleCode())) + && (defaultGroup == null || !requested.contains(defaultGroup.getId()))) { + throw new BusinessException("EMPLOYEE 角色必须包含默认用户组", 409); + } + Set affected = new TreeSet<>(current); + affected.addAll(requested); + boolean superAdmin = isSuperAdmin(actorId); + if (isPrivilegedRole(role) && !superAdmin) throw new BusinessException("只有超级管理员可以变更管理员角色用户组", 403); + if (!added.isEmpty()) { + validateDelegatedRoles(actorId, Collections.singleton(id)); + ensurePrivilegedRoleDelegation(actorId, null, Collections.singleton(id)); + } + for (Long groupId : affected) { + SysUserGroup group = requireGroupForUpdate(groupId); + if (added.contains(groupId) && !isActiveStatus(group.getStatus())) throw new BusinessException("只能绑定启用用户组", 400); + if (isDefaultGroup(group)) { + if (requested.contains(groupId) && !EMPLOYEE.equals(normalize(role.getRoleCode()))) + throw new BusinessException("默认用户组角色固定为 EMPLOYEE", 409); + continue; + } + if (current.contains(groupId) == requested.contains(groupId)) continue; + if (!superAdmin && containsPrivilegedGroupRole(groupId)) throw new BusinessException("只有超级管理员可以变更管理员用户组角色", 403); + SysUserGroupRole assignment = new SysUserGroupRole(groupId, id); + if (requested.contains(groupId)) groupRoles.save(assignment); + else groupRoles.deleteById(assignment.getId()); + auditIam("iam.group.role.update", actorId, "IAM_GROUP", groupId, + singletonAttribute("roleCount", groupRoleIdSet(groupId).size())); + } + if (isPrivilegedRole(role)) ensureActiveSuperAdminRemains(); + } @Transactional(readOnly = true) public List groupMemberIds(Long id) { SysUserGroup group = requireGroup(id); @@ -543,6 +710,8 @@ public class RoleService { ensurePrivilegedRoleDelegation(actorId, null, ids); groupRoles.deleteByIdGroupId(id); for (Long roleId : ids) groupRoles.save(new SysUserGroupRole(id, roleId)); if (hadPrivileged || requestsPrivileged) ensureActiveSuperAdminRemains(); + auditIam("iam.group.role.update", actorId, "IAM_GROUP", id, + singletonAttribute("roleCount", ids.size())); } @Transactional @@ -577,15 +746,7 @@ public class RoleService { .map(assignment -> assignment.getId().getRoleId()) .collect(Collectors.toList()); validateDelegatedRoles(actorId, assignedRoleIds); - boolean privilegedGroup = false; - for (Long roleId : assignedRoleIds) { - SysRole role = requireRole(roleId); - String code = normalize(role.getRoleCode()); - if (ADMIN.equals(code) || SUPER_ADMIN.equals(code)) { - privilegedGroup = true; - break; - } - } + boolean privilegedGroup = containsPrivilegedRole(assignedRoleIds); if (privilegedGroup && !isSuperAdmin(actorId)) { throw new BusinessException("只有超级管理员可以管理管理员用户组成员", 403); } @@ -616,6 +777,8 @@ public class RoleService { throw new BusinessException("用户已属于其他用户组", 409); } if (privilegedGroup) ensureActiveSuperAdminRemains(); + auditIam("iam.group.member.update", actorId, "IAM_GROUP", id, + singletonAttribute("memberCount", ids.size())); } /** @@ -687,6 +850,8 @@ public class RoleService { throw new BusinessException("用户已属于其他用户组", 409); } if (privilegedGroup) ensureActiveSuperAdminRemains(); + auditIam("iam.group.member.update", actorId, "IAM_GROUP", id, + singletonAttribute("memberCount", committed.size())); return new ArrayList<>(committed); } @@ -697,7 +862,7 @@ public class RoleService { .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); String normalizedStatus = status(requestedStatus); Set targetRoleIds = activeExplicitRoleIds(userId); - boolean privileged = containsRoleCode(targetRoleIds, ADMIN) || containsRoleCode(targetRoleIds, SUPER_ADMIN); + boolean privileged = containsPrivilegedRole(targetRoleIds); if (privileged && !hasActiveExplicitRole(actorId, SUPER_ADMIN)) { throw new BusinessException("只有超级管理员可以变更管理员状态", 403); } @@ -711,6 +876,8 @@ public class RoleService { user.setStatus(normalizedStatus); users.save(user); if (privileged && "INACTIVE".equals(normalizedStatus)) ensureActiveSuperAdminRemains(); + auditIam("iam.user.status.update", actorId, "IAM_USER", userId, + singletonAttribute("statusCode", normalizedStatus)); return user; } @@ -906,15 +1073,7 @@ public class RoleService { private long countAdministratorAssignments(Long roleId) { return groupRoles.countByIdRoleId(roleId); } private void ensurePrivilegedRoleDelegation(Long actorId, Long targetUserId, Collection roleIds) { - boolean privileged = false; - for (Long roleId : roleIds) { - SysRole role = requireRole(roleId); - String code = normalize(role.getRoleCode()); - if (ADMIN.equals(code) || SUPER_ADMIN.equals(code)) { - privileged = true; - break; - } - } + boolean privileged = containsPrivilegedRole(roleIds); if (!privileged) return; if (!isSuperAdmin(actorId)) { throw new BusinessException("只有超级管理员可以授予管理员角色", 403); @@ -964,11 +1123,19 @@ public class RoleService { } private boolean containsPrivilegedRole(Collection roleIds) { for (Long roleId : roleIds) { - String code = normalize(requireRole(roleId).getRoleCode()); - if (ADMIN.equals(code) || SUPER_ADMIN.equals(code)) return true; + if (isPrivilegedRole(requireRole(roleId))) return true; } return false; } + + private boolean isPrivilegedRole(SysRole role) { + if (role == null) return false; + String code = normalize(role.getRoleCode()); + int tier = role.getPrivilegeTier() == null + ? (SUPER_ADMIN.equals(code) ? SUPER_ADMIN_PRIVILEGE_TIER : ADMIN.equals(code) ? ADMIN_PRIVILEGE_TIER : 10) + : role.getPrivilegeTier(); + return tier >= ADMIN_PRIVILEGE_TIER || ADMIN.equals(code) || SUPER_ADMIN.equals(code); + } private boolean containsPrivilegedGroupRole(Long groupId) { for (SysUserGroupRole assignment : safe(groupRoles.findByIdGroupId(groupId))) { if (assignment.getId() != null @@ -998,8 +1165,10 @@ public class RoleService { roles.findByRoleCodeForUpdate(SUPER_ADMIN); } private boolean canDelegatePermission(Long actorId, SysPermission permission, String requestedAccess) { + if (permission == null) return false; String code = permission.getPermissionCode(); if ("HIDDEN".equals(requestedAccess)) return true; + if (Boolean.FALSE.equals(permission.getDelegable())) return false; String effective = "FIELD".equals(permission.getPermissionType()) ? fieldAccess(actorId, code) : permissionAccess(actorId, code); return accessRank(effective) >= accessRank(requestedAccess); @@ -1049,6 +1218,9 @@ public class RoleService { if (permission == null || !ACCESS_LEVELS.contains(assignment.getAccessLevel())) { throw new BusinessException("角色包含无效权限,不能启用", 403); } + if (Boolean.FALSE.equals(permission.getDelegable())) { + throw new BusinessException("角色包含不可委派权限,不能启用", 403); + } if (EMPLOYEE.equals(normalize(role.getRoleCode())) && SAFE_EMPLOYEE_PERMISSIONS.contains(permission.getPermissionCode())) continue; if (accessRank(actorAccess.get(permission.getPermissionCode())) @@ -1159,7 +1331,7 @@ public class RoleService { private SysUserGroup requireGroupForUpdate(Long id) { return groups.findByIdForUpdate(id).orElseThrow(() -> new ResourceNotFoundException("用户组不存在")); } private SysUser requireUser(Long id) { return users.findById(id).orElseThrow(() -> new ResourceNotFoundException("用户不存在")); } private void validateRoleIds(Collection ids) { for (Long id : ids) { SysRole r = requireRole(id); if (!isActiveStatus(r.getStatus())) throw new BusinessException("只能绑定启用角色", 400); } } - private Map roleMap(SysRole r) { Map x = new LinkedHashMap<>(); x.put("id", r.getId()); x.put("roleCode", r.getRoleCode()); x.put("roleName", r.getRoleName()); x.put("description", r.getDescription()); x.put("status", r.getStatus()); x.put("builtIn", r.getBuiltIn()); return x; } + private Map roleMap(SysRole r) { Map x = new LinkedHashMap<>(); x.put("id", r.getId()); x.put("roleCode", r.getRoleCode()); x.put("roleName", r.getRoleName()); x.put("description", r.getDescription()); x.put("status", r.getStatus()); x.put("builtIn", r.getBuiltIn()); x.put("privilegeTier", r.getPrivilegeTier()); return x; } private Map groupMap(SysUserGroup g) { Map x = new LinkedHashMap<>(); x.put("id", g.getId()); x.put("groupCode", g.getGroupCode()); x.put("groupName", g.getGroupName()); x.put("description", g.getDescription()); x.put("status", g.getStatus()); x.put("builtIn", Boolean.TRUE.equals(g.getBuiltIn())); return x; } private Map permissionMap(List assignments) { Set ids = assignments.stream().filter(x -> x.getId() != null).map(x -> x.getId().getPermissionId()).collect(Collectors.toSet()); return permissions.findAllById(ids).stream().collect(Collectors.toMap(SysPermission::getId, x -> x)); } private String stronger(String a, String b) { return "EDIT".equals(a) || "EDIT".equals(b) ? "EDIT" : "READ"; } @@ -1272,6 +1444,48 @@ public class RoleService { String normalized = value.trim().toUpperCase(Locale.ROOT); return ACCESS_LEVELS.contains(normalized) ? normalized : null; } + + private int requestedPrivilegeTier(Map body, SysRole role, String requestedCode, boolean superAdminActor) { + int current = role.getPrivilegeTier() == null ? 10 : role.getPrivilegeTier(); + Object raw = body == null ? null : body.get("privilegeTier"); + if (raw == null) { + String code = normalize(requestedCode); + if (SUPER_ADMIN.equals(code)) return SUPER_ADMIN_PRIVILEGE_TIER; + if (ADMIN.equals(code)) return ADMIN_PRIVILEGE_TIER; + return current; + } + if (!(raw instanceof Number)) throw new BusinessException("privilegeTier必须是整数", 400); + int requested = ((Number) raw).intValue(); + if (requested < 1 || requested > SUPER_ADMIN_PRIVILEGE_TIER) { + throw new BusinessException("privilegeTier范围必须是1到100", 400); + } + if (!superAdminActor && requested != current) { + throw new BusinessException("只有超级管理员可以变更角色特权层级", 403); + } + return requested; + } + + private Map singletonAttribute(String key, Object value) { + Map attributes = new LinkedHashMap<>(); + attributes.put(key, value); + return attributes; + } + + /** AuditPort persists to the transactional outbox; any validation/write failure rolls back the IAM mutation. */ + private void auditIam(String action, Long actorId, String resourceType, Long resourceId, + Map attributes) { + if (auditPort == null) return; + auditPort.emit(AuditEventCommand.builder() + .eventTime(Instant.now()).tenantId("default").category("ADMIN") + .action(action).outcome("SUCCESS") + .actorType(actorId == null ? "SYSTEM" : "USER").actorId(actorId) + .targetType(resourceType).targetId(String.valueOf(resourceId)) + .resourceType(resourceType).resourceId(String.valueOf(resourceId)) + .source(actorId == null ? "INTERNAL" : "WEB") + .changes(Collections.emptyMap()) + .attributes(attributes == null ? Collections.emptyMap() : attributes) + .build()); + } private String requiredCode(Map body, String key) { String value = requiredText(body, key); if (!value.matches("[A-Za-z0-9:_-]{2,80}")) throw new BusinessException("编码格式不正确", 400); return value.toUpperCase(Locale.ROOT); } private String requiredText(Map body, String key) { String x = text(body.get(key)); if (!StringUtils.hasText(x)) throw new BusinessException(key + "不能为空", 400); return x.trim(); } private String text(Object x) { return x == null ? null : String.valueOf(x); } diff --git a/src/main/java/com/finance/system/service/ScheduledTaskPoller.java b/src/main/java/com/finance/system/service/ScheduledTaskPoller.java index f9939f4..b705abb 100644 --- a/src/main/java/com/finance/system/service/ScheduledTaskPoller.java +++ b/src/main/java/com/finance/system/service/ScheduledTaskPoller.java @@ -17,7 +17,7 @@ public class ScheduledTaskPoller { try { tasks.claimDue(); } catch (RuntimeException failure) { - log.warn("Scheduled task poll failed", failure); + log.warn("定时任务轮询失败", failure); } } } diff --git a/src/main/java/com/finance/system/service/ScheduledTaskService.java b/src/main/java/com/finance/system/service/ScheduledTaskService.java index 9746464..3abe79e 100644 --- a/src/main/java/com/finance/system/service/ScheduledTaskService.java +++ b/src/main/java/com/finance/system/service/ScheduledTaskService.java @@ -5,7 +5,9 @@ import com.finance.system.adapter.feishu.FeishuDirectoryService; import com.finance.system.adapter.feishu.FeishuDirectorySyncDispatcher; import com.finance.system.dto.ScheduledTaskRunDto; import com.finance.system.exception.BusinessException; +import com.finance.system.integration.audit.IntegrationAuditEvents; import lombok.Data; +import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; @@ -34,27 +36,33 @@ public class ScheduledTaskService { private final FeishuDirectoryRunStore runs; private final FeishuDirectorySyncDispatcher dispatcher; private final TransactionTemplate tx; + private final IntegrationAuditEvents auditEvents; + @Value("${observability.tenant-id:default}") + private String systemTenant = "default"; public ScheduledTaskService(JdbcTemplate jdbc, PlatformTransactionManager manager, - FeishuDirectoryRunStore runs, FeishuDirectorySyncDispatcher dispatcher) { + FeishuDirectoryRunStore runs, FeishuDirectorySyncDispatcher dispatcher, + IntegrationAuditEvents auditEvents) { this.jdbc = jdbc; this.runs = runs; this.dispatcher = dispatcher; + this.auditEvents = auditEvents; this.tx = new TransactionTemplate(manager); this.tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); this.tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); this.tx.setTimeout(10); } - public List> list() { - return Collections.singletonList(detail(FEISHU)); + public List> list(String tenantId) { + return Collections.singletonList(detail(FEISHU, tenantId)); } - public Map detail(String code) { + public Map detail(String code, String tenantId) { requireCode(code); + String tenant = tenant(tenantId); Map row = jdbc.queryForMap( "SELECT task_code,display_name,enabled,interval_hours,time_zone,next_due_at,last_claimed_at,version,updated_at " - + "FROM sys_scheduled_task WHERE task_code=?", code); + + "FROM sys_scheduled_task WHERE tenant_id=? AND task_code=?", tenant, code); Map result = new LinkedHashMap<>(); result.put("code", row.get("task_code")); result.put("name", row.get("display_name")); @@ -64,82 +72,123 @@ public class ScheduledTaskService { result.put("nextDueAt", instant(row.get("next_due_at"))); result.put("lastClaimedAt", instant(row.get("last_claimed_at"))); result.put("version", row.get("version")); - result.put("status", active() ? "RUNNING" : "IDLE"); + result.put("status", active(tenant) ? "RUNNING" : "IDLE"); return result; } - public Map update(String code, ScheduleRequest request) { + public Map update(String code, ScheduleRequest request, String tenantId, Long actorId) { requireCode(code); + String tenant = tenant(tenantId); if (request == null || request.version == null || request.enabled == null || request.intervalHours == null || !INTERVALS.contains(request.intervalHours)) { throw new BusinessException("Invalid schedule configuration", 400); } - tx.execute(status -> { - List> rows = jdbc.queryForList( - "SELECT enabled,version FROM sys_scheduled_task WHERE task_code=? FOR UPDATE", code); - if (rows.size() != 1 || ((Number) rows.get(0).get("version")).longValue() != request.version) { - throw new BusinessException("Schedule configuration changed; refresh and retry", 409); - } - boolean wasEnabled = bool(rows.get(0).get("enabled")); - long delay = !wasEnabled && request.enabled ? 60L : request.intervalHours * 3600L; - Timestamp now = databaseNow(); - Timestamp next = request.enabled ? Timestamp.from(now.toInstant().plusSeconds(delay)) : null; - jdbc.update("UPDATE sys_scheduled_task SET enabled=?,interval_hours=?,next_due_at=?,version=version+1,updated_at=? WHERE task_code=?", - request.enabled, request.intervalHours, next, now, code); - return null; - }); - return detail(code); + try { + tx.execute(status -> { + List> rows = jdbc.queryForList( + "SELECT enabled,version FROM sys_scheduled_task WHERE tenant_id=? AND task_code=? FOR UPDATE", + tenant, code); + if (rows.size() != 1 || ((Number) rows.get(0).get("version")).longValue() != request.version) { + throw new BusinessException("Schedule configuration changed; refresh and retry", 409); + } + boolean wasEnabled = bool(rows.get(0).get("enabled")); + long delay = !wasEnabled && request.enabled ? 60L : request.intervalHours * 3600L; + Timestamp now = databaseNow(); + Timestamp next = request.enabled ? Timestamp.from(now.toInstant().plusSeconds(delay)) : null; + jdbc.update("UPDATE sys_scheduled_task SET enabled=?,interval_hours=?,next_due_at=?,version=version+1,updated_at=? WHERE tenant_id=? AND task_code=?", + request.enabled, request.intervalHours, next, now, tenant, code); + auditEvents.scheduled(tenant, actorId, "integration.schedule.update", code, null, + request.enabled ? "ENABLED" : "DISABLED", Arrays.asList("enabled", "intervalHours")); + return null; + }); + } catch (RuntimeException failure) { + auditEvents.scheduledFailed(tenant, actorId, "integration.schedule.update", code, null, + "SCHEDULE_UPDATE_FAILED"); + throw failure; + } + return detail(code, tenant); } - public ScheduledTaskRunDto execute(String code) { + public ScheduledTaskRunDto execute(String code, String tenantId, Long actorId) { requireCode(code); - FeishuDirectoryService.Run accepted = runs.enqueue("MANUAL"); - ScheduledTaskRunDto run = tx.execute(status -> loadPublicRun(accepted.getRunId())); + String tenant = tenant(tenantId); + detail(code, tenant); + ScheduledTaskRunDto run; + try { + run = tx.execute(status -> { + FeishuDirectoryService.Run accepted = runs.enqueueInCurrentTransaction("MANUAL", tenant); + ScheduledTaskRunDto queued = loadPublicRun(accepted.getRunId(), tenant); + auditEvents.scheduled(tenant, actorId, "integration.schedule.execute", code, + accepted.getRunId(), "QUEUED", Collections.emptyList()); + return queued; + }); + } catch (RuntimeException failure) { + auditEvents.scheduledFailed(tenant, actorId, "integration.schedule.execute", code, null, + "SCHEDULE_EXECUTE_FAILED"); + throw failure; + } dispatcher.wake(); return run; } /** Cluster-safe due claim. Advancing from DB now coalesces all downtime into one run. */ public boolean claimDue() { - Boolean queued = tx.execute(status -> { - List> rows = jdbc.queryForList( - "SELECT enabled,interval_hours,next_due_at FROM sys_scheduled_task WHERE task_code=? FOR UPDATE", FEISHU); - if (rows.isEmpty() || !bool(rows.get(0).get("enabled"))) return false; + final String tenant = tenant(systemTenant); + String runId; + try { + runId = tx.execute(status -> { + List> rows = jdbc.queryForList( + "SELECT enabled,interval_hours,next_due_at FROM sys_scheduled_task WHERE tenant_id=? AND task_code=? FOR UPDATE", + tenant, FEISHU); + if (rows.isEmpty() || !bool(rows.get(0).get("enabled"))) return null; - Timestamp now = databaseNow(); - Timestamp due = (Timestamp) rows.get(0).get("next_due_at"); - if (due != null && due.after(now)) return false; + Timestamp now = databaseNow(); + Timestamp due = (Timestamp) rows.get(0).get("next_due_at"); + if (due != null && due.after(now)) return null; - jdbc.queryForMap("SELECT id FROM feishu_directory_state WHERE id=1 FOR UPDATE"); - int hours = ((Number) rows.get(0).get("interval_hours")).intValue(); - Timestamp next = Timestamp.from(now.toInstant().plusSeconds(hours * 3600L)); - jdbc.update("UPDATE sys_scheduled_task SET next_due_at=?,last_claimed_at=?,version=version+1,updated_at=? WHERE task_code=?", - next, now, now, FEISHU); + jdbc.queryForMap("SELECT id FROM feishu_directory_state WHERE tenant_id=? AND id=1 FOR UPDATE", tenant); + int hours = ((Number) rows.get(0).get("interval_hours")).intValue(); + Timestamp next = Timestamp.from(now.toInstant().plusSeconds(hours * 3600L)); + jdbc.update("UPDATE sys_scheduled_task SET next_due_at=?,last_claimed_at=?,version=version+1,updated_at=? WHERE tenant_id=? AND task_code=?", + next, now, now, tenant, FEISHU); - Integer active = jdbc.queryForObject( - "SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class); - if (active != null && active > 0) return false; + Integer active = jdbc.queryForObject( + "SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", + Integer.class, tenant); + if (active != null && active > 0) return null; - jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger_type,state,queued_at,started_at,complete,applied) " - + "VALUES (?,'SCHEDULED','QUEUED',?,NULL,FALSE,FALSE)", - UUID.randomUUID().toString(), now); - return true; - }); - if (Boolean.TRUE.equals(queued)) dispatcher.wake(); - return Boolean.TRUE.equals(queued); + String claimedRunId = UUID.randomUUID().toString(); + jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,tenant_id,trigger_type,state,queued_at,started_at,complete,applied) " + + "VALUES (?,?,'SCHEDULED','QUEUED',?,NULL,FALSE,FALSE)", + claimedRunId, tenant, now); + auditEvents.scheduled(tenant, null, "integration.schedule.execute", FEISHU, + claimedRunId, "QUEUED", Collections.emptyList()); + return claimedRunId; + }); + } catch (RuntimeException failure) { + auditEvents.scheduledFailed(tenant, null, "integration.schedule.execute", FEISHU, null, + "SCHEDULE_CLAIM_FAILED"); + throw failure; + } + if (runId != null) dispatcher.wake(); + return runId != null; } - public Map runs(String code, int page, int size) { + public Map runs(String code, int page, int size, String tenantId) { requireCode(code); + String tenant = tenant(tenantId); if (page < 0 || size < 1 || size > 100 || page > Integer.MAX_VALUE / size) { throw new BusinessException("Invalid pagination", 400); } + detail(code, tenant); int offset = page * size; - Integer total = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run", Integer.class); + Integer total = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=?", + Integer.class, tenant); List items = new ArrayList<>(); List> rows = jdbc.queryForList( "SELECT " + RUN_COLUMNS - + " FROM feishu_directory_sync_run ORDER BY queued_at DESC,run_id DESC LIMIT ? OFFSET ?", size, offset); + + " FROM feishu_directory_sync_run WHERE tenant_id=? ORDER BY queued_at DESC,run_id DESC LIMIT ? OFFSET ?", + tenant, size, offset); for (Map row : rows) items.add(publicRun(row)); Map result = new LinkedHashMap<>(); @@ -150,9 +199,10 @@ public class ScheduledTaskService { return result; } - private ScheduledTaskRunDto loadPublicRun(String runId) { + private ScheduledTaskRunDto loadPublicRun(String runId, String tenantId) { return publicRun(jdbc.queryForMap( - "SELECT " + RUN_COLUMNS + " FROM feishu_directory_sync_run WHERE run_id=?", runId)); + "SELECT " + RUN_COLUMNS + " FROM feishu_directory_sync_run WHERE tenant_id=? AND run_id=?", + tenantId, runId)); } private ScheduledTaskRunDto publicRun(Map row) { @@ -177,14 +227,21 @@ public class ScheduledTaskService { counts.setIneligible(number(row.get("ineligible"))); counts.setOutOfScope(number(row.get("out_of_scope"))); result.setCounts(counts); - result.setErrorCode(row.get("error_code") == null ? null : String.valueOf(row.get("error_code"))); - result.setErrorMessage(sanitize(row.get("error_message"))); + result.setErrorCode(safeErrorCode(row.get("error_code"))); + result.setErrorMessage(null); return result; } - private boolean active() { + private static String safeErrorCode(Object value) { + if (value == null) return null; + String code = String.valueOf(value); + return code.matches("[A-Z0-9_]{1,80}") ? code : "SYNC_FAILED"; + } + + private boolean active(String tenantId) { Integer count = jdbc.queryForObject( - "SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class); + "SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", + Integer.class, tenantId); return count != null && count > 0; } @@ -214,6 +271,12 @@ public class ScheduledTaskService { if (!FEISHU.equals(code)) throw new BusinessException("Scheduled task not found", 404); } + private String tenant(String value) { + if (value == null || !value.matches("[A-Za-z0-9._-]{1,64}")) + throw new BusinessException("Invalid tenant boundary", 403); + return value; + } + @Data public static class ScheduleRequest { private Boolean enabled; diff --git a/src/main/java/com/finance/system/service/TravelApplicationService.java b/src/main/java/com/finance/system/service/TravelApplicationService.java new file mode 100644 index 0000000..e45cf68 --- /dev/null +++ b/src/main/java/com/finance/system/service/TravelApplicationService.java @@ -0,0 +1,63 @@ +package com.finance.system.service; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +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 org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class TravelApplicationService { + private static final TypeReference> STRING_LIST = new TypeReference>() { }; + private final FeishuTravelApplicationRepository repository; + private final ObjectMapper objectMapper; + + public TravelApplicationService(FeishuTravelApplicationRepository repository, ObjectMapper objectMapper) { + this.repository = repository; + this.objectMapper = objectMapper; + } + + @Transactional(readOnly = true) + public List mine(Long actorId) { + if (actorId == null) return Collections.emptyList(); + return repository.findByApplicantUserIdOrderByStartDateDescIdDesc(actorId).stream() + .map(this::toDto).collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public TravelApplicationDto mineById(Long actorId, Long id) { + if (actorId == null) throw new ResourceNotFoundException("出差申请不存在"); + return repository.findByIdAndApplicantUserId(id, actorId).map(this::toDto) + .orElseThrow(() -> new ResourceNotFoundException("出差申请不存在")); + } + + private TravelApplicationDto toDto(FeishuTravelApplication value) { + return TravelApplicationDto.builder().id(value.getId()) + .travelRequestNo(value.getTravelRequestNo()) + .approvalInstanceId(value.getApprovalInstanceId()) + .applicant(value.getApplicantName()).applicantCode(value.getApplicantCode()) + .travelerCodes(stringList(value.getTravelerCodes())) + .travelers(stringList(value.getTravelerNames())) + .entity(value.getLegalEntity()).department(value.getDepartment()) + .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(); + } + + private List stringList(String json) { + if (json == null || json.trim().isEmpty()) return Collections.emptyList(); + try { + return objectMapper.readValue(json, STRING_LIST); + } catch (Exception ignored) { + return Collections.emptyList(); + } + } +} diff --git a/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java b/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java index d766bfc..0ef3142 100644 --- a/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/DashboardServiceImpl.java @@ -6,16 +6,16 @@ import com.finance.system.entity.ReimApplication; import com.finance.system.entity.SysUser; import com.finance.system.entity.SysDepartment; import com.finance.system.entity.SysExpenseType; -import com.finance.system.enums.ApprovalStatus; -import com.finance.system.enums.PaymentStatus; import com.finance.system.repository.ReimApplicationRepository; import com.finance.system.repository.SysUserRepository; import com.finance.system.repository.SysDepartmentRepository; import com.finance.system.repository.SysExpenseTypeRepository; import com.finance.system.service.DashboardService; -import com.finance.system.service.RoleService; import com.finance.system.exception.UnauthorizedException; -import org.springframework.beans.factory.annotation.Autowired; +import com.finance.system.security.finance.FinanceAuthorization; +import com.finance.system.security.finance.FinanceFieldProjection; +import com.finance.system.security.finance.FinanceScope; +import org.springframework.data.domain.PageRequest; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -31,50 +31,23 @@ public class DashboardServiceImpl implements DashboardService { private final SysUserRepository sysUserRepository; private final SysDepartmentRepository sysDepartmentRepository; private final SysExpenseTypeRepository sysExpenseTypeRepository; - private RoleService roleService; - - @Autowired(required = false) - public void setRoleService(RoleService roleService) { this.roleService = roleService; } + private final FinanceAuthorization financeAuthorization; + private final FinanceFieldProjection financeProjection; @Override public DashboardStats getDashboardStats(Long userId) { if (userId == null) throw new UnauthorizedException("未登录"); - List applications; - - boolean viewAll = canViewAll(userId); - if (viewAll) { - // 财务人员查看所有申请 - applications = reimApplicationRepository.findAll(); - } else { - // 普通员工查看自己的申请 - applications = reimApplicationRepository.findByApplicantIdOrderByCreatedAtDesc(userId); - } - - long total = applications.size(); - long pendingApproval = applications.stream() - .filter(a -> ApprovalStatus.PENDING.name().equals(a.getApprovalStatus())) - .count(); - long approved = applications.stream() - .filter(a -> ApprovalStatus.APPROVED.name().equals(a.getApprovalStatus())) - .count(); - long rejected = applications.stream() - .filter(a -> ApprovalStatus.REJECTED.name().equals(a.getApprovalStatus())) - .count(); - long pendingPayment = applications.stream() - .filter(a -> PaymentStatus.UNPAID.name().equals(a.getPaymentStatus())) - .count(); - long unpaid = applications.stream() - .filter(a -> PaymentStatus.UNPAID.name().equals(a.getPaymentStatus()) - || PaymentStatus.PARTIAL.name().equals(a.getPaymentStatus())) - .count(); - - BigDecimal totalAmount = applications.stream() - .map(ReimApplication::getTotalAmount) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal paidAmount = applications.stream() - .filter(a -> PaymentStatus.PAID.name().equals(a.getPaymentStatus())) - .map(ReimApplication::getTotalAmount) - .reduce(BigDecimal.ZERO, BigDecimal::add); + FinanceScope access = financeAuthorization.scope(userId, "finance.dashboard", "read"); + Object[] aggregate = reimApplicationRepository.aggregateScoped(access.getTenantId(), access.code(), + access.getActorId(), access.getDepartmentIds()); + long total = number(aggregate, 0); + long pendingApproval = number(aggregate, 1); + long approved = number(aggregate, 2); + long rejected = number(aggregate, 3); + long pendingPayment = number(aggregate, 4); + long unpaid = number(aggregate, 5); + BigDecimal totalAmount = decimal(aggregate, 6); + BigDecimal paidAmount = decimal(aggregate, 7); BigDecimal pendingAmount = totalAmount.subtract(paidAmount); return DashboardStats.builder() @@ -93,39 +66,24 @@ public class DashboardServiceImpl implements DashboardService { @Override public List getRecentApplications(Long userId, int limit) { if (userId == null) throw new UnauthorizedException("未登录"); - List applications; - if (canViewAll(userId)) { - int safeLimit = Math.max(1, Math.min(limit, 100)); - applications = reimApplicationRepository.findAll().stream() - .sorted((left, right) -> { - if (left.getCreatedAt() == null) return right.getCreatedAt() == null ? 0 : 1; - if (right.getCreatedAt() == null) return -1; - return right.getCreatedAt().compareTo(left.getCreatedAt()); - }) - .limit(safeLimit).collect(Collectors.toList()); - } else { - applications = reimApplicationRepository.findFirst10ByApplicantIdOrderByCreatedAtDesc(userId); - } - - return applications.stream().map(this::buildSummary).collect(Collectors.toList()); + int safeLimit = Math.max(1, Math.min(limit, 100)); + FinanceScope access = financeAuthorization.scope(userId, "finance.dashboard", "read"); + return reimApplicationRepository.findScoped(access.getTenantId(), access.code(), access.getActorId(), + access.getDepartmentIds(), null, null, null, PageRequest.of(0, safeLimit)) + .map(app -> financeProjection.application(buildSummary(app), + financeAuthorization.checkApplication(userId, "finance.dashboard", "read", app))) + .getContent(); } - private boolean canViewAll(Long userId) { - if (roleService != null) { - return roleService.hasPermission(userId, "page.finance-receipt") - || roleService.hasPermission(userId, "page.source-documents") - || roleService.hasPermission(userId, "page.payments") - || roleService.hasPermission(userId, "finance.receipt.confirm") - || roleService.hasPermission(userId, "finance.approval.decide") - || roleService.hasPermission(userId, "finance.payment.register") - // Legacy codes remain during the RBAC migration window. - || roleService.hasPermission(userId, "reimbursement:view-all") - || roleService.hasPermission(userId, "receipt:manage") - || roleService.hasPermission(userId, "payment:register") - || roleService.hasPermission(userId, "approval:view"); - } - // Missing authorization infrastructure must never widen data scope. - return false; + private long number(Object[] values, int index) { + return values != null && values.length > index && values[index] instanceof Number + ? ((Number) values[index]).longValue() : 0L; + } + + private BigDecimal decimal(Object[] values, int index) { + Object value = values != null && values.length > index ? values[index] : null; + return value instanceof BigDecimal ? (BigDecimal) value + : (value instanceof Number ? new BigDecimal(value.toString()) : BigDecimal.ZERO); } private ReimApplicationSummary buildSummary(ReimApplication app) { diff --git a/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java index e9e0d57..8bb52d2 100644 --- a/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java @@ -9,7 +9,15 @@ import com.finance.system.repository.*; import com.finance.system.service.ReimApplicationService; import com.finance.system.service.RoleService; import com.finance.system.service.ReimbursementFormService; +import com.finance.system.service.ReimbursementApplicantDepartmentService; import com.finance.system.util.AuditUtil; +import com.finance.system.authorization.AuthorizationDecision; +import com.finance.system.authorization.FieldAccess; +import com.finance.system.authorization.SegregationOfDutiesEvaluator; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.security.finance.FinanceAuthorization; +import com.finance.system.security.finance.FinanceFieldProjection; +import com.finance.system.security.finance.FinanceScope; import com.finance.system.adapter.kingdee.KingdeeConfig; import com.finance.system.adapter.feishu.FeishuApprovalService; import lombok.RequiredArgsConstructor; @@ -21,6 +29,10 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.beans.factory.annotation.Autowired; +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.PersistenceContext; + import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; @@ -50,17 +62,19 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { private final KingdeeConfig kingdeeConfig; private final ReimbursementFormService reimbursementFormService; private final com.finance.system.service.ReimbursementAttachmentService reimbursementAttachmentService; - private RoleService roleService; + private final RoleService roleService; private FeishuApprovalService feishuApprovalService; private ReimbursementRoutePreviewService routePreviewService; private ReimbursementSubmissionCoordinator submissionCoordinator; private IntFeishuApprovalRepository feishuApprovalRepository; private FeishuInstanceTimelineNodeRepository timelineNodeRepository; - - @Autowired(required = false) - public void setRoleService(RoleService roleService) { - this.roleService = roleService; - } + private final FinanceAuthorization financeAuthorization; + private final FinanceFieldProjection financeProjection; + private final FinanceAuditEvents financeAudit; + private final SegregationOfDutiesEvaluator sodEvaluator; + private ReimbursementApplicantDepartmentService applicantDepartmentService; + @PersistenceContext + private EntityManager entityManager; @Autowired(required = false) public void setFeishuApprovalService(FeishuApprovalService feishuApprovalService) { @@ -87,14 +101,20 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { this.timelineNodeRepository = repository; } + @Autowired + public void setApplicantDepartmentService(ReimbursementApplicantDepartmentService service) { + this.applicantDepartmentService = service; + } + @Override @Transactional public RoutePreviewDto previewRoute(Long id, Long userId) { requireEditPermission(userId, "reimbursement.application.edit"); + FinanceScope access = scope(userId, "reimbursement.application", "edit"); // This application-row lock serializes concurrent token issuance and the // Phase-A create intent for the same reimbursement. - ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ReimApplication app = findScopedForUpdate(id, access); + checkApplication(userId, "reimbursement.application", "edit", app); ensureOwner(app, userId); if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { throw new BusinessException("只能预览可编辑草稿的审批路线", 409); @@ -120,9 +140,9 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override public List getRouteTimeline(Long id, Long userId) { requirePermission(userId, "page.applications", "page.application-edit", "page.finance-receipt"); - ReimApplication app = reimApplicationRepository.findById(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - ensureCanRead(app, userId); + FinanceScope access = scope(userId, "reimbursement.application", "read"); + ReimApplication app = findScoped(id, access); + checkApplication(userId, "reimbursement.application", "read", app); if (feishuApprovalRepository == null || timelineNodeRepository == null) return Collections.emptyList(); IntFeishuApproval mapping = feishuApprovalRepository.findByApplicationId(id).orElse(null); if (mapping == null || !org.springframework.util.StringUtils.hasText(mapping.getFeishuInstanceCode())) @@ -138,22 +158,34 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override @Transactional(readOnly = true) public WorkbenchDto getWorkbench(Long userId) { - requirePermission(userId, "page.dashboard", "page.applications", "page.application-create", - "page.application-edit", "page.finance-receipt", "page.payments"); + requirePermission(userId, "page.applications", "page.application-create", + "page.application-edit", "page.finance-receipt"); SysUser user = sysUserRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); - List applications = reimApplicationRepository - .findByApplicantIdOrderByCreatedAtDesc(userId); + FinanceScope access = scope(userId, "finance.dashboard", "read"); + List applications = reimApplicationRepository.findScopedForApplicant( + access.getTenantId(), access.code(), access.getActorId(), access.getDepartmentIds(), + userId, null, null, Pageable.unpaged()).getContent(); UserProfile userProfile = buildUserProfile(user); List summaries = applications.stream() - .map(this::buildSummary) + .map(app -> { + ReimApplicationSummary summary = projectSummary(buildSummary(app), + checkApplication(userId, "finance.dashboard", "read", app)); + summary.setAvailableActions(applicationActions(app, userId)); + return summary; + }) .collect(Collectors.toList()); - List payments = reimPaymentRepository.findByPayeeId(userId); + List payments = reimPaymentRepository.findScopedForApplicant(access.getTenantId(), + access.code(), access.getActorId(), access.getDepartmentIds(), userId); + java.util.Map applicationsById = applications.stream() + .collect(Collectors.toMap(ReimApplication::getId, app -> app)); List paymentDtos = payments.stream() - .map(this::buildPaymentRecord) + .map(payment -> financeProjection.payment(buildPaymentRecord(payment), + checkApplication(userId, "finance.dashboard", "read", + applicationsById.get(payment.getApplicationId())))) .collect(Collectors.toList()); DashboardStats stats = buildDashboardStats(userId, applications); @@ -169,60 +201,79 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override public Page getMyApplications(Long userId, String status, Pageable pageable) { requirePermission(userId, "page.applications"); - Page applications; + FinanceScope access = scope(userId, "reimbursement.application", "read"); + String applicationStatus = null; + String approvalStatus = null; if (status != null && !status.isEmpty() && !"ALL".equalsIgnoreCase(status)) { if (ApplicationStatus.DRAFT.name().equalsIgnoreCase(status)) { - applications = reimApplicationRepository.findByApplicantIdAndApplicationStatus( - userId, ApplicationStatus.DRAFT.name(), pageable); + applicationStatus = ApplicationStatus.DRAFT.name(); } else { - applications = reimApplicationRepository.findByApplicantIdAndApprovalStatus( - userId, status, pageable); + approvalStatus = status; } - } else { - applications = reimApplicationRepository.findByApplicantIdOrderByCreatedAtDesc(userId, pageable); } - return applications.map(this::buildSummary); + Page applications = reimApplicationRepository.findScopedForApplicant( + access.getTenantId(), access.code(), access.getActorId(), access.getDepartmentIds(), userId, + applicationStatus, approvalStatus, pageable); + return applications.map(app -> { + ReimApplicationSummary summary = projectSummary(buildSummary(app), + checkApplication(userId, "reimbursement.application", "read", app)); + summary.setAvailableActions(applicationActions(app, userId)); + return summary; + }); } @Override public ReimApplicationDetail getApplicationDetail(Long id, Long userId) { requirePermission(userId, "page.applications", "page.application-edit", "page.finance-receipt"); - ReimApplication app = reimApplicationRepository.findById(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - ensureCanRead(app, userId); - return buildDetail(app); + FinanceScope access = scope(userId, "reimbursement.application", "read"); + ReimApplication app = findScoped(id, access); + AuthorizationDecision decision = checkApplication(userId, "reimbursement.application", "read", app); + return projectDetailWithActions(app, userId, decision); } @Override public ReimApplicationDetail getByApplicationNo(String applicationNo, Long userId) { requirePermission(userId, "page.applications", "page.application-edit", "page.finance-receipt"); - ReimApplication app = reimApplicationRepository.findByApplicationNo(applicationNo); - if (app == null) { - throw new ResourceNotFoundException("报销申请不存在: " + applicationNo); - } - ensureCanRead(app, userId); - return buildDetail(app); + 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("报销申请不存在"); + AuthorizationDecision decision = checkApplication(userId, "reimbursement.application", "read", app); + return projectDetailWithActions(app, userId, decision); } @Override @Transactional public ReimApplicationDetail createApplication(CreateApplicationRequest request, Long userId) { requireEditPermission(userId, "reimbursement.application.create"); - SysUser user = sysUserRepository.findById(userId) + FinanceScope access = scope(userId, "reimbursement.application", "create"); + SysUser user = sysUserRepository.findByIdForUpdate(userId) .orElseThrow(() -> new ResourceNotFoundException("用户不存在")); + // scope/authorization may already have loaded this user into the current + // persistence context. The locking query then waits correctly but is not + // required by JPA to replace that managed instance's stale field values. + // 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); validateFieldPermissions(request, userId, null, true); validateRequest(request, userId); ReimbursementFormService.PinnedForm pinnedForm = reimbursementFormService.validateForWrite( request.getFormFingerprint(), request.getFormValues()); + String selectedOpenDepartmentId = reimbursementFormService + .selectedApplicantDepartment(pinnedForm).orElse(null); + Long departmentId = applicantDepartmentService.resolveForCreate( + user, access.getTenantId(), selectedOpenDepartmentId, + reimbursementFormService.usesApplicantDepartment(pinnedForm)); java.util.Map> attachmentClaims = pinnedForm.getFingerprint() == null ? Collections.emptyMap() : reimbursementAttachmentService.validateClaims( request.getItems(), pinnedForm.getFingerprint(), userId, null); ReimApplication app = new ReimApplication(); + app.setTenantId(access.getTenantId()); app.setApplicationNo(generateApplicationNo()); app.setTitle(request.getTitle()); app.setApplicantId(user.getId()); - app.setDepartmentId(user.getDepartmentId()); + app.setDepartmentId(departmentId); app.setExpenseTypeId(request.getExpenseTypeId()); app.setCategory(request.getCategory()); app.setTotalAmount(request.getTotalAmount()); @@ -248,18 +299,21 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { app.setFeishuFormDisplayValues(reimbursementFormService.buildDisplayValues(app)); 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); - return buildDetail(app); + AuthorizationDecision decision = checkApplication(userId, "reimbursement.application", "read", app); + return projectDetailWithActions(app, userId, decision); } @Override @Transactional public ReimApplicationDetail updateApplication(Long id, CreateApplicationRequest request, Long userId) { - ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - requireEditPermission(userId, "reimbursement.application.edit"); - ensureOwner(app, userId); + FinanceScope access = scope(userId, "reimbursement.application", "edit"); + ReimApplication app = findScopedForUpdate(id, access); + AuthorizationDecision writeDecision = checkApplication(userId, "reimbursement.application", "edit", app); + mergeProtectedWrite(request, app, writeDecision); ensureNoCreationInProgress(app.getId()); if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { if (!ApprovalStatus.REJECTED.name().equals(app.getApprovalStatus()) @@ -306,8 +360,12 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { } app.setReturnReason(null); app = reimApplicationRepository.save(app); - - return buildDetail(app); + financeAudit.business("reimbursement.application.update", userId, + "REIM_APPLICATION", app.getId(), app.getApplicationStatus(), app.getTotalAmount(), + Collections.singletonMap("changedFieldCodes", + java.util.Arrays.asList("title", "expenseType", "amount", "payee", "form"))); + return projectDetailWithActions(app, userId, checkApplication(userId, + "reimbursement.application", "read", app)); } @Override @@ -318,25 +376,38 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { @Override public ReimApplicationDetail submitApplication(Long id, Long userId, String previewToken) { if (submissionCoordinator == null) throw new BusinessException("审批提交服务不可用", 503); + FinanceScope access = scope(userId, "reimbursement.application", "submit"); + ReimApplication before = findScoped(id, access); + 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()); - return buildDetail(app); + return projectDetailWithActions(app, userId, checkApplication(userId, + "reimbursement.application", "read", app)); } @Override @Transactional public ReimApplicationDetail receiveApplication(Long id, Long operatorId) { Long currentUserId = AuditUtil.getCurrentUserId(); - boolean permitted = roleService != null ? roleService.hasEditPermission(operatorId, "finance.receipt.confirm") - : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); + boolean permitted = roleService.hasEditPermission(operatorId, "finance.receipt.confirm"); if (operatorId == null || !operatorId.equals(currentUserId) || !permitted) { throw new com.finance.system.exception.UnauthorizedException("仅财务人员可以确认收单"); } + FinanceScope access = scope(operatorId, "finance.receipt", "receive"); // Lock before checking or changing the receipt state so repeated/concurrent // requests cannot create more than one receipt transition or audit record. - ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ReimApplication app = findScopedForUpdate(id, access); + checkApplication(operatorId, "finance.receipt", "receive", app); + try { + sodEvaluator.check(operatorId, app.getApplicantId(), "REQUESTER", "RECEIVER"); + } catch (org.springframework.security.access.AccessDeniedException denied) { + financeAudit.sodDenied(operatorId, "REIM_APPLICATION", app.getId(), + "receipt.receive", "REQUESTER_RECEIVER"); + throw denied; + } if (!ApprovalStatus.APPROVED.name().equals(app.getApprovalStatus())) { throw new BusinessException("申请未通过审批,无法收单"); @@ -347,6 +418,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { } app.setReceiptStatus(ReceiptStatus.RECEIVED.name()); + app.setReceivedBy(operatorId); + app.setReceivedAt(LocalDateTime.now()); reimApplicationRepository.save(app); // Approval records are the existing application audit trail. A receipt @@ -360,18 +433,21 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { auditRecord.setActionTime(LocalDateTime.now()); reimApprovalRecordRepository.save(auditRecord); + financeAudit.business("finance.receipt.receive", operatorId, + "REIM_APPLICATION", app.getId(), app.getReceiptStatus(), null, null); + log.info("财务收单: applicationNo={}, operatorId={}", app.getApplicationNo(), operatorId); - return buildDetail(app); + return projectDetail(buildDetail(app), checkApplication(operatorId, + "reimbursement.application", "read", app)); } @Override @Transactional public void deleteApplication(Long id, Long userId) { - ReimApplication app = reimApplicationRepository.findByIdForUpdate(id) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); - - requireEditPermission(userId, "reimbursement.application.edit"); - ensureOwner(app, userId); + requireEditPermission(userId, "reimbursement.application.delete"); + FinanceScope access = scope(userId, "reimbursement.application", "delete"); + ReimApplication app = findScopedForUpdate(id, access); + checkApplication(userId, "reimbursement.application", "delete", app); ensureNoCreationInProgress(app.getId()); if (!ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus())) { throw new BusinessException("只能删除草稿状态的申请"); @@ -379,42 +455,32 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { app.setDeleted(true); reimApplicationRepository.save(app); + financeAudit.business("reimbursement.application.delete", userId, + "REIM_APPLICATION", app.getId(), "DELETED", null, null); } @Override - public Page getAccountsPayableTasks(String status, Pageable pageable) { - Page tasks; - - if ("PENDING".equalsIgnoreCase(status)) { - tasks = reimApplicationRepository.findByApplicationStatusAndApprovalStatus( - ApplicationStatus.SUBMITTED.name(), ApprovalStatus.PENDING.name(), pageable); - } else if ("APPROVED".equalsIgnoreCase(status)) { - tasks = reimApplicationRepository.findByApplicationStatusAndApprovalStatus( - ApplicationStatus.SUBMITTED.name(), ApprovalStatus.APPROVED.name(), pageable); - } else { - tasks = reimApplicationRepository.findByApplicationStatus( - ApplicationStatus.SUBMITTED.name(), pageable); - } - - return tasks.map(this::buildSummary); + public Page getAccountsPayableTasks(Long actorId, String status, Pageable pageable) { + FinanceScope access = scope(actorId, "finance.payable", "read"); + String approvalStatus = "PENDING".equalsIgnoreCase(status) ? ApprovalStatus.PENDING.name() + : ("APPROVED".equalsIgnoreCase(status) ? ApprovalStatus.APPROVED.name() : null); + Page tasks = reimApplicationRepository.findScoped(access.getTenantId(), access.code(), + access.getActorId(), access.getDepartmentIds(), ApplicationStatus.SUBMITTED.name(), + approvalStatus, null, pageable); + return tasks.map(app -> projectSummary(buildSummary(app), + checkApplication(actorId, "finance.payable", "read", app))); } @Override - public Page getCashierTasks(String status, Pageable pageable) { - Page tasks; - - if ("UNPAID".equalsIgnoreCase(status)) { - tasks = reimApplicationRepository.findByApprovalStatusAndPaymentStatus( - ApprovalStatus.APPROVED.name(), PaymentStatus.UNPAID.name(), pageable); - } else if ("PARTIAL".equalsIgnoreCase(status)) { - tasks = reimApplicationRepository.findByApprovalStatusAndPaymentStatus( - ApprovalStatus.APPROVED.name(), PaymentStatus.PARTIAL.name(), pageable); - } else { - tasks = reimApplicationRepository.findByApprovalStatus( - ApprovalStatus.APPROVED.name(), pageable); - } - - return tasks.map(this::buildSummary); + public Page getCashierTasks(Long actorId, String status, Pageable pageable) { + FinanceScope access = scope(actorId, "finance.payment", "read"); + String paymentStatus = "UNPAID".equalsIgnoreCase(status) ? PaymentStatus.UNPAID.name() + : ("PARTIAL".equalsIgnoreCase(status) ? PaymentStatus.PARTIAL.name() : null); + Page tasks = reimApplicationRepository.findScoped(access.getTenantId(), access.code(), + access.getActorId(), access.getDepartmentIds(), null, ApprovalStatus.APPROVED.name(), + paymentStatus, pageable); + return tasks.map(app -> projectSummary(buildSummary(app), + checkApplication(actorId, "finance.payment", "read", app))); } private ReimApplicationSummary buildSummary(ReimApplication app) { @@ -453,6 +519,36 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { } } + private List applicationActions(ReimApplication app, Long userId) { + List actions = new ArrayList<>(); + if ((roleService.hasPermission(userId, "page.applications") + || roleService.hasPermission(userId, "page.application-edit") + || roleService.hasPermission(userId, "page.finance-receipt")) + && financeAuthorization.canApplication(userId, "reimbursement.application", "read", app)) + actions.add("VIEW"); + IntFeishuApproval mapping = feishuApprovalRepository == null ? null + : feishuApprovalRepository.findByApplicationId(app.getId()).orElse(null); + boolean creationPending = mapping != null && ("CREATING".equals(mapping.getStatus()) + || "CREATED".equals(mapping.getStatus()) || "CREATE_OUTCOME_UNKNOWN".equals(mapping.getStatus())); + boolean draft = ApplicationStatus.DRAFT.name().equals(app.getApplicationStatus()); + boolean editable = draft || ApprovalStatus.REJECTED.name().equals(app.getApprovalStatus()) + || ApprovalStatus.CANCELLED.name().equals(app.getApprovalStatus()); + boolean canEdit = roleService.hasEditPermission(userId, "reimbursement.application.edit") + && financeAuthorization.canApplication(userId, "reimbursement.application", "edit", app); + if (editable && !creationPending && canEdit + && roleService.hasPermission(userId, "page.application-edit")) actions.add("EDIT"); + if (draft && userId.equals(app.getApplicantId()) && canEdit + && roleService.hasPermission(userId, "page.application-edit") + && roleService.hasEditPermission(userId, "reimbursement.application.submit") + && financeAuthorization.canApplication(userId, "reimbursement.application", "submit", app)) + actions.add("SUBMIT"); + if (draft && !creationPending + && roleService.hasEditPermission(userId, "reimbursement.application.delete") + && financeAuthorization.canApplication(userId, "reimbursement.application", "delete", app)) + actions.add("DELETE"); + return Collections.unmodifiableList(actions); + } + private void ensureNoCreationInProgress(Long applicationId) { if (feishuApprovalRepository == null) return; IntFeishuApproval mapping = feishuApprovalRepository.findByApplicationId(applicationId).orElse(null); @@ -461,30 +557,8 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { throw new BusinessException("飞书审批正在创建,暂不能修改或删除", 409); } - private void ensureCanRead(ReimApplication app, Long currentId) { - if (currentId == null) throw new com.finance.system.exception.UnauthorizedException("未登录"); - if (currentId.equals(app.getApplicantId())) { - if (roleService == null - || roleService.hasPermission(currentId, "reimbursement:view-own") - || roleService.hasPermission(currentId, "reimbursement.application.view-own") - || roleService.hasPermission(currentId, "page.applications") - || roleService.hasPermission(currentId, "page.application-edit")) { - return; - } - } - if (roleService != null && ( - roleService.hasPermission(currentId, "reimbursement:view-all") - || roleService.hasPermission(currentId, "reimbursement.application.view-all") - || roleService.hasPermission(currentId, "page.finance-receipt"))) { - return; - } - if (roleService == null && (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole())) return; - throw new org.springframework.security.access.AccessDeniedException("无权访问该申请"); - } - private void requirePermission(Long userId, String... permissionCodes) { if (userId == null) throw new com.finance.system.exception.UnauthorizedException("未登录"); - if (roleService == null) return; // retained for narrow legacy unit tests for (String permissionCode : permissionCodes) { if (roleService.hasPermission(userId, permissionCode)) return; } @@ -493,14 +567,12 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { private void requireEditPermission(Long userId, String permissionCode) { if (userId == null) throw new com.finance.system.exception.UnauthorizedException("未登录"); - if (roleService == null) return; // retained for narrow legacy unit tests if (!roleService.hasEditPermission(userId, permissionCode)) throw new org.springframework.security.access.AccessDeniedException("权限不足,无法写入"); } private void validateFieldPermissions(CreateApplicationRequest request, Long userId, ReimApplication existing, boolean creating) { - if (roleService == null) return; checkField(request == null ? null : request.getTotalAmount(), existing == null ? null : existing.getTotalAmount(), userId, "application:amount", creating, "报销金额"); checkField(request == null ? null : request.getPayeeName(), existing == null ? null : existing.getPayeeName(), @@ -549,9 +621,6 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { throw new BusinessException("请填写申请金额", 400); } assertMoneyAmount(request.getTotalAmount(), "申请金额"); - if (userId == null || !sysUserRepository.findById(userId).map(u -> u.getDepartmentId() != null).orElse(false)) { - throw new BusinessException("申请人未配置部门"); - } if (request.getTitle() == null || request.getTitle().trim().isEmpty()) { throw new BusinessException("标题不能为空", 400); } @@ -583,8 +652,10 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { throw new BusinessException("明细合计须与申请金额一致,请核对各行金额", 400); } if (request.getPayeeBankId() == null - || !sysBankAccountRepository.findById(request.getPayeeBankId()).map(b -> userId.equals(b.getUserId())).orElse(false)) { - throw new BusinessException("收款银行账户不属于本人", 400); + || !sysBankAccountRepository.findById(request.getPayeeBankId()) + .map(b -> userId.equals(b.getUserId()) && "ACTIVE".equalsIgnoreCase(b.getStatus())) + .orElse(false)) { + throw new BusinessException("收款银行账户不属于本人或已停用", 400); } } @@ -608,8 +679,9 @@ 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 (app.getPayeeBankId() == null || !sysBankAccountRepository.findById(app.getPayeeBankId()) - .map(b -> app.getApplicantId().equals(b.getUserId())).orElse(false)) { - throw new BusinessException("收款银行账户不属于本人"); + .map(b -> app.getApplicantId().equals(b.getUserId()) + && "ACTIVE".equalsIgnoreCase(b.getStatus())).orElse(false)) { + throw new BusinessException("收款银行账户不属于本人或已停用"); } } @@ -646,10 +718,9 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { ? specified.getId() : null; } String role = node.getApproverRole(); - List users = roleService == null - ? sysUserRepository.findByUserType("FINANCE") : sysUserRepository.findAll(); + List users = sysUserRepository.findAll(); for (SysUser user : users) { - if ((roleService == null || roleService.hasEditPermission(user.getId(), "finance.approval.decide")) + if (roleService.hasEditPermission(user.getId(), "finance.approval.decide") && ApprovalRoutingRules.matchesRole(user, role)) return user.getId(); } return null; @@ -824,6 +895,64 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { .build(); } + private FinanceScope scope(Long actorId, String resource, String action) { + return financeAuthorization.scope(actorId, resource, action); + } + + private ReimApplication findScoped(Long id, FinanceScope access) { + return reimApplicationRepository.findScopedById(id, access.getTenantId(), access.code(), + access.getActorId(), access.getDepartmentIds()) + .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("报销申请不存在")); + } + + private AuthorizationDecision checkApplication(Long actorId, String resource, String action, + ReimApplication application) { + return financeAuthorization.checkApplication(actorId, resource, action, application); + } + + private ReimApplicationDetail projectDetail(ReimApplicationDetail detail, AuthorizationDecision decision) { + return financeProjection.application(detail, decision); + } + + private ReimApplicationDetail projectDetailWithActions(ReimApplication app, Long userId, + AuthorizationDecision decision) { + ReimApplicationDetail detail = projectDetail(buildDetail(app), decision); + detail.setAvailableActions(applicationActions(app, userId)); + return detail; + } + + private ReimApplicationSummary projectSummary(ReimApplicationSummary summary, AuthorizationDecision decision) { + return financeProjection.application(summary, decision); + } + + /** PUT compatibility: fields without EDIT are preserved from the locked server row. */ + 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("totalAmount") != FieldAccess.EDIT) { + request.setTotalAmount(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("payeeName") != FieldAccess.EDIT) request.setPayeeName(current.getPayeeName()); + if (decision.accessFor("payeeBankId") != FieldAccess.EDIT) request.setPayeeBankId(current.getPayeeBankId()); + if (decision.accessFor("formSnapshot") != FieldAccess.EDIT) { + request.setFormFingerprint(current.getFeishuFormFingerprint()); + request.setFormValues(reimbursementFormService.mergedSnapshotValues(current, + reimbursementFormService.parseSchema(current.getFeishuFormSchema()))); + } + } + private DashboardStats buildDashboardStats(Long userId, List applications) { long total = applications.size(); long pendingApproval = applications.stream() diff --git a/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java index 797fbe4..527cb49 100644 --- a/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimApprovalServiceImpl.java @@ -15,11 +15,14 @@ import com.finance.system.repository.*; import com.finance.system.service.ReimApprovalService; import com.finance.system.service.RoleService; import com.finance.system.util.AuditUtil; +import com.finance.system.authorization.SegregationOfDutiesEvaluator; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.security.finance.FinanceAuthorization; +import com.finance.system.security.finance.FinanceScope; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.beans.factory.annotation.Autowired; import java.time.LocalDateTime; import java.util.List; @@ -34,24 +37,23 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { private final ReimApprovalRecordRepository reimApprovalRecordRepository; private final SysUserRepository sysUserRepository; private final SysApprovalNodeRepository sysApprovalNodeRepository; - private RoleService roleService; - - @Autowired(required = false) - public void setRoleService(RoleService roleService) { - this.roleService = roleService; - } + private final RoleService roleService; + private final FinanceAuthorization financeAuthorization; + private final SegregationOfDutiesEvaluator sodEvaluator; + private final FinanceAuditEvents financeAudit; @Override @Transactional public ApprovalRecordDto approve(Long applicationId, Long approverId, String comment) { - ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ReimApplication app = findApprovalForUpdate(applicationId, approverId); + financeAuthorization.checkApplication(approverId, "finance.approval", "decide", app); if (!ApplicationStatus.SUBMITTED.name().equals(app.getApplicationStatus()) || !ApprovalStatus.PENDING.name().equals(app.getApprovalStatus())) { throw new BusinessException("该申请不在待审批状态"); } ensureCurrentApprover(app, approverId); + checkSod(approverId, app.getApplicantId(), "REQUESTER", "APPROVER", app, "approval.approve"); // 记录审批动作 ReimApprovalRecord record = new ReimApprovalRecord(); @@ -107,6 +109,9 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { reimApplicationRepository.save(app); + financeAudit.business("finance.approval.approve", approverId, + "REIM_APPLICATION", app.getId(), app.getApprovalStatus(), null, null); + log.info("审批通过: applicationNo={}, approverId={}", app.getApplicationNo(), approverId); return buildApprovalRecordDto(record); } @@ -114,14 +119,15 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { @Override @Transactional public ApprovalRecordDto reject(Long applicationId, Long approverId, String comment, String returnReason) { - ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ReimApplication app = findApprovalForUpdate(applicationId, approverId); + financeAuthorization.checkApplication(approverId, "finance.approval", "decide", app); if (!ApplicationStatus.SUBMITTED.name().equals(app.getApplicationStatus()) || !ApprovalStatus.PENDING.name().equals(app.getApprovalStatus())) { throw new BusinessException("该申请不在待审批状态"); } ensureCurrentApprover(app, approverId); + checkSod(approverId, app.getApplicantId(), "REQUESTER", "APPROVER", app, "approval.reject"); // 记录审批动作 ReimApprovalRecord record = new ReimApprovalRecord(); @@ -141,6 +147,9 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { app.setCurrentApproverId(app.getApplicantId()); reimApplicationRepository.save(app); + financeAudit.business("finance.approval.reject", approverId, + "REIM_APPLICATION", app.getId(), app.getApprovalStatus(), null, null); + log.info("审批退回: applicationNo={}, approverId={}, reason={}", app.getApplicationNo(), approverId, returnReason); return buildApprovalRecordDto(record); @@ -149,8 +158,13 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { @Override @Transactional public ApprovalRecordDto transfer(Long applicationId, Long fromUserId, Long toUserId, String comment) { - ReimApplication app = reimApplicationRepository.findById(applicationId) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ReimApplication app = findApprovalForUpdate(applicationId, fromUserId); + ensureCurrentApprover(app, fromUserId); + SysUser target = sysUserRepository.findById(toUserId) + .filter(ApprovalRoutingRules::isActive) + .orElseThrow(() -> new BusinessException("转交目标不存在或已停用", 400)); + checkSod(toUserId, app.getApplicantId(), "REQUESTER", "APPROVER", app, "approval.transfer"); + financeAuthorization.checkProspectiveApprover(target.getId(), app); ReimApprovalRecord record = new ReimApprovalRecord(); record.setApplicationId(applicationId); @@ -164,6 +178,10 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { app.setCurrentApproverId(toUserId); reimApplicationRepository.save(app); + financeAudit.business("finance.approval.transfer", fromUserId, + "REIM_APPLICATION", app.getId(), app.getApprovalStatus(), null, + java.util.Collections.singletonMap("targetActorId", toUserId)); + return buildApprovalRecordDto(record); } @@ -196,8 +214,7 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { private void ensureCurrentApprover(ReimApplication app, Long approverId) { Long actorId = AuditUtil.getCurrentUserId(); - boolean permitted = roleService != null ? roleService.hasEditPermission(approverId, "finance.approval.decide") - : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); + boolean permitted = roleService.hasEditPermission(approverId, "finance.approval.decide"); if (approverId == null || (actorId != null && !approverId.equals(actorId)) || !permitted) { throw new com.finance.system.exception.UnauthorizedException("无审批权限"); } @@ -221,6 +238,24 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { throw new com.finance.system.exception.UnauthorizedException("当前申请不属于您的审批节点"); } + private ReimApplication findApprovalForUpdate(Long applicationId, Long actorId) { + FinanceScope access = financeAuthorization.scope(actorId, "finance.approval", "decide"); + return reimApplicationRepository.findScopedByIdForUpdate(applicationId, access.getTenantId(), + access.code(), access.getActorId(), access.getDepartmentIds()) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + } + + private void checkSod(Long actorId, Long relatedActorId, String leftDuty, String rightDuty, + ReimApplication app, String operation) { + try { + sodEvaluator.check(actorId, relatedActorId, leftDuty, rightDuty); + } catch (org.springframework.security.access.AccessDeniedException denied) { + financeAudit.sodDenied(actorId, "REIM_APPLICATION", app.getId(), + operation, leftDuty + "_" + rightDuty); + throw denied; + } + } + private Long resolveApprover(SysApprovalNode node) { if (!ApprovalRoutingRules.isApprovalNode(node)) return null; if (node.getApproverId() != null) { @@ -228,10 +263,9 @@ public class ReimApprovalServiceImpl implements ReimApprovalService { return ApprovalRoutingRules.matchesRole(specified, node.getApproverRole()) ? specified.getId() : null; } - List users = roleService == null - ? sysUserRepository.findByUserType("FINANCE") : sysUserRepository.findAll(); + List users = sysUserRepository.findAll(); for (SysUser user : users) { - if ((roleService == null || roleService.hasEditPermission(user.getId(), "finance.approval.decide")) + if (roleService.hasEditPermission(user.getId(), "finance.approval.decide") && ApprovalRoutingRules.matchesRole(user, node.getApproverRole())) return user.getId(); } return null; diff --git a/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java index 6de4bbc..5bb5932 100644 --- a/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimPaymentServiceImpl.java @@ -18,12 +18,21 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.finance.system.util.AuditUtil; import com.finance.system.service.RoleService; -import org.springframework.beans.factory.annotation.Autowired; +import com.finance.system.authorization.AuthorizationDecision; +import com.finance.system.authorization.SegregationOfDutiesEvaluator; +import com.finance.system.finance.audit.FinanceAuditEvents; +import com.finance.system.security.finance.FinanceAuthorization; +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 java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; +import java.util.ArrayList; +import java.util.Collections; import java.util.UUID; import java.util.stream.Collectors; @@ -40,30 +49,29 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { private final SysBankAccountRepository sysBankAccountRepository; private final SysDepartmentRepository sysDepartmentRepository; private final PaymentIdempotencyLock paymentIdempotencyLock; - private RoleService roleService; - - @Autowired(required = false) - public void setRoleService(RoleService roleService) { - this.roleService = roleService; - } + private final RoleService roleService; + private final FinanceAuthorization financeAuthorization; + private final FinanceFieldProjection financeProjection; + private final SegregationOfDutiesEvaluator sodEvaluator; + private final FinanceAuditEvents financeAudit; @Override public Page getPendingPayments(Long operatorId, Pageable pageable) { requirePaymentPermission(operatorId); - Page applications = reimApplicationRepository - .findByApprovalStatusAndPaymentStatusIn( - "APPROVED", - java.util.Arrays.asList("UNPAID", "PARTIAL"), - pageable); - - return applications.map(this::buildPaymentTask); + FinanceScope access = scope(operatorId, "finance.payment", "read"); + Page applications = reimApplicationRepository.findScopedPaymentTasks( + access.getTenantId(), access.code(), access.getActorId(), access.getDepartmentIds(), pageable); + return applications.map(app -> financeProjection.payment(buildPaymentTask(app, operatorId), + financeAuthorization.checkApplication(operatorId, "finance.payment", "read", app))); } @Override public PaymentDetailDto getPaymentDetail(Long applicationId, Long operatorId) { requirePaymentPermission(operatorId); - ReimApplication app = reimApplicationRepository.findById(applicationId) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + FinanceScope access = scope(operatorId, "finance.payment", "read"); + ReimApplication app = findApplication(applicationId, access, false); + AuthorizationDecision decision = financeAuthorization.checkApplication( + operatorId, "finance.payment", "read", app); SysUser payee = sysUserRepository.findById(app.getApplicantId()).orElse(null); SysDepartment dept = app.getDepartmentId() != null ? @@ -97,14 +105,25 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { dto.setBankName(bank.getBankName()); dto.setBranchName(bank.getBranchName()); dto.setBankAccountMask(bank.getAccountNoMask()); - dto.setAccountName(bank.getAccountName()); } } - dto.setPaymentHistory(payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList())); + List history = payments.stream() + .map(payment -> financeProjection.payment(buildPaymentRecord(payment, app, operatorId), decision)) + .collect(Collectors.toList()); + dto.setPaymentHistory(history); dto.setApprovalRecords(approvalRecords.stream().map(this::buildApprovalRecord).collect(Collectors.toList())); + List actions = new ArrayList<>(); + if (canRegister(operatorId, app)) actions.add("PAYMENT_REGISTER"); + boolean canVerify = history.stream().anyMatch(record -> Boolean.TRUE.equals(record.getCanVerify())); + boolean canReject = history.stream().anyMatch(record -> Boolean.TRUE.equals(record.getCanReject())); + if (canVerify) actions.add("PAYMENT_VERIFY"); + if (canReject) actions.add("PAYMENT_REJECT"); + dto.setAvailableActions(Collections.unmodifiableList(actions)); + dto.setCanVerify(canVerify); + dto.setCanReject(canReject); - return dto; + return financeProjection.payment(dto, decision); } @Override @@ -123,9 +142,10 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { if (operatorId == null || !operatorId.equals(AuditUtil.getCurrentUserId())) { throw new com.finance.system.exception.UnauthorizedException("无权使用其他用户身份付款"); } + FinanceScope access = scope(operatorId, "finance.payment", "register"); String normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey); - ReimApplication app = reimApplicationRepository.findByIdForUpdate(applicationId) - .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + ReimApplication app = findApplication(applicationId, access, true); + financeAuthorization.checkApplication(operatorId, "finance.payment", "register", app); if (normalizedIdempotencyKey != null) { // Acquire the transaction-scoped database lock before // reading the key. This serializes claims across application rows. @@ -146,6 +166,12 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { if (!"RECEIVED".equals(app.getReceiptStatus())) { throw new BusinessException("申请尚未完成财务收单,无法付款"); } + checkSod(operatorId, app.getApplicantId(), "REQUESTER", "PAYER", app, "payment.register"); + for (ReimApprovalRecord approval : reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(applicationId)) { + checkSod(operatorId, approval.getApproverId(), "APPROVER", "PAYMENT_MAKER", + app, "payment.register"); + } if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) { throw new BusinessException("付款金额必须大于0"); @@ -158,8 +184,12 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { .filter(p -> "COMPLETED".equals(p.getPaymentStatus())) .map(ReimPayment::getPaymentAmount) .reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal pendingAmount = existingPayments.stream() + .filter(p -> "PENDING_REVIEW".equals(p.getPaymentStatus())) + .map(ReimPayment::getPaymentAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal remaining = app.getTotalAmount().subtract(paidAmount); + BigDecimal remaining = app.getTotalAmount().subtract(paidAmount).subtract(pendingAmount); if (amount.compareTo(remaining) > 0) { throw new BusinessException("付款金额超过剩余未付金额"); @@ -173,6 +203,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { // 创建付款记录 ReimPayment payment = new ReimPayment(); + payment.setTenantId(access.getTenantId()); payment.setPaymentNo(generatePaymentNo()); payment.setApplicationId(applicationId); payment.setPayeeId(app.getApplicantId()); @@ -186,30 +217,24 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { payment.setReferenceNo(referenceNo); payment.setBankAccountNo(null); // never persist a full account number payment.setOperatorId(operatorId); - payment.setPaymentStatus("COMPLETED"); - payment.setPaymentTime(LocalDateTime.now()); + payment.setMakerId(operatorId); + payment.setPaymentStatus("PENDING_REVIEW"); + payment.setPaymentTime(null); payment.setIdempotencyKey(idempotencyKey); payment.setRemark(remark); payment.setDeleted(false); payment = reimPaymentRepository.save(payment); - // 更新申请付款状态 - BigDecimal newPaidAmount = paidAmount.add(amount); - if (newPaidAmount.compareTo(app.getTotalAmount()) >= 0) { - app.setPaymentStatus(PaymentStatus.PAID.name()); - } else { - app.setPaymentStatus(PaymentStatus.PARTIAL.name()); - } - reimApplicationRepository.save(app); - - log.info("执行付款: paymentNo={}, applicationNo={}, amount={}", + financeAudit.business("finance.payment.register", operatorId, + "REIM_PAYMENT", payment.getId(), payment.getPaymentStatus(), amount, null); + log.info("付款待复核: paymentNo={}, applicationNo={}, amount={}", payment.getPaymentNo(), app.getApplicationNo(), amount); PaymentResultDto result = new PaymentResultDto(); result.setPaymentNo(payment.getPaymentNo()); result.setAmount(amount); - result.setPaymentStatus("COMPLETED"); - result.setMessage("付款登记成功(模拟)"); + result.setPaymentStatus("PENDING_REVIEW"); + result.setMessage("付款登记成功,等待独立复核"); return result; } @@ -225,26 +250,98 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { remark, idempotencyKey, false, true); } + @Override + @Transactional + public PaymentResultDto verifyPayment(Long paymentId, Long checkerId) { + requirePaymentPermission(checkerId); + requireCurrentActor(checkerId); + FinanceScope access = scope(checkerId, "finance.payment", "review"); + 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 (!"PENDING_REVIEW".equals(payment.getPaymentStatus())) { + throw new BusinessException("付款记录不在待复核状态", 409); + } + checkSod(checkerId, payment.getMakerId(), "PAYMENT_MAKER", "PAYMENT_CHECKER", + app, "payment.verify"); + for (ReimApprovalRecord approval : reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(app.getId())) { + checkSod(checkerId, approval.getApproverId(), "APPROVER", "PAYMENT_CHECKER", + app, "payment.verify"); + } + payment.setCheckerId(checkerId); + payment.setVerifiedAt(LocalDateTime.now()); + payment.setPaymentTime(payment.getVerifiedAt()); + payment.setPaymentStatus("COMPLETED"); + 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(); + } + + @Override + @Transactional + public PaymentResultDto rejectPayment(Long paymentId, Long checkerId, String rejectionCode) { + requirePaymentPermission(checkerId); + requireCurrentActor(checkerId); + if (rejectionCode == null || !rejectionCode.matches("[A-Z0-9_]{1,80}")) { + throw new BadRequestException("付款拒绝码格式不正确"); + } + FinanceScope access = scope(checkerId, "finance.payment", "reject"); + ReimPayment payment = findPaymentForUpdate(paymentId, access); + ReimApplication app = findApplication(payment.getApplicationId(), access, true); + financeAuthorization.checkApplication(checkerId, "finance.payment", "reject", app); + if ("REJECTED".equals(payment.getPaymentStatus()) + && checkerId.equals(payment.getCheckerId())) return buildPaymentResult(payment); + if (!"PENDING_REVIEW".equals(payment.getPaymentStatus())) { + throw new BusinessException("付款记录不在待复核状态", 409); + } + checkSod(checkerId, payment.getMakerId(), "PAYMENT_MAKER", "PAYMENT_CHECKER", + app, "payment.reject"); + for (ReimApprovalRecord approval : reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(app.getId())) { + checkSod(checkerId, approval.getApproverId(), "APPROVER", "PAYMENT_CHECKER", + app, "payment.reject"); + } + payment.setCheckerId(checkerId); + payment.setRejectedAt(LocalDateTime.now()); + payment.setRejectionCode(rejectionCode); + payment.setPaymentStatus("REJECTED"); + reimPaymentRepository.save(payment); + financeAudit.business("finance.payment.reject", checkerId, + "REIM_PAYMENT", payment.getId(), payment.getPaymentStatus(), null, + java.util.Collections.singletonMap("rejectionCode", rejectionCode)); + return PaymentResultDto.builder().paymentNo(payment.getPaymentNo()).amount(payment.getPaymentAmount()) + .paymentStatus(payment.getPaymentStatus()).message("付款已拒绝").build(); + } + @Override public List getPaymentHistoryByOperator(Long operatorId) { requirePaymentPermission(operatorId); - List payments = reimPaymentRepository.findByOperatorId(operatorId); - return payments.stream().map(this::buildPaymentRecord).collect(Collectors.toList()); + FinanceScope access = scope(operatorId, "finance.payment", "read"); + List payments = reimPaymentRepository.findScoped(access.getTenantId(), access.code(), + access.getActorId(), access.getDepartmentIds(), null, PageRequest.of(0, 500)).getContent(); + return payments.stream().map(payment -> project(buildPaymentRecord(payment), payment, access)) + .collect(Collectors.toList()); } @Override public PaymentRecordDto getPaymentByNo(String paymentNo, Long operatorId) { requirePaymentPermission(operatorId); - ReimPayment payment = reimPaymentRepository.findByPaymentNo(paymentNo); + FinanceScope access = scope(operatorId, "finance.payment", "read"); + ReimPayment payment = reimPaymentRepository.findScopedByPaymentNo(paymentNo, access.getTenantId(), + access.code(), access.getActorId(), access.getDepartmentIds()).orElse(null); if (payment == null) { - throw new ResourceNotFoundException("付款记录不存在: " + paymentNo); + throw new ResourceNotFoundException("付款记录不存在"); } - return buildPaymentRecord(payment); + return project(buildPaymentRecord(payment), payment, access); } private void requirePaymentPermission(Long operatorId) { - boolean permitted = roleService != null ? roleService.hasEditPermission(operatorId, "finance.payment.register") - : (AuditUtil.isFinanceRole() || AuditUtil.isAdminRole()); + boolean permitted = roleService.hasEditPermission(operatorId, "finance.payment.register"); if (!permitted) throw new com.finance.system.exception.UnauthorizedException("仅财务人员可以登记付款"); } @@ -276,7 +373,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { return normalized; } - private PaymentTaskDto buildPaymentTask(ReimApplication app) { + private PaymentTaskDto buildPaymentTask(ReimApplication app, Long actorId) { SysUser payee = sysUserRepository.findById(app.getApplicantId()).orElse(null); SysDepartment dept = app.getDepartmentId() != null ? sysDepartmentRepository.findById(app.getDepartmentId()).orElse(null) : null; @@ -290,6 +387,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { PaymentTaskDto dto = new PaymentTaskDto(); dto.setId(app.getId()); + dto.setApplicationId(app.getId()); dto.setApplicationNo(app.getApplicationNo()); dto.setTitle(app.getTitle()); dto.setPayeeName(app.getPayeeName()); @@ -302,6 +400,11 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { dto.setApprovalStatus(app.getApprovalStatus()); dto.setSubmitTime(app.getSubmitTime()); dto.setCreatedAt(app.getCreatedAt()); + boolean canRegister = canRegister(actorId, app); + dto.setAvailableActions(canRegister + ? Collections.singletonList("PAYMENT_REGISTER") : Collections.emptyList()); + dto.setCanVerify(false); + dto.setCanReject(false); // 获取银行信息 if (app.getPayeeBankId() != null) { @@ -316,11 +419,16 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { } private PaymentRecordDto buildPaymentRecord(ReimPayment payment) { + return buildPaymentRecord(payment, null, null); + } + + private PaymentRecordDto buildPaymentRecord(ReimPayment payment, ReimApplication application, Long actorId) { SysUser operator = payment.getOperatorId() != null ? sysUserRepository.findById(payment.getOperatorId()).orElse(null) : null; PaymentRecordDto dto = new PaymentRecordDto(); dto.setId(payment.getId()); + dto.setApplicationId(payment.getApplicationId()); dto.setPaymentNo(payment.getPaymentNo()); dto.setPaymentAmount(payment.getPaymentAmount()); dto.setTotalAmount(payment.getTotalAmount()); @@ -332,6 +440,7 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { dto.setOperatorName(operator != null ? operator.getRealName() : null); dto.setPaymentTime(payment.getPaymentTime()); dto.setRemark(payment.getRemark()); + if (application != null && actorId != null) applyReviewActions(dto, payment, application, actorId); return dto; } @@ -361,4 +470,105 @@ public class ReimPaymentServiceImpl implements ReimPaymentService { .substring(0, 12).toUpperCase(java.util.Locale.ROOT); return "PAY-" + datePart + "-" + randomPart; } + + private FinanceScope scope(Long actorId, String resource, String action) { + return financeAuthorization.scope(actorId, resource, action); + } + + private ReimApplication findApplication(Long applicationId, FinanceScope access, boolean forUpdate) { + return (forUpdate + ? reimApplicationRepository.findScopedByIdForUpdate(applicationId, access.getTenantId(), + access.code(), access.getActorId(), access.getDepartmentIds()) + : reimApplicationRepository.findScopedById(applicationId, access.getTenantId(), + access.code(), access.getActorId(), access.getDepartmentIds())) + .orElseThrow(() -> new ResourceNotFoundException("报销申请不存在")); + } + + private ReimPayment findPaymentForUpdate(Long paymentId, FinanceScope access) { + return reimPaymentRepository.findByIdForUpdate(paymentId, access.getTenantId()) + .orElseThrow(() -> new ResourceNotFoundException("付款记录不存在")); + } + + private void updateApplicationPaymentState(ReimApplication app) { + BigDecimal completed = reimPaymentRepository.findByApplicationId(app.getId()).stream() + .filter(payment -> "COMPLETED".equals(payment.getPaymentStatus())) + .map(ReimPayment::getPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add); + app.setPaymentStatus(completed.compareTo(app.getTotalAmount()) >= 0 + ? PaymentStatus.PAID.name() + : (completed.signum() > 0 ? PaymentStatus.PARTIAL.name() : PaymentStatus.UNPAID.name())); + reimApplicationRepository.save(app); + } + + private void requireCurrentActor(Long actorId) { + if (actorId == null || !actorId.equals(AuditUtil.getCurrentUserId())) { + throw new com.finance.system.exception.UnauthorizedException("无权使用其他用户身份操作付款"); + } + } + + private void checkSod(Long actorId, Long relatedActorId, String leftDuty, String rightDuty, + ReimApplication app, String operation) { + try { + sodEvaluator.check(actorId, relatedActorId, leftDuty, rightDuty); + } catch (AccessDeniedException denied) { + financeAudit.sodDenied(actorId, "REIM_APPLICATION", app.getId(), + operation, leftDuty + "_" + rightDuty); + throw denied; + } + } + + private PaymentRecordDto project(PaymentRecordDto value, ReimPayment payment, FinanceScope access) { + ReimApplication application = findApplication(payment.getApplicationId(), access, false); + AuthorizationDecision decision = financeAuthorization.checkApplication( + access.getActorId(), "finance.payment", "read", application); + applyReviewActions(value, payment, application, access.getActorId()); + return financeProjection.payment(value, decision); + } + + private boolean canRegister(Long actorId, ReimApplication application) { + if (actorId == null || application == null + || !"APPROVED".equals(application.getApprovalStatus()) + || !"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 + .findByApplicationIdOrderByActionTimeAsc(application.getId())) { + if (!sodAllowed(actorId, approval.getApproverId(), "APPROVER", "PAYMENT_MAKER")) return false; + } + return true; + } + + private void applyReviewActions(PaymentRecordDto dto, ReimPayment payment, + ReimApplication application, Long actorId) { + boolean pending = "PENDING_REVIEW".equals(payment.getPaymentStatus()); + boolean sodAllowed = pending + && sodAllowed(actorId, payment.getMakerId(), "PAYMENT_MAKER", "PAYMENT_CHECKER"); + if (sodAllowed) { + for (ReimApprovalRecord approval : reimApprovalRecordRepository + .findByApplicationIdOrderByActionTimeAsc(application.getId())) { + if (!sodAllowed(actorId, approval.getApproverId(), "APPROVER", "PAYMENT_CHECKER")) { + sodAllowed = false; + break; + } + } + } + boolean canVerify = sodAllowed && financeAuthorization.canApplication( + actorId, "finance.payment", "review", application); + boolean canReject = sodAllowed && financeAuthorization.canApplication( + actorId, "finance.payment", "reject", application); + List actions = new ArrayList<>(); + if (canVerify) actions.add("PAYMENT_VERIFY"); + if (canReject) actions.add("PAYMENT_REJECT"); + dto.setAvailableActions(Collections.unmodifiableList(actions)); + dto.setCanVerify(canVerify); + dto.setCanReject(canReject); + } + + private boolean sodAllowed(Long actorId, Long relatedActorId, String leftDuty, String rightDuty) { + try { + sodEvaluator.check(actorId, relatedActorId, leftDuty, rightDuty); + return true; + } catch (AccessDeniedException denied) { + return false; + } + } } diff --git a/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java b/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java index 3faa7b2..22b8f7d 100644 --- a/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java +++ b/src/main/java/com/finance/system/service/impl/ReimbursementRoutePreviewService.java @@ -48,7 +48,7 @@ public class ReimbursementRoutePreviewService { @Transactional public RoutePreviewDto preview(ReimApplication application, Long userId) { forms.assertApplicationMatchesCurrentForm(application); - Route route = currentRoute(false); + Route route = currentRoute(application, false); return issue(application, userId, route, fingerprints.fingerprint(application)); } @@ -96,7 +96,7 @@ public class ReimbursementRoutePreviewService { if (!Objects.equals(token.getApplicationId(), application.getId()) || !Objects.equals(token.getUserId(), userId) || token.getConsumedAt() != null || token.getExpiresAt() == null || !token.getExpiresAt().isAfter(LocalDateTime.now())) throw invalid(); - Route current = currentRoute(true); + Route current = currentRoute(application, true); if (!Objects.equals(token.getApplicationFingerprint(), fingerprints.fingerprint(application)) || !Objects.equals(token.getRouteSource(), current.source) || !Objects.equals(token.getApprovalCode(), current.approvalCode) @@ -144,14 +144,18 @@ public class ReimbursementRoutePreviewService { || token.getConsumedAt() != null || token.getExpiresAt() == null || !token.getExpiresAt().isAfter(LocalDateTime.now()) || !Objects.equals(token.getApplicationFingerprint(), fingerprints.fingerprint(application))) throw invalid(); - Route current = localRoute(); + Route current = localRoute(application); if (!Objects.equals(token.getRouteFingerprint(), current.fingerprint) - || !Objects.equals(token.getApprovalCode(), current.approvalCode)) throw invalid(); + || !Objects.equals(token.getApprovalCode(), current.approvalCode) + || !Objects.equals(token.getFirstApproverId(), current.firstApproverId) + || !Objects.equals(token.getFirstNodeId(), current.firstNodeId) + || !Objects.equals(token.getFirstApproverRole(), current.firstApproverRole) + || !Objects.equals(token.getFirstNodeName(), current.firstNodeName)) throw invalid(); nodesFromToken(token); } - private Route currentRoute(boolean lockSnapshot) { - return feishu.isApprovalEnabledAndConfigured() ? feishuRoute(lockSnapshot) : localRoute(); + private Route currentRoute(ReimApplication application, boolean lockSnapshot) { + return feishu.isApprovalEnabledAndConfigured() ? feishuRoute(lockSnapshot) : localRoute(application); } private Route feishuRoute(boolean lockSnapshot) { @@ -199,9 +203,11 @@ public class ReimbursementRoutePreviewService { null, null, approvalCode); } - private Route localRoute() { + private Route localRoute(ReimApplication application) { + ApprovalBoundary boundary = approvalBoundary(application); List result = new ArrayList<>(); List bindings = new ArrayList<>(); + bindings.add(boundary.tenantId + ":" + boundary.organizationId); Long firstApproverId = null, firstNodeId = null; String firstNodeName = null, firstRole = null; int order = 1; List configuredNodes = new ArrayList<>(localNodes.findAllByOrderBySortOrder()); configuredNodes.sort(Comparator.comparing(SysApprovalNode::getSortOrder, Comparator.nullsLast(Integer::compareTo)) @@ -209,7 +215,7 @@ public class ReimbursementRoutePreviewService { for (SysApprovalNode node : configuredNodes) { if (!ApprovalRoutingRules.isApprovalNode(node)) continue; if (result.size() >= MAX_ROUTE_NODES) throw new BusinessException("当前审批路线节点过多,无法预览"); - SysUser approver = resolveApprover(node); + SysUser approver = resolveApprover(node, boundary); if (approver == null) throw new BusinessException("当前审批节点未配置有效审批人,无法预览"); if (firstApproverId == null) { firstApproverId = approver.getId(); firstNodeId = node.getId(); firstNodeName = node.getNodeName(); firstRole = node.getApproverRole(); } @@ -227,20 +233,39 @@ public class ReimbursementRoutePreviewService { null, null, false, true, null, firstApproverId, firstNodeName, firstNodeId, firstRole, configuredCode); } - private SysUser resolveApprover(SysApprovalNode node) { + private SysUser resolveApprover(SysApprovalNode node, ApprovalBoundary boundary) { if (node.getApproverId() != null) { SysUser user = users.findById(node.getApproverId()).orElse(null); - return ApprovalRoutingRules.matchesRole(user, node.getApproverRole()) + return inBoundary(user, boundary) && ApprovalRoutingRules.matchesRole(user, node.getApproverRole()) && roles.hasEditPermission(user.getId(), "finance.approval.decide") ? user : null; } - List candidates = new ArrayList<>(users.findAll()); + List candidates = new ArrayList<>(users.findByTenantId(boundary.tenantId)); candidates.sort(Comparator.comparing(SysUser::getId, Comparator.nullsLast(Long::compareTo))); for (SysUser user : candidates) - if (roles.hasEditPermission(user.getId(), "finance.approval.decide") + if (inBoundary(user, boundary) && roles.hasEditPermission(user.getId(), "finance.approval.decide") && ApprovalRoutingRules.matchesRole(user, node.getApproverRole())) return user; return null; } + private ApprovalBoundary approvalBoundary(ReimApplication application) { + if (application == null || !StringUtils.hasText(application.getTenantId()) + || application.getApplicantId() == null) { + throw new BusinessException("申请归属边界无效,无法预览审批路线", 409); + } + String tenantId = application.getTenantId().trim(); + SysUser applicant = users.findById(application.getApplicantId()).orElse(null); + if (applicant == null || !tenantId.equals(applicant.getTenantId()) + || applicant.getOrganizationId() == null) { + throw new BusinessException("申请归属边界无效,无法预览审批路线", 409); + } + return new ApprovalBoundary(tenantId, applicant.getOrganizationId()); + } + + private boolean inBoundary(SysUser user, ApprovalBoundary boundary) { + return user != null && Objects.equals(boundary.tenantId, user.getTenantId()) + && Objects.equals(boundary.organizationId, user.getOrganizationId()); + } + private String localBinding(SysApprovalNode node, SysUser approver) { StringBuilder out = new StringBuilder(); append(out, node.getId()); append(out, node.getNodeCode()); append(out, node.getNodeName()); @@ -271,6 +296,15 @@ public class ReimbursementRoutePreviewService { private String bounded(String value, int max) { return value == null ? null : value.substring(0, Math.min(max, value.length())); } private BusinessException invalid() { return new BusinessException(INVALID_PREVIEW, 409); } + private static class ApprovalBoundary { + final String tenantId; + final Long organizationId; + ApprovalBoundary(String tenantId, Long organizationId) { + this.tenantId = tenantId; + this.organizationId = organizationId; + } + } + private static class Route { final String source; final List nodes; final String fingerprint; final String snapshotFingerprint; final LocalDateTime snapshotFetchedAt; final boolean stale; diff --git a/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java b/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java index 903aeab..dac8b04 100644 --- a/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java +++ b/src/main/java/com/finance/system/service/impl/ReimbursementSubmissionStateService.java @@ -35,8 +35,6 @@ public class ReimbursementSubmissionStateService { private final RoleService roles; private final FeishuApprovalService feishu; private final ReimbursementFingerprintService fingerprints; - private final SysUserRepository users; - private final SysApprovalNodeRepository localNodes; private final IntFeishuApprovalAttemptRepository attempts; private final ReimbursementFormService forms; @@ -168,7 +166,6 @@ public class ReimbursementSubmissionStateService { if (!"LOCAL".equals(token.getRouteSource()) || token.getFirstApproverId() == null) throw new BusinessException(ReimbursementRoutePreviewService.INVALID_PREVIEW, 409); routes.validateLockedLocalForFinalization(app, token); - validateLocalFirstApprover(token); app.setCurrentApprovalNode(token.getFirstNodeName()); app.setCurrentApproverId(token.getFirstApproverId()); } @@ -238,32 +235,6 @@ public class ReimbursementSubmissionStateService { .status(mapping.getStatus()).eventUpdatedAt(mapping.getEventUpdatedAt()).createdAt(now).updatedAt(now).build()); } - private void validateLocalFirstApprover(ReimRoutePreviewToken token) { - SysApprovalNode node = token.getFirstNodeId() == null ? null : localNodes.findById(token.getFirstNodeId()).orElse(null); - SysUser user = users.findById(token.getFirstApproverId()).orElse(null); - SysUser currentlyResolved = node == null ? null : resolveLocalApprover(node); - if (node == null || !ApprovalRoutingRules.isApprovalNode(node) - || !Objects.equals(node.getApproverRole(), token.getFirstApproverRole()) - || !ApprovalRoutingRules.matchesRole(user, token.getFirstApproverRole()) - || !roles.hasEditPermission(user.getId(), "finance.approval.decide") || currentlyResolved == null - || !Objects.equals(currentlyResolved.getId(), token.getFirstApproverId())) - throw new BusinessException("预览中的首位审批人已失效,请重新预览", 409); - } - - private SysUser resolveLocalApprover(SysApprovalNode node) { - if (node.getApproverId() != null) { - SysUser user = users.findById(node.getApproverId()).orElse(null); - return user != null && ApprovalRoutingRules.matchesRole(user, node.getApproverRole()) - && roles.hasEditPermission(user.getId(), "finance.approval.decide") ? user : null; - } - List candidates = new ArrayList<>(users.findAll()); - candidates.sort(Comparator.comparing(SysUser::getId, Comparator.nullsLast(Long::compareTo))); - for (SysUser candidate : candidates) - if (ApprovalRoutingRules.matchesRole(candidate, node.getApproverRole()) - && roles.hasEditPermission(candidate.getId(), "finance.approval.decide")) return candidate; - return null; - } - private void applyApprovalStatus(ReimApplication app, String status) { app.setApprovalStatus(status); app.setCurrentApproverId(null); if (ApprovalStatus.PENDING.name().equals(status)) { @@ -286,8 +257,9 @@ public class ReimbursementSubmissionStateService { } if (sum.compareTo(app.getTotalAmount()) != 0) throw new BusinessException("费用明细合计必须等于总金额"); if (app.getPayeeBankId() == null || !banks.findById(app.getPayeeBankId()) - .map(b -> Objects.equals(app.getApplicantId(), b.getUserId())).orElse(false)) - throw new BusinessException("收款银行账户不属于本人"); + .map(b -> Objects.equals(app.getApplicantId(), b.getUserId()) + && "ACTIVE".equalsIgnoreCase(b.getStatus())).orElse(false)) + throw new BusinessException("收款银行账户不属于本人或已停用"); } private void requirePermission(Long userId) { diff --git a/src/main/java/com/finance/system/storage/AliyunOssFileStorage.java b/src/main/java/com/finance/system/storage/AliyunOssFileStorage.java new file mode 100644 index 0000000..5a39e65 --- /dev/null +++ b/src/main/java/com/finance/system/storage/AliyunOssFileStorage.java @@ -0,0 +1,129 @@ +package com.finance.system.storage; + +import com.aliyun.oss.ClientException; +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.OSSException; +import com.aliyun.oss.model.CannedAccessControlList; +import com.aliyun.oss.model.ObjectMetadata; +import com.aliyun.oss.model.PutObjectRequest; +import com.finance.system.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PreDestroy; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +@Slf4j +@Component +@RequiredArgsConstructor +public class AliyunOssFileStorage implements FileStorage { + private final FileStorageProperties properties; + private volatile OSS client; + + @Override + public String providerCode() { + return "aliyun-oss"; + } + + @Override + public void validateConfiguration() { + FileStorageProperties.AliyunOss oss = properties.getAliyunOss(); + if (!StringUtils.hasText(oss.getRegion()) || !StringUtils.hasText(oss.getEndpoint()) + || !StringUtils.hasText(oss.getBucket())) { + throw new IllegalStateException("阿里云 OSS 模式必须配置 region、endpoint 和 bucket"); + } + if (!StringUtils.hasText(oss.getAccessKeyId()) || !StringUtils.hasText(oss.getAccessKeySecret())) { + throw new IllegalStateException("阿里云 OSS 模式必须通过环境变量配置访问凭据"); + } + } + + @Override + public void put(String objectKey, String contentType, byte[] content) { + StorageObjectKeyPolicy.requireValid(objectKey); + if (content == null || content.length == 0) throw new BusinessException("附件内容不能为空", 400); + verifyPrivateBucket(); + FileStorageProperties.AliyunOss config = properties.getAliyunOss(); + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentLength(content.length); + if (StringUtils.hasText(contentType)) metadata.setContentType(contentType); + try (ByteArrayInputStream input = new ByteArrayInputStream(content)) { + PutObjectRequest request = new PutObjectRequest(config.getBucket(), objectKey, input, metadata); + oss().putObject(request); + } catch (OSSException e) { + log.warn("阿里云 OSS 附件上传失败: region={}, bucket={}, objectKey={}, errorCode={}, requestId={}", + config.getRegion(), config.getBucket(), objectKey, e.getErrorCode(), e.getRequestId()); + throw new BusinessException("附件持久化存储失败", 502); + } catch (ClientException | IOException e) { + log.warn("阿里云 OSS 附件上传失败: region={}, bucket={}, objectKey={}", + config.getRegion(), config.getBucket(), objectKey, e); + throw new BusinessException("附件持久化存储失败", 502); + } + } + + @Override + public void delete(String objectKey) { + StorageObjectKeyPolicy.requireValid(objectKey); + FileStorageProperties.AliyunOss config = properties.getAliyunOss(); + try { + oss().deleteObject(config.getBucket(), objectKey); + } catch (OSSException e) { + log.warn("阿里云 OSS 附件删除失败: region={}, bucket={}, objectKey={}, errorCode={}, requestId={}", + config.getRegion(), config.getBucket(), objectKey, e.getErrorCode(), e.getRequestId()); + throw new BusinessException("附件持久化对象删除失败", 502); + } catch (ClientException e) { + log.warn("阿里云 OSS 附件删除失败: region={}, bucket={}, objectKey={}", + config.getRegion(), config.getBucket(), objectKey, e); + throw new BusinessException("附件持久化对象删除失败", 502); + } + } + + private void verifyPrivateBucket() { + FileStorageProperties.AliyunOss config = properties.getAliyunOss(); + try { + CannedAccessControlList acl = oss().getBucketAcl(config.getBucket()).getCannedACL(); + if (!CannedAccessControlList.Private.equals(acl)) { + throw new BusinessException("阿里云 OSS 存储桶必须设置为私有", 500); + } + } catch (OSSException e) { + log.warn("阿里云 OSS 私有桶校验失败: region={}, bucket={}, errorCode={}, requestId={}", + config.getRegion(), config.getBucket(), e.getErrorCode(), e.getRequestId()); + throw new BusinessException("无法确认阿里云 OSS 存储桶为私有", 502); + } catch (ClientException e) { + log.warn("阿里云 OSS 私有桶校验失败: region={}, bucket={}", + config.getRegion(), config.getBucket(), e); + throw new BusinessException("无法确认阿里云 OSS 存储桶为私有", 502); + } + } + + private OSS oss() { + OSS value = client; + if (value != null) return value; + synchronized (this) { + if (client == null) { + validateConfiguration(); + FileStorageProperties.AliyunOss config = properties.getAliyunOss(); + if (StringUtils.hasText(config.getSessionToken())) { + client = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), + config.getAccessKeySecret(), config.getSessionToken()); + } else { + client = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), + config.getAccessKeySecret()); + } + } + return client; + } + } + + @PreDestroy + public void shutdown() { + OSS value = client; + if (value != null) { + value.shutdown(); + client = null; + } + } +} diff --git a/src/main/java/com/finance/system/storage/FileStorage.java b/src/main/java/com/finance/system/storage/FileStorage.java new file mode 100644 index 0000000..0920f4a --- /dev/null +++ b/src/main/java/com/finance/system/storage/FileStorage.java @@ -0,0 +1,12 @@ +package com.finance.system.storage; + +/** Private object storage used by business attachments. Implementations never expose public URLs. */ +public interface FileStorage { + String providerCode(); + + void validateConfiguration(); + + void put(String objectKey, String contentType, byte[] content); + + void delete(String objectKey); +} diff --git a/src/main/java/com/finance/system/storage/FileStorageCleanupService.java b/src/main/java/com/finance/system/storage/FileStorageCleanupService.java new file mode 100644 index 0000000..dca5d8d --- /dev/null +++ b/src/main/java/com/finance/system/storage/FileStorageCleanupService.java @@ -0,0 +1,136 @@ +package com.finance.system.storage; + +import com.finance.system.entity.FileStorageCleanupTask; +import com.finance.system.entity.ReimAttachment; +import com.finance.system.repository.FileStorageCleanupTaskRepository; +import com.finance.system.repository.ReimAttachmentRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.List; + +/** Durable, idempotent cleanup queue for private storage objects. */ +@Slf4j +@Service +@RequiredArgsConstructor +public class FileStorageCleanupService { + private static final String PENDING = "PENDING"; + private static final String COMPLETED = "COMPLETED"; + private static final String PERSISTING = "PERSISTING"; + private static final String DELETED = "DELETED"; + private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai"); + + private final FileStorageCleanupTaskRepository tasks; + private final ReimAttachmentRepository attachments; + private final FileStorageManager fileStorage; + private final TransactionTemplate transactions; + + @Value("${file.storage.cleanup.stale-upload-minutes:60}") + private long staleUploadMinutes; + + /** Called inside the same transaction that tombstones the attachment. */ + public void enqueue(ReimAttachment attachment, String reason) { + if (attachment == null || !StringUtils.hasText(attachment.getStorageProvider()) + || !StringUtils.hasText(attachment.getStorageObjectKey())) { + return; + } + if (tasks.existsByStorageProviderAndStorageObjectKey( + attachment.getStorageProvider(), attachment.getStorageObjectKey())) { + return; + } + tasks.save(FileStorageCleanupTask.builder() + .attachmentId(attachment.getId()) + .storageProvider(attachment.getStorageProvider()) + .storageObjectKey(attachment.getStorageObjectKey()) + .cleanupReason(normalizeReason(reason)) + .taskStatus(PENDING) + .attemptCount(0) + .nextAttemptAt(now()) + .build()); + } + + @Scheduled(fixedDelayString = "${file.storage.cleanup.interval-ms:30000}", initialDelayString = "10000") + public void processDueTasks() { + List due = tasks + .findTop20ByTaskStatusAndNextAttemptAtLessThanEqualOrderByIdAsc(PENDING, now()); + for (FileStorageCleanupTask task : due) processOne(task.getId()); + } + + @Scheduled(fixedDelayString = "${file.storage.cleanup.interval-ms:30000}", initialDelayString = "15000") + @Transactional + public void enqueueStaleUploads() { + long minutes = Math.max(1L, staleUploadMinutes); + List stale = attachments + .findTop50ByUploadStatusAndCreatedAtBeforeOrderByIdAsc(PERSISTING, now().minusMinutes(minutes)); + for (ReimAttachment candidate : stale) { + ReimAttachment locked = attachments.findByIdForUpdate(candidate.getId()).orElse(null); + if (locked == null || !PERSISTING.equals(locked.getUploadStatus())) continue; + locked.setApplicationId(null); + locked.setExpenseItemId(null); + locked.setUploadStatus(DELETED); + attachments.save(locked); + enqueue(locked, "上传未完成超时清理"); + log.warn("附件上传长时间未完成,已进入持久化对象清理队列: attachmentId={}", locked.getId()); + } + } + + private void processOne(Long taskId) { + FileStorageCleanupTask snapshot = tasks.findById(taskId).orElse(null); + if (snapshot == null || !PENDING.equals(snapshot.getTaskStatus()) + || snapshot.getNextAttemptAt().isAfter(now())) { + return; + } + try { + fileStorage.delete(snapshot.getStorageProvider(), snapshot.getStorageObjectKey()); + transactions.executeWithoutResult(status -> tasks.findById(taskId).ifPresent(current -> { + if (!PENDING.equals(current.getTaskStatus())) return; + current.setTaskStatus(COMPLETED); + current.setCompletedAt(now()); + current.setLastError(null); + tasks.save(current); + })); + log.info("附件持久化对象清理完成: taskId={}, attachmentId={}, provider={}, reason={}", + snapshot.getId(), snapshot.getAttachmentId(), snapshot.getStorageProvider(), + snapshot.getCleanupReason()); + } catch (RuntimeException failure) { + transactions.executeWithoutResult(status -> tasks.findById(taskId).ifPresent(current -> { + if (!PENDING.equals(current.getTaskStatus())) return; + int attempts = current.getAttemptCount() == null ? 1 : current.getAttemptCount() + 1; + current.setAttemptCount(attempts); + current.setLastError(safeError(failure)); + current.setNextAttemptAt(now().plusSeconds(backoffSeconds(attempts))); + tasks.save(current); + })); + log.warn("附件持久化对象清理失败,将自动重试: taskId={}, attachmentId={}, provider={}", + snapshot.getId(), snapshot.getAttachmentId(), snapshot.getStorageProvider()); + } + } + + private static long backoffSeconds(int attempts) { + int exponent = Math.min(Math.max(attempts - 1, 0), 7); + return Math.min(30L * (1L << exponent), 3600L); + } + + private static String normalizeReason(String reason) { + String value = StringUtils.hasText(reason) ? reason.trim() : "附件记录已删除"; + return value.length() <= 100 ? value : value.substring(0, 100); + } + + private static String safeError(Throwable failure) { + String value = failure.getMessage(); + if (!StringUtils.hasText(value)) value = failure.getClass().getSimpleName(); + return value.length() <= 500 ? value : value.substring(0, 500); + } + + private static LocalDateTime now() { + return LocalDateTime.now(SHANGHAI); + } +} diff --git a/src/main/java/com/finance/system/storage/FileStorageManager.java b/src/main/java/com/finance/system/storage/FileStorageManager.java new file mode 100644 index 0000000..9eb1a28 --- /dev/null +++ b/src/main/java/com/finance/system/storage/FileStorageManager.java @@ -0,0 +1,57 @@ +package com.finance.system.storage; + +import com.finance.system.exception.BusinessException; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +@Component +public class FileStorageManager { + private final FileStorageProperties properties; + private final Map providers = new HashMap<>(); + private FileStorage active; + + public FileStorageManager(FileStorageProperties properties, List providers) { + this.properties = properties; + for (FileStorage provider : providers) { + FileStorage previous = this.providers.put(provider.providerCode(), provider); + if (previous != null) throw new IllegalStateException("文件存储提供方代码重复: " + provider.providerCode()); + } + } + + @PostConstruct + public void initialize() { + String provider = normalize(properties.getProvider()); + active = providers.get(provider); + if (active == null) throw new IllegalStateException("不支持的文件存储提供方: " + provider); + active.validateConfiguration(); + } + + public StoredObject put(String objectKey, String contentType, byte[] content) { + StorageObjectKeyPolicy.requireValid(objectKey); + active.put(objectKey, contentType, content); + return new StoredObject(active.providerCode(), objectKey); + } + + public String activeProviderCode() { + return active.providerCode(); + } + + public void delete(String providerCode, String objectKey) { + StorageObjectKeyPolicy.requireValid(objectKey); + FileStorage provider = providers.get(normalize(providerCode)); + if (provider == null) throw new BusinessException("附件原存储提供方不可用,暂未删除持久化对象", 500); + provider.validateConfiguration(); + provider.delete(objectKey); + } + + private static String normalize(String provider) { + if (!StringUtils.hasText(provider)) return "local"; + return provider.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/com/finance/system/storage/FileStorageProperties.java b/src/main/java/com/finance/system/storage/FileStorageProperties.java new file mode 100644 index 0000000..386825c --- /dev/null +++ b/src/main/java/com/finance/system/storage/FileStorageProperties.java @@ -0,0 +1,33 @@ +package com.finance.system.storage; + +import lombok.Data; +import lombok.ToString; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "file.storage") +public class FileStorageProperties { + private String provider = "local"; + private Local local = new Local(); + private AliyunOss aliyunOss = new AliyunOss(); + + @Data + public static class Local { + private String basePath = "./uploads"; + } + + @Data + public static class AliyunOss { + private String region; + private String endpoint; + private String bucket; + @ToString.Exclude + private String accessKeyId; + @ToString.Exclude + private String accessKeySecret; + @ToString.Exclude + private String sessionToken; + } +} diff --git a/src/main/java/com/finance/system/storage/LocalFileStorage.java b/src/main/java/com/finance/system/storage/LocalFileStorage.java new file mode 100644 index 0000000..fb8b49a --- /dev/null +++ b/src/main/java/com/finance/system/storage/LocalFileStorage.java @@ -0,0 +1,68 @@ +package com.finance.system.storage; + +import com.finance.system.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; + +@Slf4j +@Component +@RequiredArgsConstructor +public class LocalFileStorage implements FileStorage { + private final FileStorageProperties properties; + + @Override + public String providerCode() { + return "local"; + } + + @Override + public void validateConfiguration() { + if (!StringUtils.hasText(properties.getLocal().getBasePath())) { + throw new IllegalStateException("本地文件存储目录不能为空"); + } + } + + @Override + public void put(String objectKey, String contentType, byte[] content) { + StorageObjectKeyPolicy.requireValid(objectKey); + if (content == null || content.length == 0) throw new BusinessException("附件内容不能为空", 400); + Path target = resolve(objectKey); + try { + Files.createDirectories(target.getParent()); + try (OutputStream output = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE)) { + output.write(content); + } + } catch (IOException e) { + log.error("本地附件持久化失败: objectKey={}", objectKey, e); + throw new BusinessException("附件持久化存储失败", 500); + } + } + + @Override + public void delete(String objectKey) { + StorageObjectKeyPolicy.requireValid(objectKey); + try { + Files.deleteIfExists(resolve(objectKey)); + } catch (IOException e) { + log.error("本地附件持久化对象删除失败: objectKey={}", objectKey, e); + throw new BusinessException("附件持久化对象删除失败", 500); + } + } + + private Path resolve(String objectKey) { + Path root = Paths.get(properties.getLocal().getBasePath()).toAbsolutePath().normalize(); + Path target = root.resolve(objectKey.replace('/', java.io.File.separatorChar)).normalize(); + if (!target.startsWith(root)) throw new BusinessException("附件存储对象标识无效", 500); + return target; + } +} diff --git a/src/main/java/com/finance/system/storage/StorageObjectKeyPolicy.java b/src/main/java/com/finance/system/storage/StorageObjectKeyPolicy.java new file mode 100644 index 0000000..55df776 --- /dev/null +++ b/src/main/java/com/finance/system/storage/StorageObjectKeyPolicy.java @@ -0,0 +1,51 @@ +package com.finance.system.storage; + +import com.finance.system.exception.BusinessException; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.UUID; +import java.util.regex.Pattern; + +@Component +public class StorageObjectKeyPolicy { + private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai"); + private static final DateTimeFormatter DATE_PATH = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + private static final Pattern PREFIX = Pattern.compile("[a-z0-9][a-z0-9/-]{0,119}"); + private static final Pattern KEY = Pattern.compile("[a-z0-9][a-z0-9/_-]{0,488}(?:\\.[a-z0-9]{1,10})?"); + + public String randomKey(String businessPrefix, String originalFileName) { + String prefix = businessPrefix == null ? "" : businessPrefix.trim().toLowerCase(Locale.ROOT); + if (!PREFIX.matcher(prefix).matches() || prefix.contains("..") || prefix.contains("//") + || prefix.endsWith("/")) { + throw new IllegalArgumentException("非法的附件业务前缀"); + } + String extension = extension(originalFileName); + String key = prefix + "/" + LocalDate.now(SHANGHAI).format(DATE_PATH) + "/" + + UUID.randomUUID().toString().replace("-", "") + extension; + requireValid(key); + return key; + } + + public static void requireValid(String objectKey) { + if (!StringUtils.hasText(objectKey) || objectKey.length() > 500 + || objectKey.startsWith("/") || objectKey.endsWith("/") + || objectKey.contains("..") || objectKey.contains("\\") + || !KEY.matcher(objectKey).matches()) { + throw new BusinessException("附件存储对象标识无效", 500); + } + } + + private static String extension(String originalFileName) { + if (!StringUtils.hasText(originalFileName)) return ""; + int dot = originalFileName.lastIndexOf('.'); + if (dot < 0 || dot == originalFileName.length() - 1) return ""; + String value = originalFileName.substring(dot + 1).toLowerCase(Locale.ROOT); + if (!value.matches("[a-z0-9]{1,10}")) return ""; + return "." + value; + } +} diff --git a/src/main/java/com/finance/system/storage/StoredObject.java b/src/main/java/com/finance/system/storage/StoredObject.java new file mode 100644 index 0000000..88341dd --- /dev/null +++ b/src/main/java/com/finance/system/storage/StoredObject.java @@ -0,0 +1,9 @@ +package com.finance.system.storage; + +import lombok.Value; + +@Value +public class StoredObject { + String provider; + String objectKey; +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ac79b98..c7e06dc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,16 +1,21 @@ server: port: 8080 + error: + include-message: never + include-binding-errors: never + include-stacktrace: never + include-exception: false spring: application: - name: finance-system + name: financial_system_backend servlet: multipart: max-file-size: 50MB max-request-size: 51MB datasource: url: "${DB_URL:jdbc:mysql://localhost:3306/finance_system?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}" - username: "${DB_USERNAME:root}" - password: "${DB_PASSWORD:123456}" + username: "${DB_USERNAME}" + password: "${DB_PASSWORD}" driver-class-name: com.mysql.cj.jdbc.Driver hikari: maximum-pool-size: 20 @@ -24,23 +29,52 @@ spring: properties: hibernate: format_sql: true - dialect: org.hibernate.dialect.MySQL57Dialect + dialect: org.hibernate.dialect.MySQL8Dialect open-in-view: false database: # Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone. time-zone: "${DB_TIME_ZONE:Asia/Shanghai}" +# ============================================================================= +# 阿里云 OSS 文件存储配置(需要启用 OSS 时填写这里对应的环境变量) +# 1. 将 FILE_STORAGE_PROVIDER 设置为 aliyun-oss。 +# 2. 在 IDEA Run/Debug Configuration -> Environment variables 中填写: +# OSS_REGION、OSS_ENDPOINT、OSS_BUCKET、OSS_ACCESS_KEY_ID、OSS_ACCESS_KEY_SECRET。 +# 3. 使用 STS 临时凭据时再填写 OSS_SESSION_TOKEN;长期 RAM AccessKey 留空即可。 +# 4. Bucket 必须设置为私有。未填写前保持 local,系统继续使用 ./uploads 本地目录。 +# ============================================================================= +file: + storage: + # 可选值:local、aliyun-oss + provider: "${FILE_STORAGE_PROVIDER:local}" + local: + base-path: "${FILE_STORAGE_LOCAL_BASE_PATH:./uploads}" + aliyun-oss: + # 示例区域:cn-hangzhou(必填) + region: "${OSS_REGION:}" + # 示例地址:https://oss-cn-hangzhou.aliyuncs.com(必填) + endpoint: "${OSS_ENDPOINT:}" + # 私有 Bucket 名称(必填) + bucket: "${OSS_BUCKET:}" + # RAM 用户或 STS 临时凭据,通过 IDEA 环境变量填写,不要提交真实值 + access-key-id: "${OSS_ACCESS_KEY_ID:}" + access-key-secret: "${OSS_ACCESS_KEY_SECRET:}" + # 仅 STS 临时凭据需要填写 + session-token: "${OSS_SESSION_TOKEN:}" + cleanup: + interval-ms: ${FILE_STORAGE_CLEANUP_INTERVAL_MS:30000} + stale-upload-minutes: ${FILE_STORAGE_STALE_UPLOAD_MINUTES:60} jwt: - secret: "${JWT_SECRET:local-only-insecure-secret-change-before-deploy}" + secret: "${JWT_SECRET}" expiration: ${JWT_EXPIRATION:86400000} auth: time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}" feishu: # Feishu credentials are file/env only (not editable via 配置管理 UI). - enabled: ${FEISHU_ENABLED:true} - app-id: "${FEISHU_APP_ID:cli_aa1d754854f95ccd}" - app-secret: "${FEISHU_APP_SECRET:Uqen22fWWeubQ6f2dFIWteMDIhd4PU4u}" + enabled: ${FEISHU_ENABLED:false} + app-id: "${FEISHU_APP_ID:}" + app-secret: "${FEISHU_APP_SECRET:}" redirect-uri: "${FEISHU_REDIRECT_URI:http://127.0.0.1:8080/api/feishu/callback}" - sync-org-enabled: ${FEISHU_SYNC_ORG_ENABLED:true} + sync-org-enabled: ${FEISHU_SYNC_ORG_ENABLED:false} local-bootstrap-enabled: ${FEISHU_LOCAL_BOOTSTRAP_ENABLED:false} local-bootstrap-open-id: "${FEISHU_LOCAL_BOOTSTRAP_OPEN_ID:}" directory: @@ -58,9 +92,19 @@ feishu: encrypt-key: ${FEISHU_ENCRYPT_KEY:} app: frontend-url: ${FRONTEND_URL:http://localhost:5173} + frontend-allowed-origins: "${FRONTEND_ALLOWED_ORIGINS:http://localhost:5173}" # Required when saving secret=true integration settings. Never put a real # key in this file; provide APP_INTEGRATION_ENCRYPTION_KEY at deployment. - integration-encryption-key: "${APP_INTEGRATION_ENCRYPTION_KEY:9Srk7wn4ayAb1TyPRFfdlyDQB6h9ss3f}" + integration-encryption-key: "${APP_INTEGRATION_ENCRYPTION_KEY:}" + bank-account: + # Comma-separated version=Base64(32-byte key) entries. Keep old versions + # during rotation; never commit real keys to this repository. + encryption-keys: "${APP_BANK_ACCOUNT_ENCRYPTION_KEYS:}" + fingerprint-key: "${APP_BANK_ACCOUNT_FINGERPRINT_KEY:}" + active-key-version: "${APP_BANK_ACCOUNT_ACTIVE_KEY_VERSION:}" + # 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} kingdee: # System account for sync/query. Employee write ops require bound accounts. enabled: ${KINGDEE_ENABLED:false} @@ -71,13 +115,22 @@ kingdee: db-id: ${KINGDEE_DB_ID:} logging: level: - com.finance.system: DEBUG - com.finance.system.adapter.feishu.FeishuDirectoryService: DEBUG + com.finance.system: "${APP_LOG_LEVEL:INFO}" + com.finance.system.adapter.feishu.FeishuDirectoryService: "${FEISHU_DIRECTORY_LOG_LEVEL:INFO}" org.springframework.security: INFO org.hibernate.SQL: WARN springdoc: api-docs: path: /v3/api-docs + enabled: ${OPENAPI_ENABLED:false} swagger-ui: path: /swagger-ui.html - enabled: true + enabled: ${OPENAPI_ENABLED:false} +management: + endpoints: + web: + exposure: + include: health,prometheus + endpoint: + health: + show-details: never diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml deleted file mode 100644 index aed2e28..0000000 --- a/src/main/resources/logback-spring.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - UTF-8 - - - - - ${LOG_PATH}/${APP_NAME}.log - - ${LOG_PATH}/${APP_NAME}.%d{yyyy-MM-dd}.%i.log.gz - 50MB - 30 - 2GB - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - UTF-8 - - - - - 1024 - 0 - - - - - - - - - - - - diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilderTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilderTest.java deleted file mode 100644 index b4f27f6..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilderTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.dto.ReimbursementFormField; -import com.finance.system.entity.ReimApplication; -import com.finance.system.util.Sha256; -import org.junit.jupiter.api.Test; - -import java.math.BigDecimal; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; - -class FeishuApprovalFormBuilderTest { - private final ObjectMapper json = new ObjectMapper(); - - @Test - void buildsNumericAmountCurrencyAttachmentsFormulaAndTwoDimensionalFieldList() throws Exception { - ReimbursementFormField amount = field("amount-id", "amount", "DECIMAL", "EXPENSE_AMOUNT", "金额", false); - amount.setCurrency("CNY"); - ReimbursementFormField attachment = field("attachment-id", "attachmentV2", "ATTACHMENT", "EXPENSE_ATTACHMENT", "附件", false); - ReimbursementFormField reason = field("reason-id", "input", "TEXT", "EXPENSE_DESCRIPTION", "报销事由", false); - ReimbursementFormField date = field("date-id", "date", "DATE", "EXPENSE_DATE", "发生日期", false); - ReimbursementFormField details = field("detail-id", "fieldList", "EXPENSE_ITEMS", "EXPENSE_ITEMS", "明细", false); - details.setChildren(Arrays.asList(reason, date, amount, attachment)); - ReimbursementFormField formula = field("formula-id", "formula", "FORMULA", "TOTAL_AMOUNT", "总金额", true); - ReimbursementFormField topAmount = field("top-amount-id", "amount", "DECIMAL", "CUSTOM", "预支金额", false); - topAmount.setCurrency("CNY"); - List fields = Arrays.asList(details, formula, topAmount); - - Map attachmentValue = new LinkedHashMap<>(); - attachmentValue.put("attachment_id", 7L); - attachmentValue.put("provider_code", "provider-file-code"); - attachmentValue.put("display_name", "receipt.pdf"); - Map row = new LinkedHashMap<>(); - row.put("reason-id", "差旅"); - row.put("date-id", "2026-09-30T00:00:00+08:00"); - row.put("amount-id", new BigDecimal("12.30")); - row.put("attachment-id", Collections.singletonList(attachmentValue)); - Map display = new LinkedHashMap<>(); - display.put("detail-id", Collections.singletonList(row)); - display.put("formula-id", new BigDecimal("12.30")); - - ReimApplication app = new ReimApplication(); - String schema = json.writeValueAsString(fields); - app.setFeishuFormSchema(schema); - app.setFeishuFormFingerprint(Sha256.hex(schema)); - app.setFeishuFormValues("{\"top-amount-id\":12.30}"); - app.setFeishuFormDisplayValues(json.writeValueAsString(display)); - app.setTotalAmount(new BigDecimal("12.30")); - - JsonNode form = json.readTree(FeishuApprovalFormBuilder.buildFormJson(app)); - assertThat(form.isArray()).isTrue(); - JsonNode detail = form.get(0); - assertThat(detail.path("id").asText()).isEqualTo("detail-id"); - assertThat(detail.path("value").isArray()).isTrue(); - assertThat(detail.path("value").get(0).isArray()).isTrue(); - Map controls = new HashMap<>(); - for (JsonNode control : detail.path("value").get(0)) controls.put(control.path("id").asText(), control); - assertThat(controls.get("amount-id").path("value").isNumber()).isTrue(); - assertThat(controls.get("amount-id").path("value").decimalValue()).isEqualByComparingTo("12.3"); - assertThat(controls.get("amount-id").path("currency").asText()).isEqualTo("CNY"); - assertThat(controls.get("attachment-id").path("value").isArray()).isTrue(); - assertThat(controls.get("attachment-id").path("value").get(0).asText()).isEqualTo("provider-file-code"); - assertThat(form.get(1).path("value").isNumber()).isTrue(); - assertThat(form.get(1).path("value").decimalValue()).isEqualByComparingTo("12.3"); - assertThat(form.get(2).path("currency").asText()).isEqualTo("CNY"); - assertThat(form.get(2).path("value").decimalValue()).isEqualByComparingTo("12.3"); - } - - private static ReimbursementFormField field(String id, String providerType, String type, - String binding, String label, boolean readOnly) { - return ReimbursementFormField.builder().id(id).valueKey(id).providerType(providerType).type(type) - .binding(binding).label(label).required(true).readOnly(readOnly).build(); - } -} diff --git a/src/test/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizerTest.java b/src/test/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizerTest.java deleted file mode 100644 index 22dc2ab..0000000 --- a/src/test/java/com/finance/system/adapter/feishu/FeishuDefinitionNormalizerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.finance.system.adapter.feishu; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.dto.ReimbursementFormField; -import org.junit.jupiter.api.Test; - -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class FeishuDefinitionNormalizerTest { - private final ObjectMapper json = new ObjectMapper(); - - @Test - void normalizesExactLiveNoCustomIdTemplateWithoutReplacingProviderIds() throws Exception { - String source = "{\"data\":{\"approval_code\":\"approval-live\"," - + "\"nodes\":[{\"id\":\"node-provider-1\",\"name\":\"财务审批\"}]," - + "\"form\":[" - + control("contact-id", "contact", "报销人", true, null) + "," - + control("department-id", "department", "报销人所属部门", true, null) + "," - + control("reimbursement-date-id", "date", "报销日期", true, null) + "," - + control("detail-provider-id", "fieldList", "明细", true, - "\"children\":[" - + control("reason-id", "input", "报销事由", true, null) + "," - + control("date-id", "date", "发生日期", true, null) + "," - + control("amount-id", "amount", "金额", true, - "\"option\":{\"currencyRange\":[\"CNY\",\"JPY\",\"USD\"]}") + "," - + control("attachment-id", "attachmentV2", "附件", true, null) + "]") + "," - + control("formula-id", "formula", "总金额", true, null) - + "]}}"; - - FeishuDefinitionNormalizer.NormalizedDefinition normalized = - new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "ignored"); - - assertThat(normalized.getApprovalCode()).isEqualTo("approval-live"); - assertThat(normalized.getNodes().get(0).getNodeKey()).isEqualTo("node-provider-1"); - Map top = byBinding(normalized.getFormFields()); - assertThat(top.get("APPLICANT_CONTACT").getId()).isEqualTo("contact-id"); - assertThat(top.get("APPLICANT_DEPARTMENT").getId()).isEqualTo("department-id"); - assertThat(top.get("REIMBURSEMENT_DATE").getId()).isEqualTo("reimbursement-date-id"); - assertThat(top.get("TOTAL_AMOUNT").getType()).isEqualTo("FORMULA"); - ReimbursementFormField details = top.get("EXPENSE_ITEMS"); - assertThat(details.getId()).isEqualTo("detail-provider-id"); - Map children = byBinding(details.getChildren()); - assertThat(children.keySet()).containsExactlyInAnyOrder( - "EXPENSE_DESCRIPTION", "EXPENSE_DATE", "EXPENSE_AMOUNT", "EXPENSE_ATTACHMENT"); - assertThat(children.get("EXPENSE_AMOUNT").getCurrency()).isEqualTo("CNY"); - assertThat(children.get("EXPENSE_AMOUNT").getOptions()).extracting("value").containsExactlyInAnyOrder("CNY", "JPY", "USD"); - assertThat(children.get("EXPENSE_ATTACHMENT").getType()).isEqualTo("ATTACHMENT"); - assertThat(children.get("EXPENSE_ATTACHMENT").getId()).isEqualTo("attachment-id"); - } - - @Test - void acceptsV2ChoiceOptionsFromValueArray() throws Exception { - String source = "{\"data\":{\"nodes\":[{\"id\":\"n1\"}],\"form\":[" - + "{\"id\":\"r\",\"custom_id\":\"choice\",\"type\":\"radioV2\",\"name\":\"单选\"," - + "\"value\":[{\"value\":\"a\",\"name\":\"甲\"}]}," - + "{\"id\":\"c\",\"custom_id\":\"choices\",\"type\":\"checkboxV2\",\"name\":\"多选\"," - + "\"value\":[{\"value\":\"b\",\"name\":\"乙\"}]}]}}"; - FeishuDefinitionNormalizer.NormalizedDefinition normalized = - new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "approval"); - assertThat(normalized.getFormFields().get(0).getOptions().get(0).getValue()).isEqualTo("a"); - assertThat(normalized.getFormFields().get(1).getOptions().get(0).getValue()).isEqualTo("b"); - } - - @Test - void rejectsDateTimeDefinitionFormatButKeepsDateOnlyDefault() throws Exception { - String source = "{\"data\":{\"nodes\":[{\"id\":\"n1\"}],\"form\":[" - + "{\"id\":\"d\",\"custom_id\":\"day\",\"type\":\"date\",\"name\":\"日期\"," - + "\"property\":{\"format\":\"YYYY-MM-DD HH:mm\"}}]}}"; - assertThatThrownBy(() -> new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "approval")) - .isInstanceOf(com.finance.system.exception.BusinessException.class); - } - - private static Map byBinding(List fields) { - Map result = new LinkedHashMap<>(); - for (ReimbursementFormField field : fields) result.put(field.getBinding(), field); - return result; - } - - private static String control(String id, String type, String name, boolean required, String extra) { - return "{\"id\":\"" + id + "\",\"type\":\"" + type + "\",\"name\":\"" + name - + "\",\"required\":" + required + (extra == null ? "" : "," + extra) + "}"; - } -} diff --git a/src/test/java/com/finance/system/config/SecureConfigurationDefaultsTest.java b/src/test/java/com/finance/system/config/SecureConfigurationDefaultsTest.java new file mode 100644 index 0000000..728b7d8 --- /dev/null +++ b/src/test/java/com/finance/system/config/SecureConfigurationDefaultsTest.java @@ -0,0 +1,49 @@ +package com.finance.system.config; + +import com.finance.system.adapter.feishu.FeishuConfig; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.util.Scanner; + +import static org.assertj.core.api.Assertions.assertThat; + +class SecureConfigurationDefaultsTest { + + @Test + void externalIntegrationsAreDisabledByDefault() { + FeishuConfig config = new FeishuConfig(); + + assertThat(config.isEnabled()).isFalse(); + assertThat(config.isSyncOrgEnabled()).isFalse(); + } + + @Test + void repositoryConfigurationDoesNotProvideDefaultSecrets() { + String yaml = applicationYaml(); + + assertThat(yaml) + .contains("username: \"${DB_USERNAME}\"") + .contains("password: \"${DB_PASSWORD}\"") + .contains("secret: \"${JWT_SECRET}\"") + .contains("enabled: ${FEISHU_ENABLED:false}") + .contains("app-secret: \"${FEISHU_APP_SECRET:}\"") + .contains("integration-encryption-key: \"${APP_INTEGRATION_ENCRYPTION_KEY:}\"") + .contains("encryption-keys: \"${APP_BANK_ACCOUNT_ENCRYPTION_KEYS:}\"") + .contains("fingerprint-key: \"${APP_BANK_ACCOUNT_FINGERPRINT_KEY:}\"") + .contains("active-key-version: \"${APP_BANK_ACCOUNT_ACTIVE_KEY_VERSION:}\"") + .contains("legacy-backfill-enabled: ${APP_BANK_ACCOUNT_LEGACY_BACKFILL_ENABLED:false}") + .contains("enabled: ${OPENAPI_ENABLED:false}") + .contains("include-message: never") + .contains("show-details: never"); + } + + private String applicationYaml() { + InputStream input = getClass().getClassLoader().getResourceAsStream("application.yml"); + assertThat(input).isNotNull(); + try (Scanner scanner = new Scanner(input, "UTF-8")) { + scanner.useDelimiter("\\A"); + return scanner.hasNext() ? scanner.next() : ""; + } + } +} diff --git a/src/test/java/com/finance/system/finance/rules/FinancialBusinessRulesTest.java b/src/test/java/com/finance/system/finance/rules/FinancialBusinessRulesTest.java new file mode 100644 index 0000000..132ccaa --- /dev/null +++ b/src/test/java/com/finance/system/finance/rules/FinancialBusinessRulesTest.java @@ -0,0 +1,81 @@ +package com.finance.system.finance.rules; + +import com.finance.system.exception.BadRequestException; +import org.junit.jupiter.api.Test; +import java.math.BigDecimal; +import static org.junit.jupiter.api.Assertions.*; + +class FinancialBusinessRulesTest { + private static final BigDecimal ZERO = BigDecimal.ZERO; + private static final BigDecimal ONE = BigDecimal.ONE; + private static final BigDecimal NEGATIVE = ONE.negate(); + + @Test void payeeTypeAndIdentityAreExclusive() { + assertDoesNotThrow(() -> FinancialBusinessRules.payee("EMPLOYEE", 1L, null)); + assertDoesNotThrow(() -> FinancialBusinessRules.payee("SUPPLIER", null, "credit")); + for (String type : new String[]{null, "", "OTHER"}) { + invalid(() -> FinancialBusinessRules.payee(type, 1L, null)); + } + invalid(() -> FinancialBusinessRules.payee("EMPLOYEE", null, null)); + invalid(() -> FinancialBusinessRules.payee("EMPLOYEE", 1L, "credit")); + invalid(() -> FinancialBusinessRules.payee("EMPLOYEE", null, "credit")); + invalid(() -> FinancialBusinessRules.payee("SUPPLIER", null, null)); + invalid(() -> FinancialBusinessRules.payee("SUPPLIER", 1L, "credit")); + invalid(() -> FinancialBusinessRules.payee("SUPPLIER", 1L, null)); + } + + @Test void currencyBoundaries() { + assertDoesNotThrow(() -> FinancialBusinessRules.currency(0, new BigDecimal("0.00000001"))); + assertDoesNotThrow(() -> FinancialBusinessRules.currency(8, ONE)); + for (Integer places : new Integer[]{null, -1, 9}) { + invalid(() -> FinancialBusinessRules.currency(places, ONE)); + } + for (BigDecimal rate : new BigDecimal[]{null, ZERO, NEGATIVE}) { + invalid(() -> FinancialBusinessRules.currency(2, rate)); + } + } + + @Test void subjectBoundaries() { + assertDoesNotThrow(() -> FinancialBusinessRules.subject(1)); + assertDoesNotThrow(() -> FinancialBusinessRules.subject(2)); + for (Integer level : new Integer[]{null, 0, 3}) invalid(() -> FinancialBusinessRules.subject(level)); + } + + @Test void budgetAndLedgerBoundariesAndNulls() { + for (boolean ledger : new boolean[]{false, true}) { + assertDoesNotThrow(() -> amounts(ledger, 2000, ZERO, ZERO, ZERO)); + assertDoesNotThrow(() -> amounts(ledger, 2100, new BigDecimal("2"), ONE, ONE)); + assertDoesNotThrow(() -> amounts(ledger, 2026, new BigDecimal("2.01"), ONE, ONE)); + for (Integer year : new Integer[]{null, 1999, 2101}) invalid(() -> amounts(ledger, year, ONE, ZERO, ZERO)); + for (BigDecimal bad : new BigDecimal[]{null, NEGATIVE}) { + invalid(() -> amounts(ledger, 2026, bad, ZERO, ZERO)); + invalid(() -> amounts(ledger, 2026, ONE, bad, ZERO)); + invalid(() -> amounts(ledger, 2026, ONE, ZERO, bad)); + } + invalid(() -> amounts(ledger, 2026, ONE, ONE, new BigDecimal("0.01"))); + invalid(() -> amounts(ledger, 2026, ZERO, ONE, ZERO)); + invalid(() -> amounts(ledger, 2026, ZERO, ZERO, ONE)); + } + } + + @Test void adjustmentBoundariesAndNulls() { + for (String direction : new String[]{"INCREASE", "DECREASE"}) { + assertDoesNotThrow(() -> FinancialBusinessRules.adjustment(direction, new BigDecimal("0.01"))); + for (BigDecimal amount : new BigDecimal[]{null, ZERO, NEGATIVE}) { + invalid(() -> FinancialBusinessRules.adjustment(direction, amount)); + } + } + for (String direction : new String[]{null, "", "OTHER"}) { + invalid(() -> FinancialBusinessRules.adjustment(direction, ONE)); + } + } + + private static void amounts(boolean ledger, Integer year, BigDecimal total, BigDecimal occupied, BigDecimal used) { + if (ledger) FinancialBusinessRules.ledger(year, total, occupied, used); + else FinancialBusinessRules.budget(year, total, occupied, used); + } + + private static void invalid(org.junit.jupiter.api.function.Executable action) { + assertThrows(BadRequestException.class, action); + } +} diff --git a/src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java b/src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java deleted file mode 100644 index d039d71..0000000 --- a/src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.finance.system.security; - -import com.finance.system.entity.SysApiAccessLog; -import com.finance.system.service.ApiAccessLogService; -import org.junit.jupiter.api.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -import javax.servlet.FilterChain; -import java.util.concurrent.atomic.AtomicInteger; - -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; -import org.mockito.ArgumentCaptor; - -class ApiAccessLogFilterTest { - - @Test - void logsAndPersistsReadAndWriteApiRequestsWithoutTrustingForwardedIp() throws Exception { - ApiAccessLogService service = mock(ApiAccessLogService.class); - ExposedFilter filter = new ExposedFilter(service); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/auth/me"); - request.setQueryString("code=oauth-code&state=oauth-state&token=bearer-secret&email=person%40example.com&view=summary"); - request.setRemoteAddr("10.0.0.8"); - request.addHeader("X-Forwarded-For", "203.0.113.99"); - request.addHeader("X-Request-Id", "test.request-1"); - MockHttpServletResponse response = new MockHttpServletResponse(); - AtomicInteger invoked = new AtomicInteger(); - FilterChain chain = (req, res) -> { - invoked.incrementAndGet(); - ((MockHttpServletResponse) res).setStatus(200); - }; - - filter.run(request, response, chain); - - assertThat(invoked).hasValue(1); - assertThat(response.getHeader("X-Request-Id")).isEqualTo("test.request-1"); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(SysApiAccessLog.class); - verify(service).recordAsync(entryCaptor.capture()); - SysApiAccessLog entry = entryCaptor.getValue(); - assertThat(entry.getHttpMethod()).isEqualTo("GET"); - assertThat(entry.getRequestPath()).isEqualTo("/api/auth/me"); - assertThat(entry.getStatusCode()).isEqualTo(200); - assertThat(entry.getClientIp()).isEqualTo("10.0.0.8"); - assertThat(entry.getQueryString()) - .contains("view=summary") - .doesNotContain("oauth-code", "oauth-state", "bearer-secret", "person%40example.com"); - } - - @Test - void capturesOptionsAndErrorResponsesAndSkipsNonApiResources() throws Exception { - ExposedFilter filter = new ExposedFilter(mock(ApiAccessLogService.class)); - assertThat(filter.skips(new MockHttpServletRequest("OPTIONS", "/api/payments"))).isFalse(); - assertThat(filter.skips(new MockHttpServletRequest("HEAD", "/api/users"))).isFalse(); - assertThat(filter.skips(new MockHttpServletRequest("GET", "/assets/app.js"))).isTrue(); - - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/payments/register"); - MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain chain = (req, res) -> ((MockHttpServletResponse) res).setStatus(422); - filter.run(request, response, chain); - - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(SysApiAccessLog.class); - verify(filter.service).recordAsync(entryCaptor.capture()); - assertThat(entryCaptor.getValue().getStatusCode()).isEqualTo(422); - assertThat(entryCaptor.getValue().getErrorMessage()).contains("422"); - } - - private static final class ExposedFilter extends ApiAccessLogFilter { - private final ApiAccessLogService service; - - private ExposedFilter(ApiAccessLogService service) { - super(service); - this.service = service; - } - - private boolean skips(MockHttpServletRequest request) { - return shouldNotFilter(request); - } - - private void run(MockHttpServletRequest request, MockHttpServletResponse response, - FilterChain chain) throws Exception { - doFilterInternal(request, response, chain); - } - } -} diff --git a/src/test/java/com/finance/system/security/finance/BankAccountProtectionTest.java b/src/test/java/com/finance/system/security/finance/BankAccountProtectionTest.java new file mode 100644 index 0000000..de76d61 --- /dev/null +++ b/src/test/java/com/finance/system/security/finance/BankAccountProtectionTest.java @@ -0,0 +1,77 @@ +package com.finance.system.security.finance; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class BankAccountProtectionTest { + private static final String ACCOUNT = "6222000000001001"; + + @Test + void encryptsNondeterministicallyAndDecryptsForPaymentExecution() { + BankAccountProtection protection = protection(); + + BankAccountProtection.ProtectedValue first = protection.protect(ACCOUNT); + BankAccountProtection.ProtectedValue second = protection.protect(ACCOUNT); + + assertThat(first.getCiphertext()).startsWith("BANK[v1]:k1:").isNotEqualTo(second.getCiphertext()); + assertThat(first.getFingerprint()).hasSize(64).isEqualTo(second.getFingerprint()); + assertThat(first.getMask()).isEqualTo("****1001"); + assertThat(first.getKeyVersion()).isEqualTo("k1"); + assertThat(protection.decryptForPaymentExecution(first.getCiphertext())).isEqualTo(ACCOUNT); + assertThat(first.toString()).doesNotContain(ACCOUNT, first.getCiphertext(), first.getFingerprint()); + } + + @Test + void keepsOldKeyVersionReadableDuringRotation() { + String oldKey = key("old-encryption-key-material-0001"); + String newKey = key("new-encryption-key-material-0002"); + String fingerprint = key("stable-fingerprint-key-material-003"); + BankAccountProtection old = new BankAccountProtection("k1=" + oldKey, fingerprint, "k1"); + String ciphertext = old.protect(ACCOUNT).getCiphertext(); + BankAccountProtection rotated = new BankAccountProtection( + "k1=" + oldKey + ",k2=" + newKey, fingerprint, "k2"); + + assertThat(rotated.decryptForPaymentExecution(ciphertext)).isEqualTo(ACCOUNT); + assertThat(rotated.protect(ACCOUNT).getKeyVersion()).isEqualTo("k2"); + } + + @Test + void failsClosedWhenKeysAreMissingOrInvalid() { + assertThatThrownBy(() -> new BankAccountProtection("", "", "").protect(ACCOUNT)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BANK_ACCOUNT_ENCRYPTION_KEYS_REQUIRED"); + assertThatThrownBy(() -> new BankAccountProtection("k1=not-base64", key("fingerprint-key-material-0000001"), "k1") + .protect(ACCOUNT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("MUST_BE_BASE64_32_BYTES"); + } + + @Test + void rejectsTamperedCiphertext() { + BankAccountProtection protection = protection(); + String ciphertext = protection.protect(ACCOUNT).getCiphertext(); + char replacement = ciphertext.endsWith("A") ? 'B' : 'A'; + String tampered = ciphertext.substring(0, ciphertext.length() - 1) + replacement; + + assertThatThrownBy(() -> protection.decryptForPaymentExecution(tampered)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BANK_ACCOUNT_CIPHERTEXT_INVALID"); + } + + private BankAccountProtection protection() { + return new BankAccountProtection("k1=" + key("encryption-key-material-for-test1"), + key("fingerprint-key-material-for-test2"), "k1"); + } + + private static String key(String source) { + byte[] input = source.getBytes(StandardCharsets.UTF_8); + byte[] key = new byte[32]; + System.arraycopy(input, 0, key, 0, Math.min(input.length, key.length)); + return Base64.getEncoder().encodeToString(key); + } +} diff --git a/src/test/java/com/finance/system/security/finance/SensitiveFieldMaskingTest.java b/src/test/java/com/finance/system/security/finance/SensitiveFieldMaskingTest.java new file mode 100644 index 0000000..107f305 --- /dev/null +++ b/src/test/java/com/finance/system/security/finance/SensitiveFieldMaskingTest.java @@ -0,0 +1,20 @@ +package com.finance.system.security.finance; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SensitiveFieldMaskingTest { + @Test + void masksBankAccountAndIdentityNumberWithoutReturningFullValues() { + assertThat(FinanceFieldProjection.maskBankAccount("6222000000001001")).isEqualTo("****1001"); + assertThat(FinanceFieldProjection.maskIdentityNumber("110101199001011234")) + .isEqualTo("110***********1234"); + } + + @Test + void masksShortSensitiveValuesCompletely() { + assertThat(FinanceFieldProjection.maskBankAccount("1234")).isEqualTo("****"); + assertThat(FinanceFieldProjection.maskIdentityNumber("1234567")).isEqualTo("****"); + } +} diff --git a/src/test/java/com/finance/system/service/ReimbursementAttachmentServiceTest.java b/src/test/java/com/finance/system/service/ReimbursementAttachmentServiceTest.java deleted file mode 100644 index 97b914c..0000000 --- a/src/test/java/com/finance/system/service/ReimbursementAttachmentServiceTest.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.finance.system.service; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.adapter.feishu.FeishuApprovalFileClient; -import com.finance.system.dto.AttachmentDto; -import com.finance.system.dto.ExpenseItemDto; -import com.finance.system.dto.ReimbursementFormField; -import com.finance.system.entity.ReimAttachment; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.ReimApplicationRepository; -import com.finance.system.repository.ReimAttachmentRepository; -import org.junit.jupiter.api.Test; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.web.multipart.MultipartFile; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - -class ReimbursementAttachmentServiceTest { - @Test - void acceptsPlainOriginalNameAndRejectsPathsAndControlCharacters() { - assertThat(ReimbursementAttachmentService.safeName(" receipt 01.pdf ")).isEqualTo("receipt 01.pdf"); - assertThatThrownBy(() -> ReimbursementAttachmentService.safeName("../receipt.pdf")) - .isInstanceOf(BusinessException.class); - assertThatThrownBy(() -> ReimbursementAttachmentService.safeName("folder\\receipt.pdf")) - .isInstanceOf(BusinessException.class); - assertThatThrownBy(() -> ReimbursementAttachmentService.safeName("receipt\r.pdf")) - .isInstanceOf(BusinessException.class); - } - - @Test - void enforcesSafeExtensionAndCompatibleMimePolicy() { - assertThat(ReimbursementAttachmentService.allowedContentType("receipt.PDF", "application/pdf")) - .isEqualTo("application/pdf"); - assertThat(ReimbursementAttachmentService.allowedContentType("photo.jpeg", "application/octet-stream")) - .isEqualTo("application/octet-stream"); - for (String name : Arrays.asList("run.exe", "page.html", "vector.svg", "bundle.zip")) - assertThatThrownBy(() -> ReimbursementAttachmentService.allowedContentType(name, "application/octet-stream")) - .isInstanceOf(BusinessException.class); - assertThatThrownBy(() -> ReimbursementAttachmentService.allowedContentType("receipt.pdf", "text/html")) - .isInstanceOf(BusinessException.class); - } - - @Test - void rejectsIndividualSizeAndStagedQuotaBeforeProviderUpload() { - ReimbursementFormService forms = mock(ReimbursementFormService.class); - FeishuApprovalFileClient client = mock(FeishuApprovalFileClient.class); - ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class); - ReimbursementAttachmentService service = new ReimbursementAttachmentService( - forms, client, repository, mock(ReimApplicationRepository.class)); - - MultipartFile tooLarge = mock(MultipartFile.class); - when(tooLarge.getOriginalFilename()).thenReturn("large.pdf"); - when(tooLarge.isEmpty()).thenReturn(false); - when(tooLarge.getSize()).thenReturn(ReimbursementAttachmentService.MAX_FILE_BYTES + 1); - assertThatThrownBy(() -> service.upload(tooLarge, "fp", "control", 7L)) - .isInstanceOf(BusinessException.class); - - ReimbursementFormField control = ReimbursementFormField.builder().id("control").build(); - when(forms.requireCurrentAttachmentControl("fp", "control")).thenReturn(control); - when(repository.countByUploaderIdAndApplicationIdIsNullAndUploadStatus(7L, "UPLOADED")) - .thenReturn(ReimbursementAttachmentService.MAX_STAGED_COUNT); - when(repository.sumStagedBytes(7L, "UPLOADED")).thenReturn(0L); - MockMultipartFile valid = new MockMultipartFile("file", "receipt.pdf", "application/pdf", new byte[]{1}); - assertThatThrownBy(() -> service.upload(valid, "fp", "control", 7L)) - .isInstanceOf(BusinessException.class); - verifyNoInteractions(client); - } - - @Test - void countsEveryUploadTodayRegardlessOfClaimOrDeletionBeforeProviderUpload() { - ReimbursementFormService forms = mock(ReimbursementFormService.class); - FeishuApprovalFileClient client = mock(FeishuApprovalFileClient.class); - ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class); - ReimbursementAttachmentService service = new ReimbursementAttachmentService( - forms, client, repository, mock(ReimApplicationRepository.class)); - when(forms.requireCurrentAttachmentControl("fp", "control")) - .thenReturn(ReimbursementFormField.builder().id("control").build()); - when(repository.countByUploaderIdAndCreatedAtGreaterThanEqual(eq(7L), any(LocalDateTime.class))) - .thenReturn(ReimbursementAttachmentService.MAX_DAILY_COUNT); - - MockMultipartFile file = new MockMultipartFile( - "file", "receipt.pdf", "application/pdf", new byte[]{1}); - assertThatThrownBy(() -> service.upload(file, "fp", "control", 7L)) - .isInstanceOf(BusinessException.class); - - org.mockito.ArgumentCaptor start = org.mockito.ArgumentCaptor.forClass(LocalDateTime.class); - verify(repository).countByUploaderIdAndCreatedAtGreaterThanEqual(eq(7L), start.capture()); - assertThat(start.getValue()).isEqualTo(LocalDate.now(ZoneId.of("Asia/Shanghai")).atStartOfDay()); - verifyNoInteractions(client); - } - - @Test - void enforcesDailyByteBudgetBeforeProviderUpload() { - ReimbursementFormService forms = mock(ReimbursementFormService.class); - FeishuApprovalFileClient client = mock(FeishuApprovalFileClient.class); - ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class); - ReimbursementAttachmentService service = new ReimbursementAttachmentService( - forms, client, repository, mock(ReimApplicationRepository.class)); - when(forms.requireCurrentAttachmentControl("fp", "control")) - .thenReturn(ReimbursementFormField.builder().id("control").build()); - when(repository.sumUploadedBytesSince(eq(7L), any(LocalDateTime.class))) - .thenReturn(ReimbursementAttachmentService.MAX_DAILY_BYTES); - - MockMultipartFile file = new MockMultipartFile( - "file", "receipt.pdf", "application/pdf", new byte[]{1}); - assertThatThrownBy(() -> service.upload(file, "fp", "control", 7L)) - .isInstanceOf(BusinessException.class); - verifyNoInteractions(client); - } - - @Test - void validatesRequiredDuplicateAndOwnershipWhenClaiming() { - ReimbursementFormService forms = mock(ReimbursementFormService.class); - ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class); - ReimbursementAttachmentService service = new ReimbursementAttachmentService( - forms, mock(FeishuApprovalFileClient.class), repository, mock(ReimApplicationRepository.class)); - ReimbursementFormField required = ReimbursementFormField.builder().id("control").required(true).build(); - when(forms.requireCurrentAttachmentControl("fp")).thenReturn(required); - - ExpenseItemDto missing = ExpenseItemDto.builder().build(); - assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(missing), "fp", 7L, null)) - .isInstanceOf(BusinessException.class); - - ExpenseItemDto duplicate = ExpenseItemDto.builder().attachmentIds(Arrays.asList(1L, 1L)).build(); - assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(duplicate), "fp", 7L, null)) - .isInstanceOf(BusinessException.class); - - ExpenseItemDto foreign = ExpenseItemDto.builder().attachmentIds(Collections.singletonList(2L)).build(); - ReimAttachment row = ReimAttachment.builder().id(2L).uploaderId(8L).uploadStatus("UPLOADED") - .formFingerprint("fp").formControlId("control").build(); - when(repository.findAllByIdInForUpdate(anyCollection())).thenReturn(Collections.singletonList(row)); - assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(foreign), "fp", 7L, null)) - .isInstanceOf(BusinessException.class); - - ExpenseItemDto deletedClaim = ExpenseItemDto.builder().attachmentIds(Collections.singletonList(3L)).build(); - ReimAttachment deleted = ReimAttachment.builder().id(3L).uploaderId(7L).uploadStatus("DELETED") - .formFingerprint("fp").formControlId("control").build(); - when(repository.findAllByIdInForUpdate(Collections.singletonList(3L))) - .thenReturn(Collections.singletonList(deleted)); - assertThatThrownBy(() -> service.validateClaims(Collections.singletonList(deletedClaim), "fp", 7L, null)) - .isInstanceOf(BusinessException.class); - } - - @Test - void removeUsesLockedLookupAndExpenseMetadataCannotExposeProviderCodeOrUrl() throws Exception { - ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class); - ReimbursementAttachmentService service = new ReimbursementAttachmentService(mock(ReimbursementFormService.class), - mock(FeishuApprovalFileClient.class), repository, mock(ReimApplicationRepository.class)); - ReimAttachment row = ReimAttachment.builder().id(4L).uploaderId(7L).fileName("receipt.pdf") - .feishuFileCode("secret-code").fileUrl("secret-url").build(); - when(repository.findByIdForUpdate(4L)).thenReturn(java.util.Optional.of(row)); - service.remove(4L, 7L); - verify(repository).findByIdForUpdate(4L); - assertThat(row.getApplicationId()).isNull(); - assertThat(row.getExpenseItemId()).isNull(); - assertThat(row.getUploadStatus()).isEqualTo("DELETED"); - verify(repository).save(row); - verify(repository, never()).delete(any(ReimAttachment.class)); - - ExpenseItemDto item = ExpenseItemDto.builder().attachments(Collections.singletonList( - AttachmentDto.builder().id(4L).fileName("receipt.pdf").build())).build(); - String json = new ObjectMapper().writeValueAsString(item); - assertThat(json).contains("\"attachments\"").doesNotContain("secret-code", "secret-url", "provider"); - } - - @Test - void omittedDraftAttachmentsBecomeUnlinkedTombstones() { - ReimAttachmentRepository repository = mock(ReimAttachmentRepository.class); - ReimbursementAttachmentService service = new ReimbursementAttachmentService(mock(ReimbursementFormService.class), - mock(FeishuApprovalFileClient.class), repository, mock(ReimApplicationRepository.class)); - ReimAttachment omitted = ReimAttachment.builder().id(9L).uploaderId(7L).applicationId(3L) - .expenseItemId(4L).uploadStatus("UPLOADED").feishuFileCode("internal-code").build(); - - service.deleteOmitted(Collections.singletonList(omitted), new HashSet(), 7L); - - assertThat(omitted.getApplicationId()).isNull(); - assertThat(omitted.getExpenseItemId()).isNull(); - assertThat(omitted.getUploadStatus()).isEqualTo("DELETED"); - assertThat(omitted.getFeishuFileCode()).isEqualTo("internal-code"); - verify(repository).save(omitted); - verify(repository, never()).delete(any(ReimAttachment.class)); - } -} diff --git a/src/test/java/com/finance/system/service/ReimbursementFormSchemaValidationTest.java b/src/test/java/com/finance/system/service/ReimbursementFormSchemaValidationTest.java deleted file mode 100644 index 7962c31..0000000 --- a/src/test/java/com/finance/system/service/ReimbursementFormSchemaValidationTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.finance.system.service; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.adapter.feishu.FeishuApprovalService; -import com.finance.system.adapter.feishu.FeishuDefinitionNormalizer; -import com.finance.system.dto.ReimbursementFormField; -import com.finance.system.repository.*; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -/** - * Ensures the live-style Feishu template (editable department + multi-currency amount) - * survives {@link ReimbursementFormService#parseSchema} after sync. - */ -class ReimbursementFormSchemaValidationTest { - - @Test - void acceptsSyncedLiveTemplateWithCurrencyOptionsAndEditableDepartment() throws Exception { - ObjectMapper json = new ObjectMapper(); - String source = "{\"data\":{\"approval_code\":\"approval-live\"," - + "\"nodes\":[{\"id\":\"node-1\",\"name\":\"财务审批\"}]," - + "\"form\":[" - + "{\"id\":\"contact-id\",\"type\":\"contact\",\"name\":\"报销人\",\"required\":true}," - + "{\"id\":\"department-id\",\"type\":\"department\",\"name\":\"报销人所属部门\",\"required\":true}," - + "{\"id\":\"reimbursement-date-id\",\"type\":\"date\",\"name\":\"报销日期\",\"required\":true}," - + "{\"id\":\"detail-id\",\"type\":\"fieldList\",\"name\":\"明细\",\"required\":true,\"children\":[" - + "{\"id\":\"reason-id\",\"type\":\"input\",\"name\":\"报销事由\",\"required\":true}," - + "{\"id\":\"date-id\",\"type\":\"date\",\"name\":\"发生日期\",\"required\":true}," - + "{\"id\":\"amount-id\",\"type\":\"amount\",\"name\":\"金额\",\"required\":true," - + "\"option\":{\"currencyRange\":[\"CNY\",\"JPY\",\"USD\"]}}," - + "{\"id\":\"attachment-id\",\"type\":\"attachmentV2\",\"name\":\"附件\",\"required\":true}" - + "]}," - + "{\"id\":\"formula-id\",\"type\":\"formula\",\"name\":\"总金额\",\"required\":true}" - + "]}}"; - - FeishuDefinitionNormalizer.NormalizedDefinition normalized = - new FeishuDefinitionNormalizer(json).normalize(json.readTree(source), "approval-live"); - - ReimbursementFormService service = new ReimbursementFormService( - mock(FeishuApprovalDefinitionSnapshotRepository.class), - mock(FeishuApprovalService.class), - json, - mock(SysUserRepository.class), - mock(SysDepartmentRepository.class), - mock(SysExpenseTypeRepository.class), - mock(ReimExpenseItemRepository.class), - mock(ReimAttachmentRepository.class), - mock(ApplicantDepartmentDirectoryRepository.class)); - - List fields = service.parseSchema(normalized.getFormSchema()); - assertThat(fields).isNotEmpty(); - ReimbursementFormField department = fields.stream() - .filter(field -> "APPLICANT_DEPARTMENT".equals(field.getBinding())) - .findFirst().orElseThrow(IllegalStateException::new); - assertThat(department.isReadOnly()).isFalse(); - ReimbursementFormField amount = fields.stream() - .filter(field -> "EXPENSE_ITEMS".equals(field.getBinding())) - .flatMap(field -> field.getChildren().stream()) - .filter(field -> "EXPENSE_AMOUNT".equals(field.getBinding())) - .findFirst().orElseThrow(IllegalStateException::new); - assertThat(amount.getOptions()).extracting(ReimbursementFormField.Option::getValue) - .contains("CNY", "JPY", "USD"); - } -} diff --git a/src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java b/src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java deleted file mode 100644 index 499b88b..0000000 --- a/src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.finance.system.service; - -import com.finance.system.entity.SysPermission; -import com.finance.system.entity.SysRole; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.*; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -class RoleServicePermissionSecurityTest { - private SysRoleRepository roles; - private SysPermissionRepository permissions; - private SysRolePermissionRepository rolePermissions; - private RoleService service; - - @BeforeEach - void setUp() { - roles = mock(SysRoleRepository.class); - permissions = mock(SysPermissionRepository.class); - rolePermissions = mock(SysRolePermissionRepository.class); - service = spy(new RoleService(roles, permissions, rolePermissions, mock(SysUserRepository.class), - mock(SysUserGroupRepository.class), mock(SysUserGroupMemberRepository.class), - mock(SysUserGroupRoleRepository.class))); - doReturn(true).when(service).isSuperAdmin(1L); - SysRole target = new SysRole(); - target.setId(7L); - target.setBuiltIn(false); - when(roles.findById(7L)).thenReturn(Optional.of(target)); - when(roles.findByIdForUpdate(7L)).thenReturn(Optional.of(target)); - } - - @Test - void rejectsAbsentOrEmptyPermissionAccessWithoutDeleting() { - assertThatThrownBy(() -> service.replaceRolePermissions(7L, Collections.emptyMap(), 1L)) - .isInstanceOf(BusinessException.class); - assertThatThrownBy(() -> service.replaceRolePermissions(7L, - Collections.singletonMap("permissionAccess", Collections.emptyMap()), 1L)) - .isInstanceOf(BusinessException.class); - verify(rolePermissions, never()).deleteByIdRoleId(7L); - } - - @Test - void rejectsEmptyLegacyPayloadWithoutDeleting() { - Map payload = new HashMap<>(); - payload.put("permissionCodes", Collections.emptyList()); - payload.put("fieldPermissions", Collections.emptyMap()); - assertThatThrownBy(() -> service.replaceRolePermissions(7L, payload, 1L)) - .isInstanceOf(BusinessException.class); - verify(rolePermissions, never()).deleteByIdRoleId(7L); - } - - @Test - void rejectsMalformedLegacyCollectionsWithClientErrorWithoutDeleting() { - Map payload = new HashMap<>(); - payload.put("permissionCodes", "not-an-array"); - payload.put("fieldPermissions", Collections.emptyMap()); - assertThatThrownBy(() -> service.replaceRolePermissions(7L, payload, 1L)) - .isInstanceOf(BusinessException.class) - .hasMessageContaining("permissionCodes 必须是数组"); - verify(rolePermissions, never()).deleteByIdRoleId(7L); - } - - @Test - void acceptsCompleteHiddenPayloadAndActionPermission() { - SysPermission action = permission(21L, "report.export", "ACTION"); - SysPermission menu = permission(22L, "dashboard", "MENU"); - when(permissions.findAll()).thenReturn(Arrays.asList(action, menu)); - - Map allHidden = new LinkedHashMap<>(); - allHidden.put("report.export", "HIDDEN"); - allHidden.put("dashboard", "HIDDEN"); - Map update = new LinkedHashMap<>(); - update.put("permissionAccess", allHidden); - update.put("expectedPermissionAccess", allHidden); - service.replaceRolePermissions(7L, update, 1L); - verify(rolePermissions).deleteByIdRoleId(7L); - verify(rolePermissions).saveAll(any()); - - reset(rolePermissions); - Map grantAction = new LinkedHashMap<>(); - grantAction.put("permissionAccess", Collections.singletonMap("report.export", "EDIT")); - grantAction.put("expectedPermissionAccess", allHidden); - service.replaceRolePermissions(7L, grantAction, 1L); - verify(rolePermissions).deleteByIdRoleId(7L); - verify(rolePermissions).saveAll(any()); - } - - @Test - void rejectsStalePermissionSnapshotWithoutOverwritingNewChanges() { - SysPermission menu = permission(22L, "dashboard", "MENU"); - when(permissions.findAll()).thenReturn(Collections.singletonList(menu)); - Map request = new LinkedHashMap<>(); - request.put("permissionAccess", Collections.singletonMap("dashboard", "EDIT")); - request.put("expectedPermissionAccess", Collections.singletonMap("dashboard", "READ")); - - assertThatThrownBy(() -> service.replaceRolePermissions(7L, request, 1L)) - .isInstanceOf(BusinessException.class) - .hasMessageContaining("已被其他管理员修改"); - verify(rolePermissions, never()).deleteByIdRoleId(7L); - } - - private SysPermission permission(Long id, String code, String type) { - SysPermission permission = new SysPermission(); - permission.setId(id); - permission.setPermissionCode(code); - permission.setPermissionType(type); - permission.setDefaultAccess("READ"); - return permission; - } -} diff --git a/src/test/java/com/finance/system/service/impl/ReimApplicationAttachmentDetailTest.java b/src/test/java/com/finance/system/service/impl/ReimApplicationAttachmentDetailTest.java deleted file mode 100644 index 153e343..0000000 --- a/src/test/java/com/finance/system/service/impl/ReimApplicationAttachmentDetailTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.finance.system.service.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.finance.system.adapter.kingdee.KingdeeConfig; -import com.finance.system.dto.ReimApplicationDetail; -import com.finance.system.entity.ReimApplication; -import com.finance.system.entity.ReimAttachment; -import com.finance.system.entity.ReimExpenseItem; -import com.finance.system.repository.*; -import com.finance.system.service.ReimbursementAttachmentService; -import com.finance.system.service.ReimbursementFormService; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; - -class ReimApplicationAttachmentDetailTest { - @Test - void detailMapsSafeAttachmentMetadataToItsExpenseRowAndKeepsTopLevelCompatibility() throws Exception { - ReimApplicationRepository applications = mock(ReimApplicationRepository.class); - SysUserRepository users = mock(SysUserRepository.class); - SysDepartmentRepository departments = mock(SysDepartmentRepository.class); - SysExpenseTypeRepository expenseTypes = mock(SysExpenseTypeRepository.class); - SysBankAccountRepository banks = mock(SysBankAccountRepository.class); - ReimExpenseItemRepository items = mock(ReimExpenseItemRepository.class); - ReimInvoiceRepository invoices = mock(ReimInvoiceRepository.class); - ReimAttachmentRepository attachments = mock(ReimAttachmentRepository.class); - ReimApprovalRecordRepository approvals = mock(ReimApprovalRecordRepository.class); - ReimPaymentRepository payments = mock(ReimPaymentRepository.class); - - ReimApplicationServiceImpl service = new ReimApplicationServiceImpl(applications, users, departments, - expenseTypes, banks, items, invoices, attachments, approvals, payments, - mock(SysApprovalNodeRepository.class), mock(KingdeeConfig.class), - mock(ReimbursementFormService.class), mock(ReimbursementAttachmentService.class)); - - ReimApplication app = new ReimApplication(); - app.setId(10L); - app.setApplicantId(7L); - ReimExpenseItem item = new ReimExpenseItem(); - item.setId(20L); - item.setApplicationId(10L); - ReimAttachment attachment = ReimAttachment.builder().id(30L).applicationId(10L).expenseItemId(20L) - .fileName("receipt.pdf").contentType("application/pdf").fileSize(123L) - .feishuFileCode("provider-secret").fileUrl("provider-url").build(); - - when(applications.findById(10L)).thenReturn(Optional.of(app)); - when(users.findById(7L)).thenReturn(Optional.empty()); - when(items.findByApplicationId(10L)).thenReturn(Collections.singletonList(item)); - when(invoices.findByApplicationId(10L)).thenReturn(Collections.emptyList()); - when(attachments.findByApplicationIdAndExpenseItemIdIsNotNullAndUploadStatus(10L, "UPLOADED")) - .thenReturn(Collections.singletonList(attachment)); - when(attachments.findByExpenseItemIdAndApplicationIdIsNotNullAndUploadStatusOrderByIdAsc(20L, "UPLOADED")) - .thenReturn(Collections.singletonList(attachment)); - when(approvals.findByApplicationIdOrderByActionTimeAsc(10L)).thenReturn(Collections.emptyList()); - when(payments.findByApplicationId(10L)).thenReturn(Collections.emptyList()); - - ReimApplicationDetail detail = service.getApplicationDetail(10L, 7L); - assertThat(detail.getExpenseItems().get(0).getAttachmentIds()).containsExactly(30L); - assertThat(detail.getExpenseItems().get(0).getAttachments().get(0).getFileName()).isEqualTo("receipt.pdf"); - assertThat(detail.getAttachments()).hasSize(1); - String payload = new ObjectMapper().writeValueAsString(detail); - assertThat(payload).doesNotContain("provider-secret", "provider-url", "feishuFileCode", "fileUrl"); - } -}