feat: 完成财务中台核心功能与前后端基础设施搭建

This commit is contained in:
zxp
2026-10-28 11:45:28 +08:00
commit c3fe52c1ee
239 changed files with 28937 additions and 0 deletions
@@ -0,0 +1,12 @@
package com.gas.fin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FinanceApplication {
public static void main(String[] args) {
SpringApplication.run(FinanceApplication.class, args);
}
}
@@ -0,0 +1,64 @@
package com.gas.fin.account.controller;
import com.gas.fin.account.dto.AccountAdjustRequest;
import com.gas.fin.account.dto.AccountDetailResponse;
import com.gas.fin.account.dto.AccountInfoResponse;
import com.gas.fin.account.service.AccountService;
import com.gas.fin.common.api.PageResult;
import com.gas.fin.common.api.R;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import com.gas.fin.transaction.dto.TransactionInfoResponse;
import jakarta.servlet.http.HttpServletRequest;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/admin/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping
@RequirePermission(PermissionRegistry.VIEW)
public R<PageResult<AccountInfoResponse>> list(
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long pageSize,
@RequestParam(required = false) String appCode,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long minBalance) {
return R.ok(accountService.page(page, pageSize, appCode, keyword, minBalance));
}
@GetMapping("/{id}")
@RequirePermission(PermissionRegistry.VIEW)
public R<AccountDetailResponse> detail(@PathVariable Long id) {
return R.ok(accountService.detail(id));
}
@GetMapping("/{id}/transactions")
@RequirePermission(PermissionRegistry.VIEW)
public R<PageResult<TransactionInfoResponse>> transactions(
@PathVariable Long id,
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long pageSize) {
return R.ok(accountService.transactions(id, page, pageSize));
}
@PostMapping("/adjust")
@RequirePermission(PermissionRegistry.ACCOUNT_ADJUST)
public R<AccountInfoResponse> adjust(@RequestBody AccountAdjustRequest request,
HttpServletRequest httpRequest) {
return R.ok(accountService.adjust(request, AuthContext.require(), httpRequest));
}
}
@@ -0,0 +1,5 @@
package com.gas.fin.account.dto;
public record AccountAdjustRequest(String appCode, String businessUserId, Long amount, String direction,
String reason, Long secondApproverId, String totp) {
}
@@ -0,0 +1,14 @@
package com.gas.fin.account.dto;
import com.gas.fin.transaction.dto.TransactionInfoResponse;
import java.time.LocalDateTime;
import java.util.List;
public record AccountDetailResponse(AccountInfoResponse account, VipDetail vip,
List<TransactionInfoResponse> transactions) {
public record VipDetail(String planCode, String planName, LocalDateTime vipUntil,
boolean effective, Integer freeDeduction) {
}
}
@@ -0,0 +1,42 @@
package com.gas.fin.account.dto;
import com.gas.fin.account.entity.AccountEntity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class AccountInfoResponse {
private Long id;
private String appCode;
private String appName;
private String businessUserId;
private String usernameSnapshot;
private String phoneMasked;
private Long balance;
private Long totalSpent;
private Integer versionNo;
private String vipPlanCode;
private LocalDateTime vipUntil;
private LocalDateTime createTime;
private LocalDateTime updateTime;
public static AccountInfoResponse from(AccountEntity entity, String appName) {
AccountInfoResponse response = new AccountInfoResponse();
response.setId(entity.getId());
response.setAppCode(entity.getAppCode());
response.setAppName(appName == null ? entity.getAppCode() : appName);
response.setBusinessUserId(entity.getBusinessUserId());
response.setUsernameSnapshot(entity.getUsernameSnapshot());
response.setPhoneMasked(entity.getPhoneMasked());
response.setBalance(entity.getBalance());
response.setTotalSpent(entity.getTotalSpent());
response.setVersionNo(entity.getVersionNo());
response.setVipPlanCode(entity.getVipPlanCode());
response.setVipUntil(entity.getVipUntil());
response.setCreateTime(entity.getCreateTime());
response.setUpdateTime(entity.getUpdateTime());
return response;
}
}
@@ -0,0 +1,31 @@
package com.gas.fin.account.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_account")
public class AccountEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String appCode;
private String businessUserId;
private String usernameSnapshot;
private String phoneMasked;
private String phoneHash;
private Long balance;
private Long totalSpent;
private Integer versionNo;
private String vipPlanCode;
private LocalDateTime vipUntil;
private String status;
private LocalDateTime firstSeenAt;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,9 @@
package com.gas.fin.account.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.account.entity.AccountEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AccountMapper extends BaseMapper<AccountEntity> {
}
@@ -0,0 +1,237 @@
package com.gas.fin.account.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gas.fin.account.dto.AccountAdjustRequest;
import com.gas.fin.account.dto.AccountDetailResponse;
import com.gas.fin.account.dto.AccountInfoResponse;
import com.gas.fin.account.entity.AccountEntity;
import com.gas.fin.account.mapper.AccountMapper;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.admin.mapper.AdminMapper;
import com.gas.fin.app.entity.AppEntity;
import com.gas.fin.app.mapper.AppMapper;
import com.gas.fin.common.api.PageResult;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.id.FinIdGenerator;
import com.gas.fin.common.security.AdminAuditor;
import com.gas.fin.common.security.TotpVerifier;
import com.gas.fin.common.web.QueryUtils;
import com.gas.fin.transaction.dto.TransactionInfoResponse;
import com.gas.fin.transaction.entity.TransactionEntity;
import com.gas.fin.transaction.mapper.TransactionMapper;
import com.gas.fin.vip.entity.VipHolderEntity;
import com.gas.fin.vip.entity.VipPlanEntity;
import com.gas.fin.vip.mapper.VipHolderMapper;
import com.gas.fin.vip.mapper.VipPlanMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 业务用户钱包:查询与人工调账。
*/
@Service
public class AccountService {
private final AccountMapper accountMapper;
private final TransactionMapper transactionMapper;
private final VipHolderMapper vipHolderMapper;
private final VipPlanMapper vipPlanMapper;
private final AdminMapper adminMapper;
private final AppMapper appMapper;
private final FinIdGenerator idGenerator;
private final TotpVerifier totpVerifier;
private final AdminAuditor adminAuditor;
public AccountService(AccountMapper accountMapper, TransactionMapper transactionMapper,
VipHolderMapper vipHolderMapper, VipPlanMapper vipPlanMapper,
AdminMapper adminMapper, AppMapper appMapper, FinIdGenerator idGenerator,
TotpVerifier totpVerifier, AdminAuditor adminAuditor) {
this.accountMapper = accountMapper;
this.transactionMapper = transactionMapper;
this.vipHolderMapper = vipHolderMapper;
this.vipPlanMapper = vipPlanMapper;
this.adminMapper = adminMapper;
this.appMapper = appMapper;
this.idGenerator = idGenerator;
this.totpVerifier = totpVerifier;
this.adminAuditor = adminAuditor;
}
public PageResult<AccountInfoResponse> page(long page, long pageSize, String appCode, String keyword,
Long minBalance) {
QueryUtils.checkPage(page, pageSize);
LambdaQueryWrapper<AccountEntity> wrapper = new LambdaQueryWrapper<>();
if (appCode != null && !appCode.isBlank()) {
wrapper.eq(AccountEntity::getAppCode, appCode.trim());
}
if (keyword != null && !keyword.isBlank()) {
String value = keyword.trim();
wrapper.and(w -> w.like(AccountEntity::getBusinessUserId, value)
.or().like(AccountEntity::getUsernameSnapshot, value)
.or().like(AccountEntity::getPhoneMasked, value));
}
if (minBalance != null) {
wrapper.ge(AccountEntity::getBalance, minBalance);
}
wrapper.orderByDesc(AccountEntity::getBalance).orderByAsc(AccountEntity::getId);
Page<AccountEntity> result = accountMapper.selectPage(new Page<>(page, pageSize), wrapper);
Map<String, String> names = appNames();
List<AccountInfoResponse> records = result.getRecords().stream()
.map(item -> AccountInfoResponse.from(item, names.get(item.getAppCode())))
.toList();
return PageResult.of(records, result.getTotal(), page, pageSize);
}
public AccountDetailResponse detail(Long id) {
AccountEntity account = requireAccount(id);
VipHolderEntity holder = vipHolderMapper.selectOne(new LambdaQueryWrapper<VipHolderEntity>()
.eq(VipHolderEntity::getAppCode, account.getAppCode())
.eq(VipHolderEntity::getBusinessUserId, account.getBusinessUserId())
.last("LIMIT 1"));
AccountDetailResponse.VipDetail vip = null;
if (holder != null) {
VipPlanEntity plan = vipPlanMapper.selectOne(new LambdaQueryWrapper<VipPlanEntity>()
.eq(VipPlanEntity::getAppCode, holder.getAppCode())
.eq(VipPlanEntity::getPlanCode, holder.getVipPlanCode())
.last("LIMIT 1"));
vip = new AccountDetailResponse.VipDetail(holder.getVipPlanCode(),
plan == null ? holder.getVipPlanCode() : plan.getPlanName(),
holder.getVipUntil(),
holder.getVipUntil().isAfter(LocalDateTime.now().withNano(0)),
plan == null || plan.getFreeDeduction() == null ? 0 : plan.getFreeDeduction());
}
List<TransactionEntity> transactions = transactionMapper.selectList(
new LambdaQueryWrapper<TransactionEntity>()
.eq(TransactionEntity::getAppCode, account.getAppCode())
.eq(TransactionEntity::getBusinessUserId, account.getBusinessUserId())
.orderByDesc(TransactionEntity::getCreateTime)
.orderByDesc(TransactionEntity::getId)
.last("LIMIT 10"));
String appName = appNames().get(account.getAppCode());
return new AccountDetailResponse(AccountInfoResponse.from(account, appName), vip,
transactions.stream().map(item -> TransactionInfoResponse.from(item, appName)).toList());
}
public PageResult<TransactionInfoResponse> transactions(Long id, long page, long pageSize) {
QueryUtils.checkPage(page, pageSize);
AccountEntity account = requireAccount(id);
Page<TransactionEntity> result = transactionMapper.selectPage(new Page<>(page, pageSize),
new LambdaQueryWrapper<TransactionEntity>()
.eq(TransactionEntity::getAppCode, account.getAppCode())
.eq(TransactionEntity::getBusinessUserId, account.getBusinessUserId())
.orderByDesc(TransactionEntity::getCreateTime)
.orderByDesc(TransactionEntity::getId));
String appName = appNames().get(account.getAppCode());
return PageResult.of(result.getRecords().stream()
.map(item -> TransactionInfoResponse.from(item, appName)).toList(),
result.getTotal(), page, pageSize);
}
@Transactional
public AccountInfoResponse adjust(AccountAdjustRequest request, AdminEntity current,
HttpServletRequest httpRequest) {
Long amount = request.amount();
if (amount == null || amount <= 0 || amount > 1000000000L) {
throw new BizException(ErrorCode.INVALID_POINTS, "调账点数必须为正整数");
}
String direction = QueryUtils.text(request.direction());
if (!"IN".equals(direction) && !"OUT".equals(direction)) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "调账方向不合法");
}
String reason = QueryUtils.text(request.reason());
if (reason.length() < 5 || reason.length() > 255) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "调账原因不少于 5 个字且不超过 255 字");
}
totpVerifier.verify(current, request.totp(), "ACCOUNT_ADJUST", "人工调账", httpRequest);
AdminEntity approver = requireApprover(request.secondApproverId(), current);
AccountEntity account = accountMapper.selectOne(new LambdaQueryWrapper<AccountEntity>()
.eq(AccountEntity::getAppCode, QueryUtils.text(request.appCode()))
.eq(AccountEntity::getBusinessUserId, QueryUtils.text(request.businessUserId()))
.last("LIMIT 1"));
if (account == null) {
throw new BizException(ErrorCode.NOT_FOUND, "钱包账户不存在");
}
long before = account.getBalance();
if ("OUT".equals(direction) && before < amount) {
throw new BizException(ErrorCode.REFUND_BALANCE_INSUFFICIENT, "账户余额不足,调减后余额不能为负");
}
long after = "IN".equals(direction) ? before + amount : before - amount;
int version = account.getVersionNo() == null ? 0 : account.getVersionNo();
LocalDateTime now = LocalDateTime.now().withNano(0);
int rows = accountMapper.update(null, new LambdaUpdateWrapper<AccountEntity>()
.eq(AccountEntity::getId, account.getId())
.eq(AccountEntity::getVersionNo, version)
.set(AccountEntity::getBalance, after)
.set(AccountEntity::getVersionNo, version + 1)
.set(AccountEntity::getUpdateTime, now));
if (rows == 0) {
throw new BizException(ErrorCode.CONCURRENT_CONFLICT);
}
TransactionEntity tx = new TransactionEntity();
tx.setAppCode(account.getAppCode());
tx.setBusinessUserId(account.getBusinessUserId());
tx.setUsernameSnapshot(account.getUsernameSnapshot());
tx.setType("ADJUST");
tx.setAmount(amount);
tx.setBalanceBefore(before);
tx.setBalanceAfter(after);
tx.setIdempotencyKey("adjust:" + current.getId() + ":" + idGenerator.nextLongId());
tx.setOperatorAdminId(current.getId());
tx.setOperatorAdminName(current.getUsername());
tx.setRefundedPoints(0L);
tx.setRemark(reason);
tx.setCreateTime(now);
transactionMapper.insert(tx);
Map<String, Object> beforeJson = new LinkedHashMap<>();
beforeJson.put("balance", before);
Map<String, Object> afterJson = new LinkedHashMap<>();
afterJson.put("balance", after);
afterJson.put("direction", direction);
afterJson.put("amount", amount);
afterJson.put("reason", reason);
afterJson.put("secondApprover", approver.getUsername());
adminAuditor.success(current, "ACCOUNT_ADJUST", "人工调账(复核人:" + approver.getUsername() + ")",
"ACCOUNT", account.getId(), beforeJson, afterJson, httpRequest);
AccountEntity saved = accountMapper.selectById(account.getId());
return AccountInfoResponse.from(saved, appNames().get(saved.getAppCode()));
}
private AdminEntity requireApprover(Long secondApproverId, AdminEntity current) {
if (secondApproverId == null || secondApproverId.equals(current.getId())) {
throw new BizException(ErrorCode.INVALID_APPROVER, "人工调账必须由另一名管理员复核,且不得为本人");
}
AdminEntity approver = adminMapper.selectById(secondApproverId);
if (approver == null || !Integer.valueOf(1).equals(approver.getIsActive())) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "复核管理员不存在或已停用");
}
if (!"SUPER_ADMIN".equals(approver.getRole()) && !"FINANCE".equals(approver.getRole())) {
throw new BizException(ErrorCode.INVALID_APPROVER, "复核人必须具备资金操作权限");
}
return approver;
}
private AccountEntity requireAccount(Long id) {
AccountEntity account = accountMapper.selectById(id);
if (account == null) {
throw new BizException(ErrorCode.NOT_FOUND, "钱包账户不存在");
}
return account;
}
private Map<String, String> appNames() {
return appMapper.selectList(null).stream()
.collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a));
}
}
@@ -0,0 +1,112 @@
package com.gas.fin.admin.bootstrap;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.admin.mapper.AdminMapper;
import com.gas.fin.audit.service.AuditService;
import com.gas.fin.auth.service.PasswordHistoryService;
import com.gas.fin.common.crypto.CryptoService;
import com.gas.fin.common.totp.TotpService;
import com.gas.fin.common.util.PasswordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
/**
* 首次启动种子超管:无任何管理员时创建 admin,随机初始密码与 TOTP 密钥只写入本地运维文件。
*/
@Component
@Order(10)
public class AdminBootstrapRunner implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(AdminBootstrapRunner.class);
private final AdminMapper adminMapper;
private final PasswordEncoder passwordEncoder;
private final CryptoService cryptoService;
private final TotpService totpService;
private final PasswordHistoryService passwordHistoryService;
private final AuditService auditService;
@Value("${fin.bootstrap.enabled:true}")
private boolean enabled;
@Value("${fin.runtime-dir:./.runtime}")
private String runtimeDir;
public AdminBootstrapRunner(AdminMapper adminMapper,
PasswordEncoder passwordEncoder,
CryptoService cryptoService,
TotpService totpService,
PasswordHistoryService passwordHistoryService,
AuditService auditService) {
this.adminMapper = adminMapper;
this.passwordEncoder = passwordEncoder;
this.cryptoService = cryptoService;
this.totpService = totpService;
this.passwordHistoryService = passwordHistoryService;
this.auditService = auditService;
}
@Override
public void run(ApplicationArguments args) throws Exception {
if (!enabled) {
return;
}
Long count = adminMapper.selectCount(null);
if (count != null && count > 0) {
checkSuperAdminExists();
return;
}
String initialPassword = PasswordUtils.randomPassword(16);
String totpSecret = totpService.generateSecret();
AdminEntity admin = new AdminEntity();
admin.setUsername("admin");
admin.setPasswordHash(passwordEncoder.encode(initialPassword));
admin.setRole("SUPER_ADMIN");
admin.setIsActive(1);
admin.setMustChangePassword(1);
admin.setTotpSecretEnc(cryptoService.encrypt(totpSecret));
admin.setTotpBound(0);
admin.setFailedAttempts(0);
admin.setVersionNo(0);
adminMapper.insert(admin);
passwordHistoryService.record(admin.getId(), admin.getPasswordHash());
Path dir = Path.of(runtimeDir);
Files.createDirectories(dir);
Path file = dir.resolve("bootstrap-admin.txt");
Files.writeString(file, "username=admin" + System.lineSeparator()
+ "initialPassword=" + initialPassword + System.lineSeparator()
+ "totpSecret=" + totpSecret + System.lineSeparator()
+ "首次登录后必须修改密码;本文件仅用于本地开发,生产环境必须通过一次性安全通道交付并立即删除。"
+ System.lineSeparator());
auditService.record("SYSTEM", null, "SYSTEM", "ADMIN_BOOTSTRAP", "初始化超级管理员",
"ADMIN", admin.getId(), null, Map.of("username", "admin"), "127.0.0.1", "system");
log.warn("已创建初始超级管理员 admin,初始凭据写入: {}", file.toAbsolutePath());
log.warn("首次登录后必须修改密码;生产环境请通过一次性安全通道交付并删除该文件");
}
private void checkSuperAdminExists() {
Long count = adminMapper.selectCount(new LambdaQueryWrapper<AdminEntity>()
.eq(AdminEntity::getRole, "SUPER_ADMIN")
.eq(AdminEntity::getIsActive, 1));
if (count == null || count == 0) {
log.error("当前系统没有启用状态的超级管理员,请立即通过数据库或运维流程恢复");
}
}
}
@@ -0,0 +1,77 @@
package com.gas.fin.admin.controller;
import com.gas.fin.admin.dto.AdminCreateRequest;
import com.gas.fin.admin.dto.AdminCreateResponse;
import com.gas.fin.admin.dto.AdminRoleUpdateRequest;
import com.gas.fin.admin.dto.AdminToggleRequest;
import com.gas.fin.admin.dto.AdminTotpRequest;
import com.gas.fin.admin.dto.MessageResponse;
import com.gas.fin.admin.dto.TempPasswordResponse;
import com.gas.fin.admin.service.AdminService;
import com.gas.fin.auth.dto.AdminInfoResponse;
import com.gas.fin.common.api.R;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
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.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/admin/admins")
@RequirePermission(PermissionRegistry.ADMIN_MANAGE)
public class AdminController {
private final AdminService adminService;
public AdminController(AdminService adminService) {
this.adminService = adminService;
}
@GetMapping
public R<List<AdminInfoResponse>> list() {
return R.ok(adminService.list());
}
@PostMapping
public R<AdminCreateResponse> create(@Valid @RequestBody AdminCreateRequest request,
HttpServletRequest httpRequest) {
return R.ok(adminService.create(request, AuthContext.require(), httpRequest));
}
@PutMapping("/{id}")
public R<AdminInfoResponse> updateRole(@PathVariable Long id,
@Valid @RequestBody AdminRoleUpdateRequest request,
HttpServletRequest httpRequest) {
return R.ok(adminService.updateRole(id, request, AuthContext.require(), httpRequest));
}
@PostMapping("/{id}/toggle")
public R<AdminInfoResponse> toggle(@PathVariable Long id,
@Valid @RequestBody AdminToggleRequest request,
HttpServletRequest httpRequest) {
return R.ok(adminService.toggle(id, request, AuthContext.require(), httpRequest));
}
@PostMapping("/{id}/reset-password")
public R<TempPasswordResponse> resetPassword(@PathVariable Long id,
@Valid @RequestBody AdminTotpRequest request,
HttpServletRequest httpRequest) {
return R.ok(adminService.resetPassword(id, request.getTotp(), AuthContext.require(), httpRequest));
}
@PostMapping("/{id}/reset-totp")
public R<MessageResponse> resetTotp(@PathVariable Long id,
@Valid @RequestBody AdminTotpRequest request,
HttpServletRequest httpRequest) {
return R.ok(adminService.resetTotp(id, request.getTotp(), AuthContext.require(), httpRequest));
}
}
@@ -0,0 +1,19 @@
package com.gas.fin.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
@Data
public class AdminCreateRequest {
@NotBlank(message = "用户名不能为空")
@Pattern(regexp = "^[a-z][a-z0-9_]{2,31}$", message = "用户名需为 3~32 位小写字母/数字/下划线,且以字母开头")
private String username;
@NotBlank(message = "角色不能为空")
@Pattern(regexp = "^(SUPER_ADMIN|FINANCE|AUDITOR)$", message = "角色不合法")
private String role;
private String totp;
}
@@ -0,0 +1,13 @@
package com.gas.fin.admin.dto;
import com.gas.fin.auth.dto.AdminInfoResponse;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class AdminCreateResponse {
private AdminInfoResponse admin;
private String initialPassword;
}
@@ -0,0 +1,13 @@
package com.gas.fin.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
@Data
public class AdminRoleUpdateRequest {
@NotBlank(message = "角色不能为空")
@Pattern(regexp = "^(SUPER_ADMIN|FINANCE|AUDITOR)$", message = "角色不合法")
private String role;
}
@@ -0,0 +1,15 @@
package com.gas.fin.admin.dto;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class AdminToggleRequest {
@NotNull(message = "enabled 不能为空")
@Min(value = 0, message = "enabled 只能为 0 或 1")
@Max(value = 1, message = "enabled 只能为 0 或 1")
private Integer enabled;
}
@@ -0,0 +1,9 @@
package com.gas.fin.admin.dto;
import lombok.Data;
@Data
public class AdminTotpRequest {
private String totp;
}
@@ -0,0 +1,11 @@
package com.gas.fin.admin.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MessageResponse {
private String message;
}
@@ -0,0 +1,11 @@
package com.gas.fin.admin.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class TempPasswordResponse {
private String tempPassword;
}
@@ -0,0 +1,32 @@
package com.gas.fin.admin.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_admin")
public class AdminEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String username;
private String passwordHash;
private String role;
private Integer isActive;
private Integer mustChangePassword;
private String totpSecretEnc;
private Integer totpBound;
private Integer failedAttempts;
private LocalDateTime lockedUntil;
private LocalDateTime lastLoginAt;
private String lastLoginIp;
private LocalDateTime passwordUpdatedAt;
private Integer versionNo;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,20 @@
package com.gas.fin.admin.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_admin_password_history")
public class AdminPasswordHistoryEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private Long adminId;
private String passwordHash;
private LocalDateTime createTime;
}
@@ -0,0 +1,26 @@
package com.gas.fin.admin.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_admin_session")
public class AdminSessionEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private Long adminId;
private String tokenHash;
private String issuedIp;
private String userAgent;
private LocalDateTime lastActiveAt;
private LocalDateTime idleExpireAt;
private LocalDateTime absoluteExpireAt;
private LocalDateTime revokedAt;
private LocalDateTime createTime;
}
@@ -0,0 +1,9 @@
package com.gas.fin.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.admin.entity.AdminEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AdminMapper extends BaseMapper<AdminEntity> {
}
@@ -0,0 +1,9 @@
package com.gas.fin.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.admin.entity.AdminPasswordHistoryEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AdminPasswordHistoryMapper extends BaseMapper<AdminPasswordHistoryEntity> {
}
@@ -0,0 +1,9 @@
package com.gas.fin.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.admin.entity.AdminSessionEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AdminSessionMapper extends BaseMapper<AdminSessionEntity> {
}
@@ -0,0 +1,266 @@
package com.gas.fin.admin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gas.fin.admin.dto.AdminCreateRequest;
import com.gas.fin.admin.dto.AdminCreateResponse;
import com.gas.fin.admin.dto.AdminRoleUpdateRequest;
import com.gas.fin.admin.dto.AdminToggleRequest;
import com.gas.fin.admin.dto.MessageResponse;
import com.gas.fin.admin.dto.TempPasswordResponse;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.admin.mapper.AdminMapper;
import com.gas.fin.audit.service.AuditService;
import com.gas.fin.auth.dto.AdminInfoResponse;
import com.gas.fin.auth.service.PasswordHistoryService;
import com.gas.fin.auth.service.SessionService;
import com.gas.fin.common.crypto.CryptoService;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.totp.TotpService;
import com.gas.fin.common.util.PasswordUtils;
import com.gas.fin.common.web.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@Service
public class AdminService {
private final AdminMapper adminMapper;
private final PasswordEncoder passwordEncoder;
private final CryptoService cryptoService;
private final TotpService totpService;
private final AuditService auditService;
private final SessionService sessionService;
private final PasswordHistoryService passwordHistoryService;
@Value("${fin.trust-proxy:true}")
private boolean trustProxy;
@Value("${fin.runtime-dir:./.runtime}")
private String runtimeDir;
@Value("${fin.admin.totp-output-enabled:true}")
private boolean totpOutputEnabled;
public AdminService(AdminMapper adminMapper,
PasswordEncoder passwordEncoder,
CryptoService cryptoService,
TotpService totpService,
AuditService auditService,
SessionService sessionService,
PasswordHistoryService passwordHistoryService) {
this.adminMapper = adminMapper;
this.passwordEncoder = passwordEncoder;
this.cryptoService = cryptoService;
this.totpService = totpService;
this.auditService = auditService;
this.sessionService = sessionService;
this.passwordHistoryService = passwordHistoryService;
}
public List<AdminInfoResponse> list() {
return adminMapper.selectList(new LambdaQueryWrapper<AdminEntity>()
.orderByAsc(AdminEntity::getCreateTime)
.orderByAsc(AdminEntity::getId))
.stream()
.map(AdminInfoResponse::from)
.toList();
}
@Transactional
public AdminCreateResponse create(AdminCreateRequest request, AdminEntity current, HttpServletRequest httpRequest) {
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
validateTotp(current, request.getTotp(), ip, ua, "ADMIN_CREATE", "创建管理员");
String username = request.getUsername().trim().toLowerCase(Locale.ROOT);
Long exists = adminMapper.selectCount(new LambdaQueryWrapper<AdminEntity>()
.eq(AdminEntity::getUsername, username));
if (exists != null && exists > 0) {
throw new BizException(ErrorCode.DUPLICATE_KEY, "用户名已存在");
}
String initialPassword = PasswordUtils.randomPassword(16);
String totpSecret = totpService.generateSecret();
AdminEntity admin = new AdminEntity();
admin.setUsername(username);
admin.setPasswordHash(passwordEncoder.encode(initialPassword));
admin.setRole(request.getRole());
admin.setIsActive(1);
admin.setMustChangePassword(1);
admin.setTotpSecretEnc(cryptoService.encrypt(totpSecret));
admin.setTotpBound(0);
admin.setFailedAttempts(0);
admin.setVersionNo(0);
adminMapper.insert(admin);
passwordHistoryService.record(admin.getId(), admin.getPasswordHash());
writeTotpSecret(username, totpSecret);
AdminEntity saved = adminMapper.selectById(admin.getId());
Map<String, Object> after = new LinkedHashMap<>();
after.put("username", username);
after.put("role", request.getRole());
auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_CREATE", "创建管理员",
"ADMIN", admin.getId(), null, after, ip, ua);
return new AdminCreateResponse(AdminInfoResponse.from(saved), initialPassword);
}
@Transactional
public AdminInfoResponse updateRole(Long id, AdminRoleUpdateRequest request, AdminEntity current,
HttpServletRequest httpRequest) {
AdminEntity target = requireAdmin(id);
ensureNotLastSuperAdmin(target, request.getRole());
Map<String, Object> before = new LinkedHashMap<>();
before.put("role", target.getRole());
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, id)
.set(AdminEntity::getRole, request.getRole()));
target.setRole(request.getRole());
Map<String, Object> after = new LinkedHashMap<>();
after.put("role", request.getRole());
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_UPDATE_ROLE", "修改管理员角色",
"ADMIN", id, before, after, ip, ua);
return AdminInfoResponse.from(adminMapper.selectById(id));
}
@Transactional
public AdminInfoResponse toggle(Long id, AdminToggleRequest request, AdminEntity current,
HttpServletRequest httpRequest) {
AdminEntity target = requireAdmin(id);
boolean disabling = Integer.valueOf(0).equals(request.getEnabled());
if (disabling) {
if (id.equals(current.getId())) {
throw new BizException(ErrorCode.ADMIN_CONSTRAINT, "不能停用当前登录账号");
}
ensureNotLastSuperAdmin(target, "DISABLED");
}
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, id)
.set(AdminEntity::getIsActive, request.getEnabled()));
if (disabling) {
sessionService.revokeAll(id);
}
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
Map<String, Object> after = new LinkedHashMap<>();
after.put("enabled", request.getEnabled());
auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_TOGGLE", "启用/停用管理员",
"ADMIN", id, null, after, ip, ua);
return AdminInfoResponse.from(adminMapper.selectById(id));
}
@Transactional
public TempPasswordResponse resetPassword(Long id, String totp, AdminEntity current,
HttpServletRequest httpRequest) {
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
validateTotp(current, totp, ip, ua, "ADMIN_RESET_PASSWORD", "重置管理员密码");
AdminEntity target = requireAdmin(id);
String tempPassword = PasswordUtils.randomPassword(16);
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, id)
.set(AdminEntity::getPasswordHash, passwordEncoder.encode(tempPassword))
.set(AdminEntity::getMustChangePassword, 1)
.set(AdminEntity::getFailedAttempts, 0)
.set(AdminEntity::getLockedUntil, null)
.set(AdminEntity::getVersionNo, target.getVersionNo() == null ? 1 : target.getVersionNo() + 1));
passwordHistoryService.record(id, target.getPasswordHash());
sessionService.revokeAll(id);
auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_RESET_PASSWORD", "重置管理员密码",
"ADMIN", id, null, Map.of("mustChangePassword", 1), ip, ua);
return new TempPasswordResponse(tempPassword);
}
@Transactional
public MessageResponse resetTotp(Long id, String totp, AdminEntity current, HttpServletRequest httpRequest) {
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
validateTotp(current, totp, ip, ua, "ADMIN_RESET_TOTP", "重置管理员TOTP");
AdminEntity target = requireAdmin(id);
String newSecret = totpService.generateSecret();
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, id)
.set(AdminEntity::getTotpSecretEnc, cryptoService.encrypt(newSecret))
.set(AdminEntity::getTotpBound, 0));
writeTotpSecret(target.getUsername(), newSecret);
auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_RESET_TOTP", "重置管理员TOTP",
"ADMIN", id, null, null, ip, ua);
return new MessageResponse("TOTP 已重置,新密钥已通过运维安全通道交付");
}
public AdminEntity requireAdmin(Long id) {
AdminEntity admin = adminMapper.selectById(id);
if (admin == null) {
throw new BizException(ErrorCode.NOT_FOUND);
}
return admin;
}
public long countActiveSuperAdmins() {
Long count = adminMapper.selectCount(new LambdaQueryWrapper<AdminEntity>()
.eq(AdminEntity::getRole, "SUPER_ADMIN")
.eq(AdminEntity::getIsActive, 1));
return count == null ? 0 : count;
}
private void ensureNotLastSuperAdmin(AdminEntity target, String newRole) {
boolean targetIsActiveSuper = "SUPER_ADMIN".equals(target.getRole())
&& Integer.valueOf(1).equals(target.getIsActive());
if (!targetIsActiveSuper) {
return;
}
boolean stillSuper = newRole == null || "SUPER_ADMIN".equals(newRole);
if (!stillSuper && countActiveSuperAdmins() <= 1) {
throw new BizException(ErrorCode.ADMIN_CONSTRAINT, "不能降级或停用最后一名启用状态的超级管理员");
}
}
private void validateTotp(AdminEntity admin, String code, String ip, String ua,
String action, String actionLabel) {
String secret;
try {
secret = cryptoService.decrypt(admin.getTotpSecretEnc());
} catch (Exception ex) {
secret = null;
}
TotpService.Result result = totpService.verify(secret, code, admin.getId());
if (result != TotpService.Result.OK) {
auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(), action, actionLabel,
"ADMIN", admin.getId(), null, null, ip, ua);
throw new BizException(ErrorCode.TOTP_FAILED);
}
}
private void writeTotpSecret(String username, String secret) {
if (!totpOutputEnabled) {
return;
}
try {
Path dir = Path.of(runtimeDir);
Files.createDirectories(dir);
Path file = dir.resolve("admin-totp-" + username + ".txt");
Files.writeString(file, "username=" + username + System.lineSeparator()
+ "totpSecret=" + secret + System.lineSeparator()
+ "注意:本文件仅用于本地开发,生产环境必须由运维通过一次性安全通道交付并立即删除。" + System.lineSeparator());
} catch (Exception ex) {
throw new IllegalStateException("cannot write TOTP secret file", ex);
}
}
}
@@ -0,0 +1,96 @@
package com.gas.fin.app.controller;
import com.gas.fin.app.dto.AppCreateResponse;
import com.gas.fin.app.dto.AppInfoResponse;
import com.gas.fin.app.dto.AppPayloadRequest;
import com.gas.fin.app.dto.AppSecretRotateRequest;
import com.gas.fin.app.dto.AppSecretRotateResponse;
import com.gas.fin.app.dto.AppTokenResponse;
import com.gas.fin.app.service.AppService;
import com.gas.fin.common.api.R;
import com.gas.fin.common.dto.ToggleRequest;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import jakarta.servlet.http.HttpServletRequest;
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.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/admin/apps")
public class AppController {
private final AppService appService;
public AppController(AppService appService) {
this.appService = appService;
}
@GetMapping
@RequirePermission(PermissionRegistry.VIEW)
public R<List<AppInfoResponse>> list() {
return R.ok(appService.list());
}
@PostMapping
@RequirePermission(PermissionRegistry.APP_MANAGE)
public R<AppCreateResponse> create(@RequestBody AppPayloadRequest request,
HttpServletRequest httpRequest) {
return R.ok(appService.create(request, AuthContext.require(), httpRequest));
}
@PutMapping("/{appCode}")
@RequirePermission(PermissionRegistry.APP_MANAGE)
public R<AppInfoResponse> update(@PathVariable String appCode,
@RequestBody AppPayloadRequest request,
HttpServletRequest httpRequest) {
return R.ok(appService.update(appCode, request, AuthContext.require(), httpRequest));
}
@PostMapping("/{appCode}/secret/rotate")
@RequirePermission(PermissionRegistry.APP_MANAGE)
public R<AppSecretRotateResponse> rotate(@PathVariable String appCode,
@RequestBody(required = false) AppSecretRotateRequest request,
HttpServletRequest httpRequest) {
Integer graceHours = request == null ? null : request.graceHours();
return R.ok(appService.rotate(appCode, graceHours, AuthContext.require(), httpRequest));
}
@PostMapping("/{appCode}/secret/revoke-prev")
@RequirePermission(PermissionRegistry.APP_MANAGE)
public R<Object> revokePrev(@PathVariable String appCode, HttpServletRequest httpRequest) {
appService.revokePrevSecret(appCode, AuthContext.require(), httpRequest);
return R.ok();
}
@PostMapping("/{appCode}/toggle")
@RequirePermission(PermissionRegistry.APP_MANAGE)
public R<AppInfoResponse> toggle(@PathVariable String appCode,
@RequestBody ToggleRequest request,
HttpServletRequest httpRequest) {
return R.ok(appService.toggle(appCode, request.enabled(), AuthContext.require(), httpRequest));
}
@GetMapping("/{appCode}/tokens")
@RequirePermission(PermissionRegistry.VIEW)
public R<List<AppTokenResponse>> tokens(@PathVariable String appCode) {
return R.ok(appService.tokens(appCode));
}
@PostMapping("/{appCode}/tokens/revoke")
@RequirePermission(PermissionRegistry.APP_MANAGE)
public R<Map<String, Object>> revokeTokens(@PathVariable String appCode,
@RequestBody(required = false) Map<String, Long> body,
HttpServletRequest httpRequest) {
Long tokenId = body == null ? null : body.get("tokenId");
return R.ok(appService.revokeTokens(appCode, tokenId, AuthContext.require(), httpRequest));
}
}
@@ -0,0 +1,4 @@
package com.gas.fin.app.dto;
public record AppCreateResponse(AppInfoResponse app, String clientSecret) {
}
@@ -0,0 +1,45 @@
package com.gas.fin.app.dto;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class AppInfoResponse {
private String appCode;
private String appName;
private String allowedRedirectHosts;
private String webhookUrl;
private Integer tokenTtlSeconds;
private Integer enabled;
private LocalDateTime secretExpiresAt;
private boolean hasPrevSecret;
private LocalDateTime createTime;
private long accountCount;
private long todayAmountCent;
public static AppInfoResponse from(AppEntityView app, long accountCount, long todayAmountCent) {
AppInfoResponse response = new AppInfoResponse();
response.setAppCode(app.appCode());
response.setAppName(app.appName());
response.setAllowedRedirectHosts(app.allowedRedirectHosts());
response.setWebhookUrl(app.webhookUrl() == null ? "" : app.webhookUrl());
response.setTokenTtlSeconds(app.tokenTtlSeconds());
response.setEnabled(app.enabled());
response.setSecretExpiresAt(app.secretExpiresAt());
response.setHasPrevSecret(app.hasPrevSecret());
response.setCreateTime(app.createTime());
response.setAccountCount(accountCount);
response.setTodayAmountCent(todayAmountCent);
return response;
}
/**
* 保持 DTO 与实体解耦的只读视图,避免把 webhookSecretEnc 等敏感字段带出。
*/
public record AppEntityView(String appCode, String appName, String allowedRedirectHosts, String webhookUrl,
Integer tokenTtlSeconds, Integer enabled, LocalDateTime secretExpiresAt,
boolean hasPrevSecret, LocalDateTime createTime) {
}
}
@@ -0,0 +1,5 @@
package com.gas.fin.app.dto;
public record AppPayloadRequest(String appCode, String appName, String allowedRedirectHosts,
String webhookUrl, Integer tokenTtlSeconds) {
}
@@ -0,0 +1,4 @@
package com.gas.fin.app.dto;
public record AppSecretRotateRequest(Integer graceHours) {
}
@@ -0,0 +1,6 @@
package com.gas.fin.app.dto;
import java.time.LocalDateTime;
public record AppSecretRotateResponse(String clientSecret, LocalDateTime expiresAt) {
}
@@ -0,0 +1,30 @@
package com.gas.fin.app.dto;
import com.gas.fin.app.entity.AppTokenEntity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class AppTokenResponse {
private Long id;
private String appCode;
private String tokenPrefix;
private LocalDateTime expiresAt;
private LocalDateTime revokedAt;
private String issuedIp;
private LocalDateTime createTime;
public static AppTokenResponse from(AppTokenEntity entity) {
AppTokenResponse response = new AppTokenResponse();
response.setId(entity.getId());
response.setAppCode(entity.getAppCode());
response.setTokenPrefix(entity.getTokenPrefix());
response.setExpiresAt(entity.getExpiresAt());
response.setRevokedAt(entity.getRevokedAt());
response.setIssuedIp(entity.getIssuedIp() == null ? "" : entity.getIssuedIp());
response.setCreateTime(entity.getCreateTime());
return response;
}
}
@@ -0,0 +1,28 @@
package com.gas.fin.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_app")
public class AppEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String appCode;
private String appName;
private String allowedRedirectHosts;
private String webhookUrl;
private String webhookSecretEnc;
private Integer tokenTtlSeconds;
private Integer enabled;
private LocalDateTime secretExpiresAt;
private Integer hasPrevSecret;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,25 @@
package com.gas.fin.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_app_secret")
public class AppSecretEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String appCode;
private String secretHash;
private String secretPrefix;
private String status;
private LocalDateTime graceExpireAt;
private Long createdBy;
private LocalDateTime createTime;
private LocalDateTime revokedAt;
}
@@ -0,0 +1,24 @@
package com.gas.fin.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_app_token")
public class AppTokenEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String appCode;
private String tokenHash;
private String tokenPrefix;
private String issuedIp;
private LocalDateTime expiresAt;
private LocalDateTime revokedAt;
private LocalDateTime createTime;
}
@@ -0,0 +1,9 @@
package com.gas.fin.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.app.entity.AppEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AppMapper extends BaseMapper<AppEntity> {
}
@@ -0,0 +1,9 @@
package com.gas.fin.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.app.entity.AppSecretEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AppSecretMapper extends BaseMapper<AppSecretEntity> {
}
@@ -0,0 +1,9 @@
package com.gas.fin.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.app.entity.AppTokenEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AppTokenMapper extends BaseMapper<AppTokenEntity> {
}
@@ -0,0 +1,439 @@
package com.gas.fin.app.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gas.fin.account.entity.AccountEntity;
import com.gas.fin.account.mapper.AccountMapper;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.app.dto.AppCreateResponse;
import com.gas.fin.app.dto.AppInfoResponse;
import com.gas.fin.app.dto.AppPayloadRequest;
import com.gas.fin.app.dto.AppSecretRotateResponse;
import com.gas.fin.app.dto.AppTokenResponse;
import com.gas.fin.app.entity.AppEntity;
import com.gas.fin.app.entity.AppSecretEntity;
import com.gas.fin.app.entity.AppTokenEntity;
import com.gas.fin.app.mapper.AppMapper;
import com.gas.fin.app.mapper.AppSecretMapper;
import com.gas.fin.app.mapper.AppTokenMapper;
import com.gas.fin.common.crypto.CryptoService;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.security.AdminAuditor;
import com.gas.fin.common.util.HashUtils;
import com.gas.fin.order.entity.CashLedgerEntity;
import com.gas.fin.order.mapper.CashLedgerMapper;
import com.gas.fin.pricing.entity.AppPolicyEntity;
import com.gas.fin.pricing.entity.AppPricingEntity;
import com.gas.fin.pricing.mapper.AppPolicyMapper;
import com.gas.fin.pricing.mapper.AppPricingMapper;
import com.gas.fin.setting.service.ConfigService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 接入应用与密钥管理。
*/
@Service
public class AppService {
private static final String APP_CODE_RULE = "^[a-z][a-z0-9-]{2,31}$";
private final AppMapper appMapper;
private final AppSecretMapper secretMapper;
private final AppTokenMapper tokenMapper;
private final AccountMapper accountMapper;
private final CashLedgerMapper cashLedgerMapper;
private final AppPricingMapper pricingMapper;
private final AppPolicyMapper policyMapper;
private final ConfigService configService;
private final CryptoService cryptoService;
private final AdminAuditor adminAuditor;
public AppService(AppMapper appMapper, AppSecretMapper secretMapper, AppTokenMapper tokenMapper,
AccountMapper accountMapper, CashLedgerMapper cashLedgerMapper,
AppPricingMapper pricingMapper, AppPolicyMapper policyMapper,
ConfigService configService, CryptoService cryptoService, AdminAuditor adminAuditor) {
this.appMapper = appMapper;
this.secretMapper = secretMapper;
this.tokenMapper = tokenMapper;
this.accountMapper = accountMapper;
this.cashLedgerMapper = cashLedgerMapper;
this.pricingMapper = pricingMapper;
this.policyMapper = policyMapper;
this.configService = configService;
this.cryptoService = cryptoService;
this.adminAuditor = adminAuditor;
}
public AppEntity require(String appCode) {
AppEntity app = appMapper.selectOne(new LambdaQueryWrapper<AppEntity>()
.eq(AppEntity::getAppCode, appCode)
.last("LIMIT 1"));
if (app == null) {
throw new BizException(ErrorCode.NOT_FOUND, "接入应用不存在");
}
return app;
}
public List<AppInfoResponse> list() {
List<AppEntity> apps = appMapper.selectList(new LambdaQueryWrapper<AppEntity>()
.orderByAsc(AppEntity::getCreateTime).orderByAsc(AppEntity::getId));
Map<String, Long> accountCounts = new HashMap<>();
accountMapper.selectList(new LambdaQueryWrapper<AccountEntity>()
.select(AccountEntity::getAppCode))
.forEach(item -> accountCounts.merge(item.getAppCode(), 1L, Long::sum));
LocalDateTime dayStart = LocalDate.now().atStartOfDay();
LocalDateTime dayEnd = dayStart.plusDays(1);
Map<String, Long> todayAmounts = new HashMap<>();
cashLedgerMapper.selectList(new LambdaQueryWrapper<CashLedgerEntity>()
.eq(CashLedgerEntity::getDirection, "IN")
.ge(CashLedgerEntity::getReceivedAt, dayStart)
.lt(CashLedgerEntity::getReceivedAt, dayEnd))
.forEach(item -> todayAmounts.merge(item.getAppCode(), item.getAmountCent(), Long::sum));
return apps.stream()
.map(app -> AppInfoResponse.from(view(app),
accountCounts.getOrDefault(app.getAppCode(), 0L),
todayAmounts.getOrDefault(app.getAppCode(), 0L)))
.toList();
}
@Transactional
public AppCreateResponse create(AppPayloadRequest request, AdminEntity current, HttpServletRequest httpRequest) {
String appCode = trim(request.appCode());
String appName = trim(request.appName());
String hosts = trim(request.allowedRedirectHosts());
String webhookUrl = trim(request.webhookUrl());
if (!appCode.matches(APP_CODE_RULE)) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "app_code 需为 3~32 位小写字母、数字或短横线");
}
if (appName.length() < 2 || appName.length() > 64) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "应用名称需为 2~64 个字符");
}
if (appMapper.selectCount(new LambdaQueryWrapper<AppEntity>()
.eq(AppEntity::getAppCode, appCode)) > 0) {
throw new BizException(ErrorCode.DUPLICATE_KEY, "app_code 已存在");
}
assertHosts(hosts);
assertWebhookUrl(webhookUrl);
int ttl = request.tokenTtlSeconds() == null
? (int) configService.getNumber("token.ttl_seconds", 900)
: request.tokenTtlSeconds();
assertTtl(ttl);
String clientSecret = newSecret("sk");
String webhookSecret = newSecret("whsec");
LocalDateTime now = LocalDateTime.now().withNano(0);
AppEntity app = new AppEntity();
app.setAppCode(appCode);
app.setAppName(appName);
app.setAllowedRedirectHosts(hosts);
app.setWebhookUrl(webhookUrl);
app.setWebhookSecretEnc(cryptoService.encrypt(webhookSecret));
app.setTokenTtlSeconds(ttl);
app.setEnabled(1);
app.setHasPrevSecret(0);
app.setCreateTime(now);
app.setUpdateTime(now);
appMapper.insert(app);
AppSecretEntity secret = new AppSecretEntity();
secret.setAppCode(appCode);
secret.setSecretHash(HashUtils.sha256Hex(clientSecret));
secret.setSecretPrefix(clientSecret.substring(0, 12));
secret.setStatus("ACTIVE");
secret.setCreatedBy(current.getId());
secret.setCreateTime(now);
secretMapper.insert(secret);
AppPricingEntity pricing = new AppPricingEntity();
pricing.setAppCode(appCode);
pricing.setPointsPerYuan(100L);
pricing.setEnabled(1);
pricing.setUpdateBy(current.getUsername());
pricing.setVersionNo(0);
pricing.setCreateTime(now);
pricing.setUpdateTime(now);
pricingMapper.insert(pricing);
AppPolicyEntity policy = new AppPolicyEntity();
policy.setAppCode(appCode);
policy.setMinCost(0L);
policy.setMaxPointsPerCharge(50000L);
policy.setVipExempt(0);
policy.setFailedStrategy("none");
policy.setDualControlThresholdCent(configService.getNumber("review.threshold_cent", 500000));
policy.setEnabled(1);
policy.setUpdateBy(current.getUsername());
policy.setVersionNo(0);
policy.setCreateTime(now);
policy.setUpdateTime(now);
policyMapper.insert(policy);
Map<String, Object> after = new LinkedHashMap<>();
after.put("appCode", appCode);
after.put("appName", appName);
after.put("allowedRedirectHosts", hosts);
after.put("tokenTtlSeconds", ttl);
adminAuditor.success(current, "APP_CREATE", "接入新应用", "APP", app.getId(), null, after, httpRequest);
return new AppCreateResponse(AppInfoResponse.from(view(app), 0, 0), clientSecret);
}
@Transactional
public AppInfoResponse update(String appCode, AppPayloadRequest request, AdminEntity current,
HttpServletRequest httpRequest) {
AppEntity app = require(appCode);
String hosts = trim(request.allowedRedirectHosts());
String webhookUrl = trim(request.webhookUrl());
String appName = trim(request.appName());
assertHosts(hosts);
if (!appName.isEmpty() && (appName.length() < 2 || appName.length() > 64)) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "应用名称需为 2~64 个字符");
}
assertWebhookUrl(webhookUrl);
int ttl = request.tokenTtlSeconds() == null ? app.getTokenTtlSeconds() : request.tokenTtlSeconds();
assertTtl(ttl);
Map<String, Object> before = new LinkedHashMap<>();
before.put("appName", app.getAppName());
before.put("allowedRedirectHosts", app.getAllowedRedirectHosts());
before.put("webhookUrl", app.getWebhookUrl());
before.put("tokenTtlSeconds", app.getTokenTtlSeconds());
appMapper.update(null, new LambdaUpdateWrapper<AppEntity>()
.eq(AppEntity::getId, app.getId())
.set(AppEntity::getAppName, appName.isEmpty() ? app.getAppName() : appName)
.set(AppEntity::getAllowedRedirectHosts, hosts)
.set(AppEntity::getWebhookUrl, webhookUrl)
.set(AppEntity::getTokenTtlSeconds, ttl)
.set(AppEntity::getUpdateTime, LocalDateTime.now().withNano(0)));
Map<String, Object> after = new LinkedHashMap<>();
after.put("appName", appName.isEmpty() ? app.getAppName() : appName);
after.put("allowedRedirectHosts", hosts);
after.put("webhookUrl", webhookUrl);
after.put("tokenTtlSeconds", ttl);
adminAuditor.success(current, "APP_UPDATE", "修改应用配置", "APP", app.getId(), before, after, httpRequest);
return listOf(require(appCode));
}
@Transactional
public AppSecretRotateResponse rotate(String appCode, Integer graceHours, AdminEntity current,
HttpServletRequest httpRequest) {
AppEntity app = require(appCode);
String clientSecret = newSecret("sk");
LocalDateTime now = LocalDateTime.now().withNano(0);
long hours = graceHours == null
? configService.getNumber("secret.rotate.grace_hours", 24)
: Math.max(0, graceHours);
LocalDateTime expiresAt = hours <= 0 ? null : now.plusHours(hours);
if (hours <= 0) {
secretMapper.update(null, new LambdaUpdateWrapper<AppSecretEntity>()
.eq(AppSecretEntity::getAppCode, appCode)
.eq(AppSecretEntity::getStatus, "ACTIVE")
.set(AppSecretEntity::getStatus, "REVOKED")
.set(AppSecretEntity::getRevokedAt, now));
app.setHasPrevSecret(0);
app.setSecretExpiresAt(null);
} else {
secretMapper.update(null, new LambdaUpdateWrapper<AppSecretEntity>()
.eq(AppSecretEntity::getAppCode, appCode)
.eq(AppSecretEntity::getStatus, "ACTIVE")
.set(AppSecretEntity::getStatus, "GRACE")
.set(AppSecretEntity::getGraceExpireAt, expiresAt));
app.setHasPrevSecret(1);
app.setSecretExpiresAt(expiresAt);
}
appMapper.update(null, new LambdaUpdateWrapper<AppEntity>()
.eq(AppEntity::getId, app.getId())
.set(AppEntity::getHasPrevSecret, app.getHasPrevSecret())
.set(AppEntity::getSecretExpiresAt, app.getSecretExpiresAt())
.set(AppEntity::getUpdateTime, now));
AppSecretEntity secret = new AppSecretEntity();
secret.setAppCode(appCode);
secret.setSecretHash(HashUtils.sha256Hex(clientSecret));
secret.setSecretPrefix(clientSecret.substring(0, 12));
secret.setStatus("ACTIVE");
secret.setCreatedBy(current.getId());
secret.setCreateTime(now);
secretMapper.insert(secret);
adminAuditor.success(current, "APP_SECRET_ROTATE", "轮换应用密钥", "APP", app.getId(), null,
Map.of("graceHours", hours), httpRequest);
return new AppSecretRotateResponse(clientSecret, expiresAt);
}
@Transactional
public void revokePrevSecret(String appCode, AdminEntity current, HttpServletRequest httpRequest) {
AppEntity app = require(appCode);
Long grace = secretMapper.selectCount(new LambdaQueryWrapper<AppSecretEntity>()
.eq(AppSecretEntity::getAppCode, appCode)
.eq(AppSecretEntity::getStatus, "GRACE"));
if (grace == null || grace == 0) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "当前没有待回收的旧密钥");
}
LocalDateTime now = LocalDateTime.now().withNano(0);
secretMapper.update(null, new LambdaUpdateWrapper<AppSecretEntity>()
.eq(AppSecretEntity::getAppCode, appCode)
.eq(AppSecretEntity::getStatus, "GRACE")
.set(AppSecretEntity::getStatus, "REVOKED")
.set(AppSecretEntity::getRevokedAt, now));
appMapper.update(null, new LambdaUpdateWrapper<AppEntity>()
.eq(AppEntity::getId, app.getId())
.set(AppEntity::getHasPrevSecret, 0)
.set(AppEntity::getSecretExpiresAt, null)
.set(AppEntity::getUpdateTime, now));
adminAuditor.success(current, "APP_SECRET_REVOKE_PREV", "立即回收旧密钥", "APP", app.getId(),
null, null, httpRequest);
}
@Transactional
public AppInfoResponse toggle(String appCode, Integer enabled, AdminEntity current,
HttpServletRequest httpRequest) {
AppEntity app = require(appCode);
int value = Integer.valueOf(1).equals(enabled) ? 1 : 0;
LocalDateTime now = LocalDateTime.now().withNano(0);
appMapper.update(null, new LambdaUpdateWrapper<AppEntity>()
.eq(AppEntity::getId, app.getId())
.set(AppEntity::getEnabled, value)
.set(AppEntity::getUpdateTime, now));
if (value == 0) {
tokenMapper.update(null, new LambdaUpdateWrapper<AppTokenEntity>()
.eq(AppTokenEntity::getAppCode, appCode)
.isNull(AppTokenEntity::getRevokedAt)
.set(AppTokenEntity::getRevokedAt, now));
}
adminAuditor.success(current, "APP_TOGGLE",
value == 1 ? "启用应用" : "停用应用(熔断全部 token)",
"APP", app.getId(), null, Map.of("enabled", value), httpRequest);
return listOf(require(appCode));
}
public List<AppTokenResponse> tokens(String appCode) {
require(appCode);
return tokenMapper.selectList(new LambdaQueryWrapper<AppTokenEntity>()
.eq(AppTokenEntity::getAppCode, appCode)
.orderByDesc(AppTokenEntity::getCreateTime)
.orderByDesc(AppTokenEntity::getId))
.stream().map(AppTokenResponse::from).toList();
}
@Transactional
public Map<String, Object> revokeTokens(String appCode, Long tokenId, AdminEntity current,
HttpServletRequest httpRequest) {
AppEntity app = require(appCode);
LambdaUpdateWrapper<AppTokenEntity> wrapper = new LambdaUpdateWrapper<AppTokenEntity>()
.eq(AppTokenEntity::getAppCode, appCode)
.isNull(AppTokenEntity::getRevokedAt)
.set(AppTokenEntity::getRevokedAt, LocalDateTime.now().withNano(0));
if (tokenId != null) {
wrapper.eq(AppTokenEntity::getId, tokenId);
}
int revoked = tokenMapper.update(null, wrapper);
adminAuditor.success(current, "APP_TOKEN_REVOKE",
tokenId != null ? "撤销单个 client token" : "熔断全部 client token",
"APP", app.getId(), null,
Map.of("tokenId", tokenId == null ? "ALL" : tokenId, "count", revoked), httpRequest);
Map<String, Object> result = new LinkedHashMap<>();
result.put("revoked", revoked);
return result;
}
private AppInfoResponse listOf(AppEntity app) {
Long accounts = accountMapper.selectCount(new LambdaQueryWrapper<AccountEntity>()
.eq(AccountEntity::getAppCode, app.getAppCode()));
LocalDateTime dayStart = LocalDate.now().atStartOfDay();
long todayAmount = cashLedgerMapper.selectList(new LambdaQueryWrapper<CashLedgerEntity>()
.eq(CashLedgerEntity::getAppCode, app.getAppCode())
.eq(CashLedgerEntity::getDirection, "IN")
.ge(CashLedgerEntity::getReceivedAt, dayStart)
.lt(CashLedgerEntity::getReceivedAt, dayStart.plusDays(1)))
.stream().mapToLong(CashLedgerEntity::getAmountCent).sum();
return AppInfoResponse.from(view(app), accounts == null ? 0 : accounts, todayAmount);
}
private AppInfoResponse.AppEntityView view(AppEntity app) {
return new AppInfoResponse.AppEntityView(app.getAppCode(), app.getAppName(),
app.getAllowedRedirectHosts(), app.getWebhookUrl(), app.getTokenTtlSeconds(),
app.getEnabled(), app.getSecretExpiresAt(),
Integer.valueOf(1).equals(app.getHasPrevSecret()), app.getCreateTime());
}
private void assertTtl(int ttl) {
if (ttl < 60 || ttl > 86400) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "token 有效期需在 60~86400 秒之间");
}
}
private void assertHosts(String hosts) {
if (hosts.isEmpty()) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "必须配置跳转域名白名单");
}
for (String host : hosts.split(",")) {
if (!isSafeHost(host)) {
throw new BizException(ErrorCode.VALIDATION_FAILED,
"跳转域名不合法:" + host.trim() + "(禁止通配符与 IP 直连)");
}
}
}
private void assertWebhookUrl(String url) {
if (url.isEmpty()) {
return;
}
if (!url.startsWith("https://")) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "webhook 地址必须使用 HTTPS");
}
String host = hostOf(url);
if (host == null || !isSafeHost(host)) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "webhook 域名不合法(禁止 IP 直连与内网地址)");
}
}
public static String hostOf(String url) {
try {
String withoutScheme = url.replaceFirst("^[A-Za-z]+://", "");
String host = withoutScheme.split("[/?#]")[0];
int at = host.indexOf('@');
if (at >= 0) {
host = host.substring(at + 1);
}
int port = host.indexOf(':');
if (port >= 0) {
host = host.substring(0, port);
}
return host.isBlank() ? null : host.toLowerCase();
} catch (Exception ex) {
return null;
}
}
public static boolean isSafeHost(String host) {
String text = host == null ? "" : host.trim();
if (text.isEmpty() || text.contains("*") || text.contains("/") || text.contains(":")) {
return false;
}
if (text.matches("^\\d{1,3}(\\.\\d{1,3}){3}$")) {
return false;
}
return text.matches("^[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
}
private String newSecret(String prefix) {
return prefix + "_" + HexFormat.of().formatHex(HashUtils.randomBytes(24));
}
private String trim(String value) {
return value == null ? "" : value.trim();
}
}
@@ -0,0 +1,141 @@
package com.gas.fin.audit.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gas.fin.audit.dto.AuditLogResponse;
import com.gas.fin.audit.dto.ChainVerifyResult;
import com.gas.fin.audit.entity.AuditLogEntity;
import com.gas.fin.audit.service.AuditService;
import com.gas.fin.common.api.PageResult;
import com.gas.fin.common.api.R;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import com.gas.fin.common.web.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/admin/audit-logs")
public class AuditController {
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final AuditService auditService;
public AuditController(AuditService auditService) {
this.auditService = auditService;
}
@GetMapping
@RequirePermission(PermissionRegistry.AUDIT_VIEW)
public R<PageResult<AuditLogResponse>> list(
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long pageSize,
@RequestParam(required = false) String actor,
@RequestParam(required = false) String action,
@RequestParam(required = false) String result,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) String from,
@RequestParam(required = false) String to) {
validatePage(page, pageSize);
Page<AuditLogEntity> resultPage = auditService.page(page, pageSize, actor, action, result, keyword,
parseFrom(from), parseTo(to));
List<AuditLogResponse> records = resultPage.getRecords().stream().map(AuditLogResponse::from).toList();
return R.ok(PageResult.of(records, resultPage.getTotal(), page, pageSize));
}
@GetMapping("/export")
@RequirePermission({PermissionRegistry.EXPORT, PermissionRegistry.AUDIT_VIEW})
public R<List<AuditLogResponse>> export(
@RequestParam(required = false) String actor,
@RequestParam(required = false) String action,
@RequestParam(required = false) String result,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) String from,
@RequestParam(required = false) String to,
HttpServletRequest httpRequest) {
List<AuditLogEntity> logs = auditService.listForExport(10000, actor, action, result, keyword,
parseFrom(from), parseTo(to));
Map<String, Object> filter = new LinkedHashMap<>();
filter.put("actor", actor);
filter.put("action", action);
filter.put("result", result);
filter.put("keyword", keyword);
filter.put("from", from);
filter.put("to", to);
filter.put("count", logs.size());
auditService.record("ADMIN", AuthContext.require().getId(), AuthContext.require().getUsername(),
"AUDIT_EXPORT", "导出审计日志", "AUDIT", null, null, filter,
RequestUtils.clientIp(httpRequest, true), RequestUtils.userAgent(httpRequest));
return R.ok(logs.stream().map(AuditLogResponse::from).toList());
}
@PostMapping("/verify")
@RequirePermission(PermissionRegistry.AUDIT_VIEW)
public R<ChainVerifyResult> verify(HttpServletRequest httpRequest) {
ChainVerifyResult result = auditService.verifyChain();
auditService.record("ADMIN", AuthContext.require().getId(), AuthContext.require().getUsername(),
"AUDIT_CHAIN_VERIFY", "校验审计链", "AUDIT", null, null,
Map.of("valid", result.isValid(), "checked", result.getChecked(), "brokenAtId",
result.getBrokenAtId() == null ? "" : result.getBrokenAtId()),
RequestUtils.clientIp(httpRequest, true), RequestUtils.userAgent(httpRequest));
return R.ok(result);
}
@GetMapping("/{id}")
@RequirePermission(PermissionRegistry.AUDIT_VIEW)
public R<AuditLogResponse> detail(@PathVariable Long id) {
return R.ok(AuditLogResponse.from(auditService.getById(id)));
}
private void validatePage(long page, long pageSize) {
if (page < 1 || pageSize < 1 || pageSize > 100) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "分页参数不合法");
}
}
private LocalDateTime parseFrom(String value) {
if (value == null || value.isBlank()) {
return null;
}
String text = value.trim();
try {
if (text.length() == 10) {
return LocalDate.parse(text).atStartOfDay();
}
return LocalDateTime.parse(text, DATE_TIME);
} catch (DateTimeParseException ex) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss");
}
}
private LocalDateTime parseTo(String value) {
if (value == null || value.isBlank()) {
return null;
}
String text = value.trim();
try {
if (text.length() == 10) {
return LocalDate.parse(text).atTime(23, 59, 59);
}
return LocalDateTime.parse(text, DATE_TIME);
} catch (DateTimeParseException ex) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss");
}
}
}
@@ -0,0 +1,48 @@
package com.gas.fin.audit.dto;
import com.gas.fin.audit.entity.AuditLogEntity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class AuditLogResponse {
private Long id;
private String actorType;
private Long actorId;
private String actorName;
private String action;
private String actionLabel;
private String targetType;
private Long targetId;
private String beforeJson;
private String afterJson;
private String ip;
private String ua;
private String result;
private String prevHash;
private String curHash;
private LocalDateTime createTime;
public static AuditLogResponse from(AuditLogEntity entity) {
AuditLogResponse response = new AuditLogResponse();
response.setId(entity.getId());
response.setActorType(entity.getActorType());
response.setActorId(entity.getActorId());
response.setActorName(entity.getActorName());
response.setAction(entity.getAction());
response.setActionLabel(entity.getActionLabel());
response.setTargetType(entity.getTargetType());
response.setTargetId(entity.getTargetId());
response.setBeforeJson(entity.getBeforeJson());
response.setAfterJson(entity.getAfterJson());
response.setIp(entity.getIp());
response.setUa(entity.getUa() == null ? "" : entity.getUa());
response.setResult(entity.getResult());
response.setPrevHash(entity.getPrevHash());
response.setCurHash(entity.getCurHash());
response.setCreateTime(entity.getCreateTime());
return response;
}
}
@@ -0,0 +1,17 @@
package com.gas.fin.audit.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
public class ChainVerifyResult {
private boolean valid;
private int checked;
private Long brokenAtId;
private LocalDateTime checkedAt;
private String message;
}
@@ -0,0 +1,32 @@
package com.gas.fin.audit.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_audit_log")
public class AuditLogEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String actorType;
private Long actorId;
private String actorName;
private String action;
private String actionLabel;
private String targetType;
private Long targetId;
private String beforeJson;
private String afterJson;
private String ip;
private String ua;
private String result;
private String prevHash;
private String curHash;
private LocalDateTime createTime;
}
@@ -0,0 +1,9 @@
package com.gas.fin.audit.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.audit.entity.AuditLogEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AuditLogMapper extends BaseMapper<AuditLogEntity> {
}
@@ -0,0 +1,265 @@
package com.gas.fin.audit.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gas.fin.audit.dto.ChainVerifyResult;
import com.gas.fin.audit.entity.AuditLogEntity;
import com.gas.fin.audit.mapper.AuditLogMapper;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.util.HashUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
/**
* 审计日志:只追加 + 哈希链 + 写入串行化。
*/
@Service
public class AuditService {
private static final Logger log = LoggerFactory.getLogger(AuditService.class);
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final AuditLogMapper auditLogMapper;
private final StringRedisTemplate redisTemplate;
private final ObjectMapper objectMapper;
private final String chainLockKey;
private final Object localLock = new Object();
public AuditService(AuditLogMapper auditLogMapper,
StringRedisTemplate redisTemplate,
ObjectMapper objectMapper,
@Value("${fin.audit.chain-lock:lock:audit:chain}") String chainLockKey) {
this.auditLogMapper = auditLogMapper;
this.redisTemplate = redisTemplate;
this.objectMapper = objectMapper;
this.chainLockKey = chainLockKey;
}
/**
* 成功审计:加入当前事务,随业务一起提交/回滚。
*/
@Transactional
public void record(String actorType, Long actorId, String actorName, String action, String actionLabel,
String targetType, Long targetId, Object before, Object after, String ip, String ua) {
doRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId,
before, after, "SUCCESS", ip, ua);
}
/**
* 失败审计:独立事务,业务回滚也不丢失败记录。
*/
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void recordFailure(String actorType, Long actorId, String actorName, String action, String actionLabel,
String targetType, Long targetId, Object before, Object after, String ip, String ua) {
doRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId,
before, after, "FAILED", ip, ua);
}
private void doRecord(String actorType, Long actorId, String actorName, String action, String actionLabel,
String targetType, Long targetId, Object before, Object after, String result,
String ip, String ua) {
String canonicalBefore = canonicalJson(before);
String canonicalAfter = canonicalJson(after);
LocalDateTime now = LocalDateTime.now().withNano(0);
String timeText = now.format(TIME_FORMAT);
String lockToken = UUID.randomUUID().toString();
boolean locked = tryLock(lockToken);
if (!locked) {
synchronized (localLock) {
insertRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId,
canonicalBefore, canonicalAfter, result, ip, ua, now, timeText);
}
return;
}
try {
insertRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId,
canonicalBefore, canonicalAfter, result, ip, ua, now, timeText);
} finally {
try {
redisTemplate.delete(chainLockKey);
} catch (Exception ex) {
log.warn("release audit chain lock failed", ex);
}
}
}
private void insertRecord(String actorType, Long actorId, String actorName, String action, String actionLabel,
String targetType, Long targetId, String canonicalBefore, String canonicalAfter,
String result, String ip, String ua, LocalDateTime now, String timeText) {
AuditLogEntity last = auditLogMapper.selectOne(new LambdaQueryWrapper<AuditLogEntity>()
.orderByDesc(AuditLogEntity::getId)
.last("LIMIT 1"));
String prevHash = last == null ? "" : last.getCurHash();
String payload = prevHash + "|" + actorType + "|" + (actorId == null ? "" : actorId) + "|"
+ actorName + "|" + action + "|" + targetType + "|" + (targetId == null ? "" : targetId) + "|"
+ result + "|" + timeText + "|" + HashUtils.sha256Hex(canonicalBefore) + "|"
+ HashUtils.sha256Hex(canonicalAfter);
String curHash = HashUtils.sha256Hex(payload);
AuditLogEntity entity = new AuditLogEntity();
entity.setActorType(actorType);
entity.setActorId(actorId);
entity.setActorName(actorName == null ? "" : actorName);
entity.setAction(action);
entity.setActionLabel(actionLabel == null ? action : actionLabel);
entity.setTargetType(targetType);
entity.setTargetId(targetId);
entity.setBeforeJson(canonicalBefore);
entity.setAfterJson(canonicalAfter);
entity.setIp(ip == null || ip.isBlank() ? "unknown" : ip);
entity.setUa(ua == null ? "" : ua);
entity.setResult(result);
entity.setPrevHash(prevHash);
entity.setCurHash(curHash);
entity.setCreateTime(now);
auditLogMapper.insert(entity);
}
private boolean tryLock(String token) {
try {
for (int i = 0; i < 60; i++) {
Boolean ok = redisTemplate.opsForValue().setIfAbsent(chainLockKey, token, Duration.ofSeconds(3));
if (Boolean.TRUE.equals(ok)) {
return true;
}
Thread.sleep(50);
}
} catch (Exception ex) {
log.warn("audit chain lock unavailable, fallback to local lock", ex);
}
return false;
}
public Page<AuditLogEntity> page(long page, long pageSize, String actor, String action, String result,
String keyword, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<AuditLogEntity> wrapper = new LambdaQueryWrapper<>();
if (actor != null && !actor.isBlank()) {
wrapper.like(AuditLogEntity::getActorName, actor.trim());
}
if (action != null && !action.isBlank()) {
wrapper.eq(AuditLogEntity::getAction, action.trim());
}
if (result != null && !result.isBlank()) {
wrapper.eq(AuditLogEntity::getResult, result.trim());
}
if (keyword != null && !keyword.isBlank()) {
String value = keyword.trim();
wrapper.and(w -> w.like(AuditLogEntity::getActorName, value)
.or().like(AuditLogEntity::getAction, value)
.or().like(AuditLogEntity::getTargetType, value));
}
if (from != null) {
wrapper.ge(AuditLogEntity::getCreateTime, from);
}
if (to != null) {
wrapper.le(AuditLogEntity::getCreateTime, to);
}
wrapper.orderByDesc(AuditLogEntity::getCreateTime).orderByDesc(AuditLogEntity::getId);
return auditLogMapper.selectPage(new Page<>(page, pageSize), wrapper);
}
public List<AuditLogEntity> listForExport(long limit, String actor, String action, String result,
String keyword, LocalDateTime from, LocalDateTime to) {
Page<AuditLogEntity> page = page(1, Math.min(limit + 1, 10001), actor, action, result, keyword, from, to);
if (page.getTotal() > limit) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "导出数据超过 10000 行,请缩小查询范围");
}
return page.getRecords();
}
public AuditLogEntity getById(Long id) {
AuditLogEntity entity = auditLogMapper.selectById(id);
if (entity == null) {
throw new BizException(ErrorCode.NOT_FOUND);
}
return entity;
}
@Transactional
public ChainVerifyResult verifyChain() {
List<AuditLogEntity> logs = auditLogMapper.selectList(new LambdaQueryWrapper<AuditLogEntity>()
.orderByAsc(AuditLogEntity::getId));
String expectedPrev = "";
int checked = 0;
for (AuditLogEntity log : logs) {
checked++;
String canonicalBefore = canonicalJson(log.getBeforeJson());
String canonicalAfter = canonicalJson(log.getAfterJson());
String timeText = log.getCreateTime().format(TIME_FORMAT);
String payload = expectedPrev + "|" + log.getActorType() + "|"
+ (log.getActorId() == null ? "" : log.getActorId()) + "|"
+ log.getActorName() + "|" + log.getAction() + "|" + log.getTargetType() + "|"
+ (log.getTargetId() == null ? "" : log.getTargetId()) + "|"
+ log.getResult() + "|" + timeText + "|"
+ HashUtils.sha256Hex(canonicalBefore) + "|" + HashUtils.sha256Hex(canonicalAfter);
String computed = HashUtils.sha256Hex(payload);
if (!expectedPrev.equals(log.getPrevHash()) || !computed.equals(log.getCurHash())) {
return new ChainVerifyResult(false, checked, log.getId(), LocalDateTime.now().withNano(0),
"审计链在第 " + log.getId() + " 条断裂");
}
expectedPrev = log.getCurHash();
}
return new ChainVerifyResult(true, checked, null, LocalDateTime.now().withNano(0), "审计链完整");
}
private String canonicalJson(Object value) {
if (value == null) {
return null;
}
try {
JsonNode node;
if (value instanceof String text) {
if (text.isBlank()) {
return null;
}
node = objectMapper.readTree(text);
} else {
node = objectMapper.valueToTree(value);
}
return objectMapper.writeValueAsString(sortNode(node));
} catch (Exception ex) {
log.warn("审计 JSON 规范化失败,按原文保存", ex);
return String.valueOf(value);
}
}
/**
* 递归排序对象字段,保证 MySQL JSON 列回读后仍可复现同一哈希。
*/
private JsonNode sortNode(JsonNode node) {
if (node.isObject()) {
ObjectNode sorted = objectMapper.createObjectNode();
List<String> names = new java.util.ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
names.sort(String::compareTo);
for (String name : names) {
sorted.set(name, sortNode(node.get(name)));
}
return sorted;
}
if (node.isArray()) {
ArrayNode sorted = objectMapper.createArrayNode();
node.forEach(child -> sorted.add(sortNode(child)));
return sorted;
}
return node;
}
}
@@ -0,0 +1,56 @@
package com.gas.fin.auth.controller;
import com.gas.fin.auth.dto.ChangePasswordRequest;
import com.gas.fin.auth.dto.LoginRequest;
import com.gas.fin.auth.dto.LoginResponse;
import com.gas.fin.auth.dto.ProfileResponse;
import com.gas.fin.auth.service.AuthService;
import com.gas.fin.common.api.R;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import com.gas.fin.common.web.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
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;
@RestController
@RequestMapping("/api/admin")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("/login")
public R<LoginResponse> login(@Valid @RequestBody LoginRequest request, HttpServletRequest httpRequest) {
return R.ok(authService.login(request, httpRequest));
}
@PostMapping("/logout")
@RequirePermission(PermissionRegistry.VIEW)
public R<Object> logout(HttpServletRequest httpRequest) {
authService.logout(AuthContext.require(), RequestUtils.bearerToken(httpRequest), httpRequest);
return R.ok();
}
@GetMapping("/profile")
@RequirePermission(PermissionRegistry.VIEW)
public R<ProfileResponse> profile() {
return R.ok(authService.profile(AuthContext.require()));
}
@PostMapping("/password/change")
@RequirePermission(PermissionRegistry.VIEW)
public R<Object> changePassword(@Valid @RequestBody ChangePasswordRequest request,
HttpServletRequest httpRequest) {
authService.changePassword(AuthContext.require(), request, RequestUtils.bearerToken(httpRequest), httpRequest);
return R.ok();
}
}
@@ -0,0 +1,38 @@
package com.gas.fin.auth.dto;
import com.gas.fin.admin.entity.AdminEntity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class AdminInfoResponse {
private Long id;
private String username;
private String role;
private Integer isActive;
private Integer mustChangePassword;
private boolean totpBound;
private Integer failedAttempts;
private LocalDateTime lockedUntil;
private LocalDateTime lastLoginAt;
private String lastLoginIp;
private LocalDateTime createTime;
public static AdminInfoResponse from(AdminEntity entity) {
AdminInfoResponse response = new AdminInfoResponse();
response.setId(entity.getId());
response.setUsername(entity.getUsername());
response.setRole(entity.getRole());
response.setIsActive(entity.getIsActive());
response.setMustChangePassword(entity.getMustChangePassword());
response.setTotpBound(Integer.valueOf(1).equals(entity.getTotpBound()));
response.setFailedAttempts(entity.getFailedAttempts());
response.setLockedUntil(entity.getLockedUntil());
response.setLastLoginAt(entity.getLastLoginAt());
response.setLastLoginIp(entity.getLastLoginIp());
response.setCreateTime(entity.getCreateTime());
return response;
}
}
@@ -0,0 +1,16 @@
package com.gas.fin.auth.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class ChangePasswordRequest {
@NotBlank(message = "原密码不能为空")
@Size(max = 128, message = "原密码长度不能超过 128")
private String oldPassword;
@NotBlank(message = "新密码不能为空")
private String newPassword;
}
@@ -0,0 +1,19 @@
package com.gas.fin.auth.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class LoginRequest {
@NotBlank(message = "用户名不能为空")
@Size(max = 32, message = "用户名长度不能超过 32")
private String username;
@NotBlank(message = "密码不能为空")
@Size(max = 128, message = "密码长度不能超过 128")
private String password;
private String totp;
}
@@ -0,0 +1,15 @@
package com.gas.fin.auth.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class LoginResponse {
private String token;
private AdminInfoResponse admin;
private List<String> permissions;
}
@@ -0,0 +1,14 @@
package com.gas.fin.auth.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class ProfileResponse {
private AdminInfoResponse admin;
private List<String> permissions;
}
@@ -0,0 +1,233 @@
package com.gas.fin.auth.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.admin.mapper.AdminMapper;
import com.gas.fin.auth.dto.AdminInfoResponse;
import com.gas.fin.auth.dto.ChangePasswordRequest;
import com.gas.fin.auth.dto.LoginRequest;
import com.gas.fin.auth.dto.LoginResponse;
import com.gas.fin.auth.dto.ProfileResponse;
import com.gas.fin.audit.service.AuditService;
import com.gas.fin.common.crypto.CryptoService;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.totp.TotpService;
import com.gas.fin.common.util.HashUtils;
import com.gas.fin.common.util.PasswordUtils;
import com.gas.fin.common.web.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* 登录、登出、改密与会话签发。
*/
@Service
public class AuthService {
private final AdminMapper adminMapper;
private final PasswordEncoder passwordEncoder;
private final TotpService totpService;
private final CryptoService cryptoService;
private final AuditService auditService;
private final SessionService sessionService;
private final PasswordHistoryService passwordHistoryService;
private final LoginRateLimiter loginRateLimiter;
private final String dummyHash;
@Value("${fin.trust-proxy:true}")
private boolean trustProxy;
@Value("${fin.auth.lock-threshold:5}")
private int lockThreshold;
@Value("${fin.auth.lock-minutes:15}")
private int lockMinutes;
public AuthService(AdminMapper adminMapper,
PasswordEncoder passwordEncoder,
TotpService totpService,
CryptoService cryptoService,
AuditService auditService,
SessionService sessionService,
PasswordHistoryService passwordHistoryService,
LoginRateLimiter loginRateLimiter) {
this.adminMapper = adminMapper;
this.passwordEncoder = passwordEncoder;
this.totpService = totpService;
this.cryptoService = cryptoService;
this.auditService = auditService;
this.sessionService = sessionService;
this.passwordHistoryService = passwordHistoryService;
this.loginRateLimiter = loginRateLimiter;
this.dummyHash = passwordEncoder.encode("dummy-password-for-timing");
}
public LoginResponse login(LoginRequest request, HttpServletRequest httpRequest) {
String username = request.getUsername().trim().toLowerCase(Locale.ROOT);
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
loginRateLimiter.check(username, ip);
AdminEntity admin = adminMapper.selectOne(new LambdaQueryWrapper<AdminEntity>()
.eq(AdminEntity::getUsername, username)
.last("LIMIT 1"));
if (admin == null) {
// 不存在账号也执行一次哈希,避免响应耗时泄露账号是否存在
passwordEncoder.matches(request.getPassword(), dummyHash);
auditLoginFailure(null, username, ip, ua, 0, null);
throw new BizException(ErrorCode.LOGIN_FAILED);
}
LocalDateTime now = LocalDateTime.now();
if (admin.getLockedUntil() != null && admin.getLockedUntil().isAfter(now)) {
long remain = Math.max(1, Duration.between(now, admin.getLockedUntil()).toMinutes() + 1);
auditLoginFailure(admin, username, ip, ua, admin.getFailedAttempts(), admin.getLockedUntil());
throw new BizException(ErrorCode.ACCOUNT_LOCKED, "账号已锁定,请 " + remain + " 分钟后重试");
}
if (admin.getLockedUntil() != null) {
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, admin.getId())
.set(AdminEntity::getFailedAttempts, 0)
.set(AdminEntity::getLockedUntil, null));
admin.setFailedAttempts(0);
admin.setLockedUntil(null);
}
if (!passwordEncoder.matches(request.getPassword(), admin.getPasswordHash())) {
failAndThrow(admin, ip, ua, ErrorCode.LOGIN_FAILED);
}
if (!Integer.valueOf(1).equals(admin.getIsActive())) {
auditLoginFailure(admin, username, ip, ua, admin.getFailedAttempts(), admin.getLockedUntil());
throw new BizException(ErrorCode.ACCOUNT_DISABLED);
}
String secret = safeDecrypt(admin.getTotpSecretEnc());
TotpService.Result totpResult = totpService.verify(secret, request.getTotp(), admin.getId());
if (totpResult == TotpService.Result.FORMAT_INVALID) {
auditLoginFailure(admin, username, ip, ua, admin.getFailedAttempts(), admin.getLockedUntil());
throw new BizException(ErrorCode.TOTP_FAILED);
}
if (totpResult != TotpService.Result.OK) {
failAndThrow(admin, ip, ua, ErrorCode.TOTP_FAILED);
}
LocalDateTime loginAt = LocalDateTime.now().withNano(0);
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, admin.getId())
.set(AdminEntity::getFailedAttempts, 0)
.set(AdminEntity::getLockedUntil, null)
.set(AdminEntity::getLastLoginAt, loginAt)
.set(AdminEntity::getLastLoginIp, ip)
.set(AdminEntity::getTotpBound, 1)
.set(AdminEntity::getVersionNo, admin.getVersionNo() == null ? 1 : admin.getVersionNo() + 1));
admin.setFailedAttempts(0);
admin.setLockedUntil(null);
admin.setLastLoginAt(loginAt);
admin.setLastLoginIp(ip);
admin.setTotpBound(1);
String token = HashUtils.randomBase64Url(32);
sessionService.create(admin, token, ip, ua);
auditService.record("ADMIN", admin.getId(), admin.getUsername(), "LOGIN", "登录",
"ADMIN", admin.getId(), null, null, ip, ua);
return new LoginResponse(token, AdminInfoResponse.from(admin), PermissionRegistry.permissionsOf(admin.getRole()));
}
public ProfileResponse profile(AdminEntity admin) {
return new ProfileResponse(AdminInfoResponse.from(admin), PermissionRegistry.permissionsOf(admin.getRole()));
}
public void logout(AdminEntity admin, String token, HttpServletRequest httpRequest) {
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
sessionService.revokeByToken(token);
auditService.record("ADMIN", admin.getId(), admin.getUsername(), "LOGOUT", "登出",
"ADMIN", admin.getId(), null, null, ip, ua);
}
public void changePassword(AdminEntity admin, ChangePasswordRequest request, String token,
HttpServletRequest httpRequest) {
String ip = RequestUtils.clientIp(httpRequest, trustProxy);
String ua = RequestUtils.userAgent(httpRequest);
if (!passwordEncoder.matches(request.getOldPassword(), admin.getPasswordHash())) {
auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(),
"PASSWORD_CHANGE", "修改密码", "ADMIN", admin.getId(), null, null, ip, ua);
throw new BizException(ErrorCode.OLD_PASSWORD_MISMATCH);
}
if (!PasswordUtils.isStrong(request.getNewPassword())) {
throw new BizException(ErrorCode.PASSWORD_WEAK);
}
passwordHistoryService.validateNotReused(admin.getId(), admin.getPasswordHash(), request.getNewPassword());
String newHash = passwordEncoder.encode(request.getNewPassword());
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, admin.getId())
.set(AdminEntity::getPasswordHash, newHash)
.set(AdminEntity::getMustChangePassword, 0)
.set(AdminEntity::getPasswordUpdatedAt, LocalDateTime.now().withNano(0))
.set(AdminEntity::getFailedAttempts, 0)
.set(AdminEntity::getLockedUntil, null)
.set(AdminEntity::getVersionNo, admin.getVersionNo() == null ? 1 : admin.getVersionNo() + 1));
passwordHistoryService.record(admin.getId(), admin.getPasswordHash());
SessionService.SessionContext current = sessionService.validate(token);
sessionService.revokeOthers(admin.getId(), current.session().getId());
Map<String, Object> before = new LinkedHashMap<>();
before.put("mustChangePassword", admin.getMustChangePassword());
Map<String, Object> after = new LinkedHashMap<>();
after.put("mustChangePassword", 0);
auditService.record("ADMIN", admin.getId(), admin.getUsername(), "PASSWORD_CHANGE", "修改密码",
"ADMIN", admin.getId(), before, after, ip, ua);
}
private void failAndThrow(AdminEntity admin, String ip, String ua, ErrorCode errorCode) {
int attempts = (admin.getFailedAttempts() == null ? 0 : admin.getFailedAttempts()) + 1;
LocalDateTime lockedUntil = attempts >= lockThreshold
? LocalDateTime.now().withNano(0).plusMinutes(lockMinutes)
: null;
adminMapper.update(null, new LambdaUpdateWrapper<AdminEntity>()
.eq(AdminEntity::getId, admin.getId())
.set(AdminEntity::getFailedAttempts, attempts)
.set(AdminEntity::getLockedUntil, lockedUntil));
auditLoginFailure(admin, admin.getUsername(), ip, ua, attempts, lockedUntil);
if (lockedUntil != null) {
throw new BizException(ErrorCode.ACCOUNT_LOCKED, "账号已锁定,请 " + lockMinutes + " 分钟后重试");
}
throw new BizException(errorCode);
}
private void auditLoginFailure(AdminEntity admin, String username, String ip, String ua,
Integer attempts, LocalDateTime lockedUntil) {
Map<String, Object> after = new LinkedHashMap<>();
after.put("failedAttempts", attempts == null ? 0 : attempts);
after.put("lockedUntil", lockedUntil == null ? "" : lockedUntil.toString());
auditService.recordFailure("ADMIN", admin == null ? null : admin.getId(), username,
"LOGIN", "登录", "ADMIN", admin == null ? null : admin.getId(), null, after, ip, ua);
}
private String safeDecrypt(String value) {
try {
return cryptoService.decrypt(value);
} catch (Exception ex) {
return null;
}
}
}
@@ -0,0 +1,47 @@
package com.gas.fin.auth.service;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
/**
* 登录限流:用户名 5 次/5 分钟,IP 20 次/5 分钟。
*/
@Service
public class LoginRateLimiter {
private static final Logger log = LoggerFactory.getLogger(LoginRateLimiter.class);
private static final int WINDOW_SECONDS = 300;
private final StringRedisTemplate redisTemplate;
public LoginRateLimiter(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void check(String username, String ip) {
checkKey("rate:login:user:" + username, 5);
checkKey("rate:login:ip:" + ip, 20);
}
private void checkKey(String key, int limit) {
try {
Long count = redisTemplate.opsForValue().increment(key);
if (count != null && count == 1L) {
redisTemplate.expire(key, Duration.ofSeconds(WINDOW_SECONDS));
}
if (count != null && count > limit) {
throw new BizException(ErrorCode.TOO_MANY_REQUESTS, "操作过于频繁,请稍后再试");
}
} catch (BizException ex) {
throw ex;
} catch (Exception ex) {
log.warn("登录限流不可用,放行本次请求 key={}", key, ex);
}
}
}
@@ -0,0 +1,67 @@
package com.gas.fin.auth.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gas.fin.admin.entity.AdminPasswordHistoryEntity;
import com.gas.fin.admin.mapper.AdminPasswordHistoryMapper;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/**
* 密码历史:不得等于当前密码,不得命中最近 N 次历史。
*/
@Service
public class PasswordHistoryService {
private final AdminPasswordHistoryMapper historyMapper;
private final PasswordEncoder passwordEncoder;
private final int historySize;
public PasswordHistoryService(AdminPasswordHistoryMapper historyMapper,
PasswordEncoder passwordEncoder,
@Value("${fin.auth.password-history-size:3}") int historySize) {
this.historyMapper = historyMapper;
this.passwordEncoder = passwordEncoder;
this.historySize = historySize;
}
public void validateNotReused(Long adminId, String currentHash, String newPassword) {
if (passwordEncoder.matches(newPassword, currentHash)) {
throw new BizException(ErrorCode.PASSWORD_REUSED);
}
for (AdminPasswordHistoryEntity history : recent(adminId)) {
if (passwordEncoder.matches(newPassword, history.getPasswordHash())) {
throw new BizException(ErrorCode.PASSWORD_REUSED);
}
}
}
public void record(Long adminId, String oldHash) {
AdminPasswordHistoryEntity entity = new AdminPasswordHistoryEntity();
entity.setAdminId(adminId);
entity.setPasswordHash(oldHash);
entity.setCreateTime(LocalDateTime.now().withNano(0));
historyMapper.insert(entity);
List<AdminPasswordHistoryEntity> recent = recent(adminId);
if (recent.size() > historySize) {
List<Long> expireIds = recent.subList(historySize, recent.size()).stream()
.map(AdminPasswordHistoryEntity::getId)
.toList();
historyMapper.deleteBatchIds(expireIds);
}
}
private List<AdminPasswordHistoryEntity> recent(Long adminId) {
return historyMapper.selectList(new LambdaQueryWrapper<AdminPasswordHistoryEntity>()
.eq(AdminPasswordHistoryEntity::getAdminId, adminId)
.orderByDesc(AdminPasswordHistoryEntity::getCreateTime)
.orderByDesc(AdminPasswordHistoryEntity::getId)
.last("LIMIT 100"));
}
}
@@ -0,0 +1,124 @@
package com.gas.fin.auth.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.admin.entity.AdminSessionEntity;
import com.gas.fin.admin.mapper.AdminMapper;
import com.gas.fin.admin.mapper.AdminSessionMapper;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.util.HashUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
/**
* 管理员会话:30 分钟空闲滑动 + 8 小时绝对上限,DB 为权威,Redis 不参与会话判定。
*/
@Service
public class SessionService {
private final AdminSessionMapper sessionMapper;
private final AdminMapper adminMapper;
private final int idleMinutes;
private final int absoluteHours;
public SessionService(AdminSessionMapper sessionMapper,
AdminMapper adminMapper,
@Value("${fin.auth.idle-minutes:30}") int idleMinutes,
@Value("${fin.auth.absolute-hours:8}") int absoluteHours) {
this.sessionMapper = sessionMapper;
this.adminMapper = adminMapper;
this.idleMinutes = idleMinutes;
this.absoluteHours = absoluteHours;
}
public record SessionContext(AdminEntity admin, AdminSessionEntity session) {
}
public AdminSessionEntity create(AdminEntity admin, String token, String ip, String ua) {
LocalDateTime now = LocalDateTime.now().withNano(0);
AdminSessionEntity session = new AdminSessionEntity();
session.setAdminId(admin.getId());
session.setTokenHash(HashUtils.sha256Hex(token));
session.setIssuedIp(ip);
session.setUserAgent(ua);
session.setLastActiveAt(now);
session.setIdleExpireAt(now.plusMinutes(idleMinutes));
session.setAbsoluteExpireAt(now.plusHours(absoluteHours));
session.setCreateTime(now);
sessionMapper.insert(session);
return session;
}
public SessionContext validate(String token) {
if (token == null || token.isBlank()) {
throw new BizException(ErrorCode.UNAUTHORIZED);
}
String tokenHash = HashUtils.sha256Hex(token);
AdminSessionEntity session = sessionMapper.selectOne(new LambdaQueryWrapper<AdminSessionEntity>()
.eq(AdminSessionEntity::getTokenHash, tokenHash)
.last("LIMIT 1"));
if (session == null || session.getRevokedAt() != null) {
throw new BizException(ErrorCode.UNAUTHORIZED);
}
LocalDateTime now = LocalDateTime.now();
if (!now.isBefore(session.getAbsoluteExpireAt()) || !now.isBefore(session.getIdleExpireAt())) {
revokeSession(session.getId());
throw new BizException(ErrorCode.UNAUTHORIZED);
}
AdminEntity admin = adminMapper.selectById(session.getAdminId());
if (admin == null || !Integer.valueOf(1).equals(admin.getIsActive())) {
revokeSession(session.getId());
throw new BizException(ErrorCode.UNAUTHORIZED);
}
LocalDateTime nowSecond = now.withNano(0);
if (session.getLastActiveAt() == null || session.getLastActiveAt().plusSeconds(60).isBefore(nowSecond)) {
sessionMapper.update(null, new LambdaUpdateWrapper<AdminSessionEntity>()
.eq(AdminSessionEntity::getId, session.getId())
.set(AdminSessionEntity::getLastActiveAt, nowSecond)
.set(AdminSessionEntity::getIdleExpireAt, nowSecond.plusMinutes(idleMinutes)));
session.setLastActiveAt(nowSecond);
session.setIdleExpireAt(nowSecond.plusMinutes(idleMinutes));
}
return new SessionContext(admin, session);
}
public void revokeByToken(String token) {
if (token == null || token.isBlank()) {
return;
}
sessionMapper.update(null, new LambdaUpdateWrapper<AdminSessionEntity>()
.eq(AdminSessionEntity::getTokenHash, HashUtils.sha256Hex(token))
.isNull(AdminSessionEntity::getRevokedAt)
.set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0)));
}
public void revokeAll(Long adminId) {
sessionMapper.update(null, new LambdaUpdateWrapper<AdminSessionEntity>()
.eq(AdminSessionEntity::getAdminId, adminId)
.isNull(AdminSessionEntity::getRevokedAt)
.set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0)));
}
public void revokeOthers(Long adminId, Long keepSessionId) {
LambdaUpdateWrapper<AdminSessionEntity> wrapper = new LambdaUpdateWrapper<AdminSessionEntity>()
.eq(AdminSessionEntity::getAdminId, adminId)
.isNull(AdminSessionEntity::getRevokedAt)
.set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0));
if (keepSessionId != null) {
wrapper.ne(AdminSessionEntity::getId, keepSessionId);
}
sessionMapper.update(null, wrapper);
}
private void revokeSession(Long sessionId) {
sessionMapper.update(null, new LambdaUpdateWrapper<AdminSessionEntity>()
.eq(AdminSessionEntity::getId, sessionId)
.isNull(AdminSessionEntity::getRevokedAt)
.set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0)));
}
}
@@ -0,0 +1,20 @@
package com.gas.fin.common.api;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.List;
/**
* 统一分页响应,字段名与前端 PageResult 一致。
*/
@JsonPropertyOrder({"records", "total", "page", "pageSize"})
public record PageResult<T>(List<T> records, long total, long page, long pageSize) {
public static <T> PageResult<T> of(List<T> records, long total, long page, long pageSize) {
return new PageResult<>(records, total, page, pageSize);
}
public static <T> PageResult<T> empty(long page, long pageSize) {
return new PageResult<>(List.of(), 0, page, pageSize);
}
}
@@ -0,0 +1,25 @@
package com.gas.fin.common.api;
import com.gas.fin.common.web.TraceId;
/**
* 统一响应体:HTTP 固定 200,业务结果由 code 表达。
*/
public record R<T>(int code, String message, T data, String traceId) {
public static <T> R<T> ok(T data) {
return new R<>(0, "success", data, TraceId.current());
}
public static <T> R<T> ok() {
return ok(null);
}
public static <T> R<T> fail(int code, String message) {
return new R<>(code, message, null, TraceId.current());
}
public static <T> R<T> fail(int code, String message, T data) {
return new R<>(code, message, data, TraceId.current());
}
}
@@ -0,0 +1,105 @@
package com.gas.fin.common.crypto;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.SecureRandom;
import java.util.Base64;
/**
* AES-256-GCM 加解密:用于 TOTP secret、webhook secret 等需要还原原文的字段。
* 主密钥优先取 FIN_SECRET_ENC_KEY(32 字节 Base64);本地开发缺省时生成到 .runtime/secret-enc.key。
*/
@Component
public class CryptoService {
private static final Logger log = LoggerFactory.getLogger(CryptoService.class);
private static final SecureRandom RANDOM = new SecureRandom();
private static final int IV_LENGTH = 12;
private static final int TAG_BITS = 128;
@Value("${fin.secret-enc-key:}")
private String configuredKey;
@Value("${fin.runtime-dir:./.runtime}")
private String runtimeDir;
private SecretKeySpec key;
@PostConstruct
public void init() {
byte[] keyBytes;
if (configuredKey != null && !configuredKey.isBlank()) {
keyBytes = Base64.getDecoder().decode(configuredKey.trim());
} else {
keyBytes = loadOrCreateLocalKey();
}
if (keyBytes.length != 32) {
throw new IllegalStateException("FIN_SECRET_ENC_KEY must be 32 bytes (Base64)");
}
this.key = new SecretKeySpec(keyBytes, "AES");
}
public String encrypt(String plaintext) {
if (plaintext == null) {
return null;
}
try {
byte[] iv = new byte[IV_LENGTH];
RANDOM.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
byte[] cipherText = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
byte[] combined = new byte[iv.length + cipherText.length];
System.arraycopy(iv, 0, combined, 0, iv.length);
System.arraycopy(cipherText, 0, combined, iv.length, cipherText.length);
return Base64.getEncoder().encodeToString(combined);
} catch (Exception ex) {
throw new IllegalStateException("encrypt failed", ex);
}
}
public String decrypt(String cipherText) {
if (cipherText == null || cipherText.isBlank()) {
return null;
}
try {
byte[] combined = Base64.getDecoder().decode(cipherText);
byte[] iv = new byte[IV_LENGTH];
System.arraycopy(combined, 0, iv, 0, IV_LENGTH);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
byte[] plain = cipher.doFinal(combined, IV_LENGTH, combined.length - IV_LENGTH);
return new String(plain, StandardCharsets.UTF_8);
} catch (Exception ex) {
throw new IllegalStateException("decrypt failed", ex);
}
}
private byte[] loadOrCreateLocalKey() {
try {
Path dir = Path.of(runtimeDir);
Path file = dir.resolve("secret-enc.key");
if (Files.exists(file)) {
return Base64.getDecoder().decode(Files.readString(file).trim());
}
Files.createDirectories(dir);
byte[] bytes = new byte[32];
RANDOM.nextBytes(bytes);
Files.writeString(file, Base64.getEncoder().encodeToString(bytes));
log.warn("FIN_SECRET_ENC_KEY 未配置,已生成本地开发密钥: {}", file.toAbsolutePath());
return bytes;
} catch (Exception ex) {
throw new IllegalStateException("cannot initialize local encryption key", ex);
}
}
}
@@ -0,0 +1,7 @@
package com.gas.fin.common.dto;
/**
* 通用启停请求:{@code enabled} 1 启用 / 0 停用。
*/
public record ToggleRequest(Integer enabled) {
}
@@ -0,0 +1,44 @@
package com.gas.fin.common.error;
/**
* 可预期的业务异常。HTTP 状态仍为 200,业务错误通过 code 表达。
*/
public class BizException extends RuntimeException {
private final int code;
private final transient Object data;
public BizException(int code, String message) {
this(code, message, null);
}
public BizException(int code, String message, Object data) {
super(message);
this.code = code;
this.data = data;
}
public BizException(ErrorCode errorCode) {
this(errorCode.code(), errorCode.message());
}
public BizException(ErrorCode errorCode, String message) {
this(errorCode.code(), message);
}
public int getCode() {
return code;
}
public Object getData() {
return data;
}
public static BizException of(ErrorCode errorCode) {
return new BizException(errorCode);
}
public static BizException of(ErrorCode errorCode, String message) {
return new BizException(errorCode, message);
}
}
@@ -0,0 +1,65 @@
package com.gas.fin.common.error;
/**
* 业务错误码,与需求文档 §9.2 及前端 KNOWN_MESSAGES 保持一致。
*/
public enum ErrorCode {
SUCCESS(0, "success"),
BAD_REQUEST(400, "请求格式错误"),
UNAUTHORIZED(4010, "登录状态已失效,请重新登录"),
LOGIN_FAILED(4011, "用户名或密码错误"),
ACCOUNT_DISABLED(4012, "账号已停用"),
OLD_PASSWORD_MISMATCH(4013, "原密码不正确"),
PASSWORD_WEAK(4014, "新密码强度不足"),
PASSWORD_REUSED(4015, "新密码不得与最近 3 次密码重复"),
MUST_CHANGE_PASSWORD(4016, "请先修改初始密码"),
ACCOUNT_LOCKED(4021, "账号已锁定,请稍后重试"),
TOTP_FAILED(4022, "动态口令校验失败"),
FORBIDDEN(403, "当前账号无权执行该操作"),
NOT_FOUND(404, "资源不存在"),
IDEMPOTENT_CONFLICT(4091, "重复提交已被拦截,已返回首次结果"),
CONCURRENT_CONFLICT(4092, "并发操作冲突,请稍后重试"),
STATUS_CONFLICT(4093, "单据状态已变更,请刷新后重试"),
SECOND_APPROVER_REQUIRED(4094, "该笔金额需要第二复核人"),
INVALID_APPROVER(4095, "复核人不符合要求"),
ADMIN_CONSTRAINT(4096, "管理约束冲突"),
PROTECTED_CONFIG(4097, "受保护参数禁止修改"),
DUPLICATE_VOUCHER(4098, "该银行凭证号已被其他订单使用,请核对后重新录入"),
VALIDATION_FAILED(422, "提交内容不符合规范,请检查后重试"),
DUPLICATE_KEY(4221, "唯一键冲突"),
TOO_MANY_REQUESTS(429, "操作过于频繁,请稍后再试"),
BIZ_OBJECT_UNAVAILABLE(4001, "业务对象不可用"),
APP_CREDENTIAL_INVALID(4003, "应用凭证无效"),
INSUFFICIENT_BALANCE(6001, "账户余额不足,无法完成扣费"),
EXCEED_CHARGE_LIMIT(6002, "超出单次扣费上限,已被拒绝"),
INVALID_POINTS(6003, "点数必须为正整数"),
REFUND_EXCEEDED(6004, "退款金额超出可退上限"),
RESERVED_6005(6005, "预留错误码"),
REFUND_BALANCE_INSUFFICIENT(6006, "退款扣回点数超出账户余额"),
TICKET_INVALID(7001, "凭证无效、已过期或已被使用"),
INTERNAL_ERROR(500, "服务器内部错误");
private final int code;
private final String message;
ErrorCode(int code, String message) {
this.code = code;
this.message = message;
}
public int code() {
return code;
}
public String message() {
return message;
}
}
@@ -0,0 +1,62 @@
package com.gas.fin.common.id;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 53 位 ID 生成器:前端 JS number 安全整数范围内(<= 2^53-1)。
* 结构:41 位毫秒时间 + 6 位机器号 + 6 位序列。
*/
@Component
public class FinIdGenerator implements IdentifierGenerator {
private static final long EPOCH = LocalDate.of(2026, 1, 1)
.atStartOfDay(ZoneId.of("Asia/Shanghai"))
.toInstant()
.toEpochMilli();
private static final long SEQUENCE_MASK = 0x3F;
private final int workerId;
private final AtomicInteger sequence = new AtomicInteger(0);
private volatile long lastTimestamp = -1L;
public FinIdGenerator(@Value("${fin.worker-id:0}") int workerId) {
this.workerId = workerId & 0x3F;
}
@Override
public synchronized Number nextId(Object entity) {
long timestamp = System.currentTimeMillis() - EPOCH;
if (timestamp < 0) {
timestamp = 0;
}
if (timestamp == lastTimestamp) {
int next = sequence.incrementAndGet() & (int) SEQUENCE_MASK;
if (next == 0) {
timestamp = waitNextMillis(timestamp);
lastTimestamp = timestamp;
}
} else {
sequence.set(0);
lastTimestamp = timestamp;
}
return (timestamp << 12) | ((long) workerId << 6) | (sequence.get() & SEQUENCE_MASK);
}
public long nextLongId() {
return nextId(null).longValue();
}
private long waitNextMillis(long current) {
long timestamp = current;
while (timestamp <= current) {
timestamp = System.currentTimeMillis() - EPOCH;
}
return timestamp;
}
}
@@ -0,0 +1,37 @@
package com.gas.fin.common.security;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.audit.service.AuditService;
import com.gas.fin.common.web.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 管理端操作审计快捷入口:统一取客户端 IP / UA,避免各业务重复拼装。
*/
@Component
public class AdminAuditor {
private final AuditService auditService;
private final boolean trustProxy;
public AdminAuditor(AuditService auditService, @Value("${fin.trust-proxy:true}") boolean trustProxy) {
this.auditService = auditService;
this.trustProxy = trustProxy;
}
public void success(AdminEntity admin, String action, String actionLabel, String targetType, Long targetId,
Object before, Object after, HttpServletRequest request) {
auditService.record("ADMIN", admin.getId(), admin.getUsername(), action, actionLabel,
targetType, targetId, before, after,
RequestUtils.clientIp(request, trustProxy), RequestUtils.userAgent(request));
}
public void failure(AdminEntity admin, String action, String actionLabel, String targetType, Long targetId,
Object before, Object after, HttpServletRequest request) {
auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(), action, actionLabel,
targetType, targetId, before, after,
RequestUtils.clientIp(request, trustProxy), RequestUtils.userAgent(request));
}
}
@@ -0,0 +1,94 @@
package com.gas.fin.common.security;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.audit.service.AuditService;
import com.gas.fin.auth.service.SessionService;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.web.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.UrlPathHelper;
import java.util.Arrays;
import java.util.Set;
/**
* 管理端统一认证 + 强制改密 + 权限码校验。
* 所有 /api/admin/** 接口(登录除外)必须经过本拦截器。
*/
@Component
public class AdminAuthInterceptor implements HandlerInterceptor {
private static final Set<String> MUST_CHANGE_ALLOWED = Set.of(
"/api/admin/profile",
"/api/admin/password/change",
"/api/admin/logout"
);
private final SessionService sessionService;
private final AuditService auditService;
public AdminAuthInterceptor(SessionService sessionService, AuditService auditService) {
this.sessionService = sessionService;
this.auditService = auditService;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod handlerMethod)) {
return true;
}
String token = RequestUtils.bearerToken(request);
SessionService.SessionContext context = sessionService.validate(token);
AdminEntity admin = context.admin();
AuthContext.set(admin);
try {
String path = UrlPathHelper.defaultInstance.getPathWithinApplication(request);
if (Integer.valueOf(1).equals(admin.getMustChangePassword()) && !MUST_CHANGE_ALLOWED.contains(path)) {
throw new BizException(ErrorCode.MUST_CHANGE_PASSWORD);
}
RequirePermission permission = findPermission(handlerMethod);
if (permission == null) {
throw new BizException(ErrorCode.FORBIDDEN, "接口未声明权限码");
}
boolean allowed = permission.anyOf()
? Arrays.stream(permission.value())
.anyMatch(item -> PermissionRegistry.has(admin.getRole(), item))
: Arrays.stream(permission.value())
.allMatch(item -> PermissionRegistry.has(admin.getRole(), item));
if (!allowed) {
auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(),
"PERMISSION_DENIED", "权限拒绝", "API", null,
null, java.util.Map.of("path", path), request.getRemoteAddr(), RequestUtils.userAgent(request));
throw new BizException(ErrorCode.FORBIDDEN);
}
return true;
} catch (RuntimeException ex) {
AuthContext.clear();
throw ex;
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
AuthContext.clear();
}
private RequirePermission findPermission(HandlerMethod handlerMethod) {
RequirePermission annotation = AnnotatedElementUtils.findMergedAnnotation(
handlerMethod.getMethod(), RequirePermission.class);
if (annotation != null) {
return annotation;
}
return AnnotatedElementUtils.findMergedAnnotation(
handlerMethod.getBeanType(), RequirePermission.class);
}
}
@@ -0,0 +1,35 @@
package com.gas.fin.common.security;
import com.gas.fin.admin.entity.AdminEntity;
/**
* 当前请求的登录管理员上下文,由认证拦截器写入并在请求结束时清理。
*/
public final class AuthContext {
private static final ThreadLocal<AdminEntity> HOLDER = new ThreadLocal<>();
private AuthContext() {
}
public static void set(AdminEntity admin) {
HOLDER.set(admin);
}
public static AdminEntity get() {
return HOLDER.get();
}
public static AdminEntity require() {
AdminEntity admin = HOLDER.get();
if (admin == null) {
throw new com.gas.fin.common.error.BizException(
com.gas.fin.common.error.ErrorCode.UNAUTHORIZED);
}
return admin;
}
public static void clear() {
HOLDER.remove();
}
}
@@ -0,0 +1,52 @@
package com.gas.fin.common.security;
import java.util.List;
import java.util.Map;
/**
* 15 个权限码与角色映射。
* 与前端 finance-web/src/constants/index.ts 的 PERM 对齐,并保留需求文档的职责分离:
* SUPER_ADMIN 不拥有确认到账 / 发起退款权限。
*/
public final class PermissionRegistry {
public static final String VIEW = "fin:view";
public static final String EXPORT = "fin:export";
public static final String APP_MANAGE = "fin:app:manage";
public static final String PRICING_EDIT = "fin:pricing:edit";
public static final String VIP_MANAGE = "fin:vip:manage";
public static final String ADMIN_MANAGE = "fin:admin:manage";
public static final String CONFIG_EDIT = "fin:config:edit";
public static final String AUDIT_VIEW = "fin:audit:view";
public static final String WEBHOOK_MANAGE = "fin:webhook:manage";
public static final String ACCOUNT_ADJUST = "fin:account:adjust";
public static final String RECHARGE_CONFIRM = "fin:recharge:confirm";
public static final String REFUND_CREATE = "fin:refund:create";
public static final String REFUND_REVIEW = "fin:refund:review";
public static final String ORDER_CANCEL = "fin:order:cancel";
public static final String RECONCILE_RUN = "fin:reconcile:run";
private static final Map<String, List<String>> ROLE_PERMISSIONS = Map.of(
"SUPER_ADMIN", List.of(
VIEW, EXPORT, APP_MANAGE, PRICING_EDIT, VIP_MANAGE, ADMIN_MANAGE,
CONFIG_EDIT, AUDIT_VIEW, WEBHOOK_MANAGE, ACCOUNT_ADJUST,
REFUND_REVIEW, ORDER_CANCEL, RECONCILE_RUN
),
"FINANCE", List.of(
VIEW, EXPORT, RECHARGE_CONFIRM, REFUND_CREATE, REFUND_REVIEW,
ORDER_CANCEL, RECONCILE_RUN
),
"AUDITOR", List.of(VIEW, EXPORT, AUDIT_VIEW)
);
private PermissionRegistry() {
}
public static List<String> permissionsOf(String role) {
return ROLE_PERMISSIONS.getOrDefault(role, List.of());
}
public static boolean has(String role, String permission) {
return permissionsOf(role).contains(permission);
}
}
@@ -0,0 +1,21 @@
package com.gas.fin.common.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 接口权限码声明。管理端接口必须声明,服务端二次校验。
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequirePermission {
String[] value();
/**
* true 表示满足任意一个权限码即可访问;默认要求全部满足。
*/
boolean anyOf() default false;
}
@@ -0,0 +1,40 @@
package com.gas.fin.common.security;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.common.crypto.CryptoService;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.totp.TotpService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
/**
* 高危操作动态口令校验:校验失败时写失败审计,再抛出 4022。
*/
@Component
public class TotpVerifier {
private final CryptoService cryptoService;
private final TotpService totpService;
private final AdminAuditor adminAuditor;
public TotpVerifier(CryptoService cryptoService, TotpService totpService, AdminAuditor adminAuditor) {
this.cryptoService = cryptoService;
this.totpService = totpService;
this.adminAuditor = adminAuditor;
}
public void verify(AdminEntity admin, String code, String action, String actionLabel,
HttpServletRequest request) {
String secret;
try {
secret = cryptoService.decrypt(admin.getTotpSecretEnc());
} catch (Exception ex) {
secret = null;
}
if (totpService.verify(secret, code, admin.getId()) != TotpService.Result.OK) {
adminAuditor.failure(admin, action, actionLabel, "ADMIN", admin.getId(), null, null, request);
throw new BizException(ErrorCode.TOTP_FAILED);
}
}
}
@@ -0,0 +1,156 @@
package com.gas.fin.common.totp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
* RFC 6238 TOTP:HmacSHA1 / 6 位 / 30 秒步长 / 允许 ±1 步;同一管理员同一验证码 90 秒内只能用一次。
*/
@Service
public class TotpService {
private static final Logger log = LoggerFactory.getLogger(TotpService.class);
private static final String BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private static final SecureRandom RANDOM = new SecureRandom();
private static final long STEP_SECONDS = 30L;
private final StringRedisTemplate redisTemplate;
public TotpService(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public enum Result {
OK,
FORMAT_INVALID,
FAILED,
REPLAY
}
public String generateSecret() {
byte[] bytes = new byte[20];
RANDOM.nextBytes(bytes);
return base32Encode(bytes);
}
public Result verify(String secretBase32, String code, Long adminId) {
if (code == null || !code.matches("^\\d{6}$")) {
return Result.FORMAT_INVALID;
}
if (secretBase32 == null || secretBase32.isBlank()) {
return Result.FAILED;
}
byte[] key;
try {
key = base32Decode(secretBase32);
} catch (IllegalArgumentException ex) {
return Result.FAILED;
}
long counter = System.currentTimeMillis() / 1000L / STEP_SECONDS;
boolean matched = false;
for (long offset = -1; offset <= 1; offset++) {
String candidate = generateCode(key, counter + offset);
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.UTF_8), code.getBytes(StandardCharsets.UTF_8))) {
matched = true;
break;
}
}
if (!matched) {
return Result.FAILED;
}
String replayKey = "totp:used:" + adminId + ":" + code;
try {
Boolean firstUse = redisTemplate.opsForValue().setIfAbsent(replayKey, "1", Duration.ofSeconds(90));
if (!Boolean.TRUE.equals(firstUse)) {
return Result.REPLAY;
}
} catch (Exception ex) {
log.error("TOTP 防重放校验失败 adminId={}", adminId, ex);
return Result.FAILED;
}
return Result.OK;
}
private String generateCode(byte[] key, long counter) {
try {
byte[] data = ByteBuffer.allocate(8).putLong(counter).array();
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(key, "HmacSHA1"));
byte[] hash = mac.doFinal(data);
int offset = hash[hash.length - 1] & 0x0F;
int binary = ((hash[offset] & 0x7F) << 24)
| ((hash[offset + 1] & 0xFF) << 16)
| ((hash[offset + 2] & 0xFF) << 8)
| (hash[offset + 3] & 0xFF);
int otp = binary % 1_000_000;
return String.format(Locale.ROOT, "%06d", otp);
} catch (Exception ex) {
throw new IllegalStateException("TOTP generate failed", ex);
}
}
private static String base32Encode(byte[] data) {
StringBuilder builder = new StringBuilder();
int buffer = 0;
int bits = 0;
for (byte b : data) {
buffer = (buffer << 8) | (b & 0xFF);
bits += 8;
while (bits >= 5) {
builder.append(BASE32_ALPHABET.charAt((buffer >> (bits - 5)) & 0x1F));
bits -= 5;
}
}
if (bits > 0) {
builder.append(BASE32_ALPHABET.charAt((buffer << (5 - bits)) & 0x1F));
}
return builder.toString();
}
private static byte[] base32Decode(String input) {
String normalized = input.replace("=", "").replace(" ", "").toUpperCase(Locale.ROOT);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int buffer = 0;
int bits = 0;
for (char c : normalized.toCharArray()) {
int value = BASE32_ALPHABET.indexOf(c);
if (value < 0) {
throw new IllegalArgumentException("invalid base32");
}
buffer = (buffer << 5) | value;
bits += 5;
if (bits >= 8) {
out.write((buffer >> (bits - 8)) & 0xFF);
bits -= 8;
}
}
return out.toByteArray();
}
public static void main(String[] args) {
// 便于本地生成测试 secret 与当前验证码
TotpService service = new TotpService(null);
String secret = args.length > 0 ? args[0] : service.generateSecret();
System.out.println("secret=" + secret);
if (args.length > 1) {
byte[] key = base32Decode(secret);
long counter = System.currentTimeMillis() / 1000L / STEP_SECONDS;
System.out.println("code=" + service.generateCode(key, counter));
}
}
}
@@ -0,0 +1,65 @@
package com.gas.fin.common.util;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
public final class HashUtils {
private static final SecureRandom RANDOM = new SecureRandom();
private static final char[] BASE64_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray();
private HashUtils() {
}
public static String sha256Hex(String value) {
return sha256Hex(value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8));
}
public static String sha256Hex(byte[] value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = digest.digest(value);
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
builder.append(Character.forDigit((b >> 4) & 0xF, 16));
builder.append(Character.forDigit(b & 0xF, 16));
}
return builder.toString();
} catch (Exception ex) {
throw new IllegalStateException("SHA-256 unavailable", ex);
}
}
public static byte[] randomBytes(int length) {
byte[] bytes = new byte[length];
RANDOM.nextBytes(bytes);
return bytes;
}
public static String randomBase64Url(int length) {
byte[] bytes = randomBytes(length);
StringBuilder builder = new StringBuilder((length * 4 + 2) / 3);
int buffer = 0;
int bits = 0;
for (byte b : bytes) {
buffer = (buffer << 8) | (b & 0xFF);
bits += 8;
while (bits >= 6) {
builder.append(BASE64_URL[(buffer >> (bits - 6)) & 0x3F]);
bits -= 6;
}
}
if (bits > 0) {
builder.append(BASE64_URL[(buffer << (6 - bits)) & 0x3F]);
}
return builder.toString();
}
public static boolean constantTimeEquals(String left, String right) {
if (left == null || right == null) {
return false;
}
return MessageDigest.isEqual(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,47 @@
package com.gas.fin.common.util;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class PasswordUtils {
private static final SecureRandom RANDOM = new SecureRandom();
private static final String LOWER = "abcdefghijkmnpqrstuvwxyz";
private static final String UPPER = "ABCDEFGHJKLMNPQRSTUVWXYZ";
private static final String DIGITS = "23456789";
private static final String SYMBOLS = "!@#$%^&*()-_=+";
private static final String ALL = LOWER + UPPER + DIGITS + SYMBOLS;
private PasswordUtils() {
}
public static boolean isStrong(String password) {
if (password == null) {
return false;
}
return password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^A-Za-z0-9])\\S{12,64}$")
&& password.matches("^[\\x21-\\x7e]+$");
}
public static String randomPassword(int length) {
int size = Math.max(length, 12);
List<Character> chars = new ArrayList<>(size);
chars.add(randomOf(LOWER));
chars.add(randomOf(UPPER));
chars.add(randomOf(DIGITS));
chars.add(randomOf(SYMBOLS));
for (int i = 4; i < size; i++) {
chars.add(randomOf(ALL));
}
Collections.shuffle(chars, RANDOM);
StringBuilder builder = new StringBuilder(size);
chars.forEach(builder::append);
return builder.toString();
}
private static char randomOf(String source) {
return source.charAt(RANDOM.nextInt(source.length()));
}
}
@@ -0,0 +1,85 @@
package com.gas.fin.common.web;
import com.gas.fin.common.api.R;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 全局异常出口:禁止把堆栈、SQL、内部地址返回给客户端。
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BizException.class)
public R<Object> handleBiz(BizException ex) {
return R.fail(ex.getCode(), ex.getMessage(), ex.getData());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public R<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
List<Map<String, String>> errors = new ArrayList<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.add(fieldError(error.getField(), error.getDefaultMessage()));
}
return R.fail(ErrorCode.VALIDATION_FAILED.code(), ErrorCode.VALIDATION_FAILED.message(), errors);
}
@ExceptionHandler(BindException.class)
public R<Object> handleBind(BindException ex) {
List<Map<String, String>> errors = new ArrayList<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.add(fieldError(error.getField(), error.getDefaultMessage()));
}
return R.fail(ErrorCode.VALIDATION_FAILED.code(), ErrorCode.VALIDATION_FAILED.message(), errors);
}
@ExceptionHandler(ConstraintViolationException.class)
public R<Object> handleConstraintViolation(ConstraintViolationException ex) {
List<Map<String, String>> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(fieldError(String.valueOf(violation.getPropertyPath()), violation.getMessage()));
}
return R.fail(ErrorCode.VALIDATION_FAILED.code(), ErrorCode.VALIDATION_FAILED.message(), errors);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public R<Object> handleUnreadable(HttpMessageNotReadableException ex) {
return R.fail(ErrorCode.BAD_REQUEST.code(), ErrorCode.BAD_REQUEST.message());
}
@ExceptionHandler(NoHandlerFoundException.class)
public R<Object> handleNoHandler(NoHandlerFoundException ex) {
return R.fail(ErrorCode.NOT_FOUND.code(), ErrorCode.NOT_FOUND.message());
}
@ExceptionHandler(Exception.class)
public R<Object> handleUnexpected(Exception ex) {
log.error("unexpected error traceId={}", TraceId.current(), ex);
return R.fail(ErrorCode.INTERNAL_ERROR.code(), ErrorCode.INTERNAL_ERROR.message());
}
private Map<String, String> fieldError(String field, String message) {
Map<String, String> item = new LinkedHashMap<>();
item.put("field", field);
item.put("message", message == null ? "参数不合法" : message);
return item;
}
}
@@ -0,0 +1,60 @@
package com.gas.fin.common.web;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
/**
* 列表类接口的公共查询参数处理:分页校验与日期区间解析。
*/
public final class QueryUtils {
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private QueryUtils() {
}
public static void checkPage(long page, long pageSize) {
if (page < 1 || pageSize < 1 || pageSize > 100) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "分页参数不合法");
}
}
public static LocalDateTime parseFrom(String value) {
if (value == null || value.isBlank()) {
return null;
}
String text = value.trim();
try {
if (text.length() == 10) {
return LocalDate.parse(text).atStartOfDay();
}
return LocalDateTime.parse(text, DATE_TIME);
} catch (DateTimeParseException ex) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss");
}
}
public static LocalDateTime parseTo(String value) {
if (value == null || value.isBlank()) {
return null;
}
String text = value.trim();
try {
if (text.length() == 10) {
return LocalDate.parse(text).atTime(23, 59, 59);
}
return LocalDateTime.parse(text, DATE_TIME);
} catch (DateTimeParseException ex) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss");
}
}
public static String text(String value) {
return value == null ? "" : value.trim();
}
}
@@ -0,0 +1,49 @@
package com.gas.fin.common.web;
import jakarta.servlet.http.HttpServletRequest;
public final class RequestUtils {
private RequestUtils() {
}
public static String clientIp(HttpServletRequest request, boolean trustProxy) {
String ip = null;
if (trustProxy) {
String forwarded = request.getHeader("X-Forwarded-For");
if (forwarded != null && !forwarded.isBlank()) {
String[] parts = forwarded.split(",");
ip = parts[parts.length - 1].trim();
}
}
if (ip == null || ip.isBlank()) {
ip = request.getRemoteAddr();
}
if (ip == null || ip.isBlank()) {
return "unknown";
}
ip = ip.replaceAll("[^0-9a-fA-F:.]", "");
return ip.length() > 45 ? ip.substring(0, 45) : ip;
}
public static String userAgent(HttpServletRequest request) {
String ua = request.getHeader("User-Agent");
if (ua == null) {
return "";
}
return ua.length() > 255 ? ua.substring(0, 255) : ua;
}
public static String bearerToken(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (authorization == null) {
return null;
}
String prefix = "Bearer ";
if (authorization.regionMatches(true, 0, prefix, 0, prefix.length())) {
String token = authorization.substring(prefix.length()).trim();
return token.isEmpty() ? null : token;
}
return null;
}
}
@@ -0,0 +1,29 @@
package com.gas.fin.common.web;
import org.slf4j.MDC;
import java.util.UUID;
/**
* TraceId 上下文:响应体与响应头使用同一个值,日志通过 MDC 串联。
*/
public final class TraceId {
public static final String MDC_KEY = "traceId";
public static final String HEADER = "X-Trace-Id";
private TraceId() {
}
public static String current() {
String value = MDC.get(MDC_KEY);
if (value != null && !value.isBlank()) {
return value;
}
return newTraceId();
}
public static String newTraceId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
}
}
@@ -0,0 +1,41 @@
package com.gas.fin.common.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.regex.Pattern;
/**
* 为每个请求生成 TraceId,写入 MDC 与响应头。上游传入的 X-Request-Id 仅在格式合法时复用。
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TraceIdFilter extends OncePerRequestFilter {
private static final Pattern SAFE_TRACE_ID = Pattern.compile("^[A-Za-z0-9-]{8,64}$");
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String incoming = request.getHeader("X-Request-Id");
String traceId = incoming != null && SAFE_TRACE_ID.matcher(incoming).matches()
? incoming
: TraceId.newTraceId();
MDC.put(TraceId.MDC_KEY, traceId);
response.setHeader(TraceId.HEADER, traceId);
try {
filterChain.doFilter(request, response);
} finally {
MDC.remove(TraceId.MDC_KEY);
}
}
}
@@ -0,0 +1,23 @@
package com.gas.fin.config;
import com.gas.fin.common.security.AdminAuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AuthWebConfig implements WebMvcConfigurer {
private final AdminAuthInterceptor adminAuthInterceptor;
public AuthWebConfig(AdminAuthInterceptor adminAuthInterceptor) {
this.adminAuthInterceptor = adminAuthInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(adminAuthInterceptor)
.addPathPatterns("/api/admin/**")
.excludePathPatterns("/api/admin/login");
}
}
@@ -0,0 +1,32 @@
package com.gas.fin.config;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfig {
public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER));
builder.serializerByType(LocalDate.class, new LocalDateSerializer(DATE_FORMATTER));
builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DATE_FORMATTER));
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
};
}
}
@@ -0,0 +1,22 @@
package com.gas.fin.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor pagination = new PaginationInnerInterceptor(DbType.MYSQL);
pagination.setMaxLimit(100L);
interceptor.addInnerInterceptor(pagination);
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
@@ -0,0 +1,15 @@
package com.gas.fin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityBeans {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
@@ -0,0 +1,33 @@
package com.gas.fin.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${fin.cors.allowed-origins:}")
private String allowedOrigins;
@Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.filter(value -> !value.isEmpty())
.toArray(String[]::new);
if (origins.length == 0) {
return;
}
registry.addMapping("/api/**")
.allowedOrigins(origins)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("X-Trace-Id")
.allowCredentials(false)
.maxAge(3600);
}
}
@@ -0,0 +1,43 @@
package com.gas.fin.dashboard.controller;
import com.gas.fin.common.api.R;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import com.gas.fin.dashboard.dto.AppDistributionResponse;
import com.gas.fin.dashboard.dto.DashboardSummaryResponse;
import com.gas.fin.dashboard.dto.TrendPointResponse;
import com.gas.fin.dashboard.service.DashboardService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/admin/dashboard")
public class DashboardController {
private final DashboardService dashboardService;
public DashboardController(DashboardService dashboardService) {
this.dashboardService = dashboardService;
}
@GetMapping("/summary")
@RequirePermission(PermissionRegistry.VIEW)
public R<DashboardSummaryResponse> summary() {
return R.ok(dashboardService.summary());
}
@GetMapping("/trend")
@RequirePermission(PermissionRegistry.VIEW)
public R<List<TrendPointResponse>> trend() {
return R.ok(dashboardService.trend());
}
@GetMapping("/distribution")
@RequirePermission(PermissionRegistry.VIEW)
public R<List<AppDistributionResponse>> distribution() {
return R.ok(dashboardService.distribution());
}
}
@@ -0,0 +1,4 @@
package com.gas.fin.dashboard.dto;
public record AppDistributionResponse(String appCode, String appName, long amountCent, long orderCount) {
}
@@ -0,0 +1,7 @@
package com.gas.fin.dashboard.dto;
public record DashboardSummaryResponse(long todayAmountCent, long todayOrderCount, long pendingOrderCount,
long pendingAmountCent, long todayConsumedPoints, long pendingRefundCount,
long totalBalancePoints, long deadWebhookCount, long diffReportCount,
long dualControlThresholdCent) {
}
@@ -0,0 +1,4 @@
package com.gas.fin.dashboard.dto;
public record TrendPointResponse(String date, long amountCent, long points, long orderCount) {
}
@@ -0,0 +1,152 @@
package com.gas.fin.dashboard.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gas.fin.account.entity.AccountEntity;
import com.gas.fin.account.mapper.AccountMapper;
import com.gas.fin.app.entity.AppEntity;
import com.gas.fin.app.mapper.AppMapper;
import com.gas.fin.dashboard.dto.AppDistributionResponse;
import com.gas.fin.dashboard.dto.DashboardSummaryResponse;
import com.gas.fin.dashboard.dto.TrendPointResponse;
import com.gas.fin.order.entity.CashLedgerEntity;
import com.gas.fin.order.entity.OrderEntity;
import com.gas.fin.order.mapper.CashLedgerMapper;
import com.gas.fin.order.mapper.OrderMapper;
import com.gas.fin.reconcile.entity.ReconcileReportEntity;
import com.gas.fin.reconcile.mapper.ReconcileReportMapper;
import com.gas.fin.refund.entity.RefundEntity;
import com.gas.fin.refund.mapper.RefundMapper;
import com.gas.fin.setting.service.ConfigService;
import com.gas.fin.transaction.entity.TransactionEntity;
import com.gas.fin.transaction.mapper.TransactionMapper;
import com.gas.fin.webhook.entity.WebhookDeliveryEntity;
import com.gas.fin.webhook.mapper.WebhookDeliveryMapper;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 首页看板:实时聚合口径见需求文档 §5.2。
*/
@Service
public class DashboardService {
private final OrderMapper orderMapper;
private final CashLedgerMapper cashLedgerMapper;
private final TransactionMapper transactionMapper;
private final AccountMapper accountMapper;
private final RefundMapper refundMapper;
private final WebhookDeliveryMapper webhookMapper;
private final ReconcileReportMapper reportMapper;
private final AppMapper appMapper;
private final ConfigService configService;
public DashboardService(OrderMapper orderMapper, CashLedgerMapper cashLedgerMapper,
TransactionMapper transactionMapper, AccountMapper accountMapper,
RefundMapper refundMapper, WebhookDeliveryMapper webhookMapper,
ReconcileReportMapper reportMapper, AppMapper appMapper,
ConfigService configService) {
this.orderMapper = orderMapper;
this.cashLedgerMapper = cashLedgerMapper;
this.transactionMapper = transactionMapper;
this.accountMapper = accountMapper;
this.refundMapper = refundMapper;
this.webhookMapper = webhookMapper;
this.reportMapper = reportMapper;
this.appMapper = appMapper;
this.configService = configService;
}
public DashboardSummaryResponse summary() {
LocalDateTime dayStart = LocalDate.now().atStartOfDay();
LocalDateTime dayEnd = dayStart.plusDays(1);
LocalDateTime now = LocalDateTime.now().withNano(0);
long todayAmountCent = cashLedgerMapper.selectList(new LambdaQueryWrapper<CashLedgerEntity>()
.eq(CashLedgerEntity::getDirection, "IN")
.ge(CashLedgerEntity::getReceivedAt, dayStart)
.lt(CashLedgerEntity::getReceivedAt, dayEnd))
.stream().mapToLong(CashLedgerEntity::getAmountCent).sum();
List<OrderEntity> paidToday = orderMapper.selectList(new LambdaQueryWrapper<OrderEntity>()
.isNotNull(OrderEntity::getPaidAt)
.ge(OrderEntity::getPaidAt, dayStart)
.lt(OrderEntity::getPaidAt, dayEnd));
List<OrderEntity> pending = orderMapper.selectList(new LambdaQueryWrapper<OrderEntity>()
.eq(OrderEntity::getStatus, "PENDING")
.gt(OrderEntity::getExpiresAt, now));
long todayConsumedPoints = transactionMapper.selectList(new LambdaQueryWrapper<TransactionEntity>()
.eq(TransactionEntity::getType, "CONSUME")
.ge(TransactionEntity::getCreateTime, dayStart)
.lt(TransactionEntity::getCreateTime, dayEnd))
.stream().mapToLong(TransactionEntity::getAmount).sum();
long totalBalance = accountMapper.selectList(null).stream()
.mapToLong(item -> item.getBalance() == null ? 0 : item.getBalance()).sum();
Long pendingRefunds = refundMapper.selectCount(new LambdaQueryWrapper<RefundEntity>()
.eq(RefundEntity::getStatus, "PENDING"));
Long deadWebhooks = webhookMapper.selectCount(new LambdaQueryWrapper<WebhookDeliveryEntity>()
.eq(WebhookDeliveryEntity::getStatus, "DEAD"));
Long diffReports = reportMapper.selectCount(new LambdaQueryWrapper<ReconcileReportEntity>()
.eq(ReconcileReportEntity::getStatus, "DIFF"));
return new DashboardSummaryResponse(todayAmountCent, paidToday.size(), pending.size(),
pending.stream().mapToLong(OrderEntity::getAmountCent).sum(), todayConsumedPoints,
pendingRefunds == null ? 0 : pendingRefunds, totalBalance,
deadWebhooks == null ? 0 : deadWebhooks, diffReports == null ? 0 : diffReports,
configService.getNumber("review.threshold_cent", 500000));
}
public List<TrendPointResponse> trend() {
LocalDate today = LocalDate.now();
LocalDate start = today.minusDays(13);
List<CashLedgerEntity> cash = cashLedgerMapper.selectList(new LambdaQueryWrapper<CashLedgerEntity>()
.eq(CashLedgerEntity::getDirection, "IN")
.ge(CashLedgerEntity::getReceivedAt, start.atStartOfDay()));
List<TransactionEntity> consumed = transactionMapper.selectList(new LambdaQueryWrapper<TransactionEntity>()
.eq(TransactionEntity::getType, "CONSUME")
.ge(TransactionEntity::getCreateTime, start.atStartOfDay()));
List<OrderEntity> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderEntity>()
.ge(OrderEntity::getCreateTime, start.atStartOfDay()));
Map<LocalDate, Long> amountMap = new HashMap<>();
cash.forEach(item -> amountMap.merge(item.getReceivedAt().toLocalDate(), item.getAmountCent(), Long::sum));
Map<LocalDate, Long> pointsMap = new HashMap<>();
consumed.forEach(item -> pointsMap.merge(item.getCreateTime().toLocalDate(), item.getAmount(), Long::sum));
Map<LocalDate, Long> orderMap = new HashMap<>();
orders.forEach(item -> orderMap.merge(item.getCreateTime().toLocalDate(), 1L, Long::sum));
List<TrendPointResponse> points = new ArrayList<>();
for (int i = 0; i < 14; i++) {
LocalDate date = start.plusDays(i);
points.add(new TrendPointResponse(String.format("%02d-%02d", date.getMonthValue(), date.getDayOfMonth()),
amountMap.getOrDefault(date, 0L), pointsMap.getOrDefault(date, 0L),
orderMap.getOrDefault(date, 0L)));
}
return points;
}
public List<AppDistributionResponse> distribution() {
LocalDateTime monthAgo = LocalDate.now().minusDays(30).atStartOfDay();
Map<String, Long> counts = new HashMap<>();
Map<String, Long> amounts = new HashMap<>();
orderMapper.selectList(new LambdaQueryWrapper<OrderEntity>()
.isNotNull(OrderEntity::getPaidAt)
.ge(OrderEntity::getPaidAt, monthAgo))
.forEach(item -> {
counts.merge(item.getAppCode(), 1L, Long::sum);
amounts.merge(item.getAppCode(), item.getAmountCent(), Long::sum);
});
List<AppDistributionResponse> result = new ArrayList<>();
for (AppEntity app : appMapper.selectList(new LambdaQueryWrapper<AppEntity>()
.orderByAsc(AppEntity::getCreateTime))) {
result.add(new AppDistributionResponse(app.getAppCode(), app.getAppName(),
amounts.getOrDefault(app.getAppCode(), 0L),
counts.getOrDefault(app.getAppCode(), 0L)));
}
return result;
}
}
@@ -0,0 +1,75 @@
package com.gas.fin.health;
import com.gas.fin.common.api.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 探活接口:只返回组件状态,不返回连接串、主机名与构建信息。
*/
@RestController
public class HealthController {
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final JdbcTemplate jdbcTemplate;
private final StringRedisTemplate redisTemplate;
@Value("${fin.version:unknown}")
private String version;
public HealthController(JdbcTemplate jdbcTemplate, StringRedisTemplate redisTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.redisTemplate = redisTemplate;
}
@GetMapping("/api/health")
public ResponseEntity<R<Map<String, Object>>> health() {
boolean dbUp = checkDb();
boolean redisUp = checkRedis();
boolean up = dbUp && redisUp;
Map<String, Object> data = new LinkedHashMap<>();
data.put("status", up ? "UP" : "DOWN");
data.put("db", dbUp ? "UP" : "DOWN");
data.put("redis", redisUp ? "UP" : "DOWN");
data.put("version", version);
data.put("time", LocalDateTime.now().format(TIME_FORMAT));
if (up) {
return ResponseEntity.ok(R.ok(data));
}
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(R.fail(503, "service unavailable", data));
}
private boolean checkDb() {
try (Connection connection = jdbcTemplate.getDataSource().getConnection()) {
return connection.isValid(1);
} catch (Exception ex) {
return false;
}
}
private boolean checkRedis() {
try {
String pong = redisTemplate.execute((RedisCallback<String>) RedisConnection::ping);
return "PONG".equalsIgnoreCase(pong);
} catch (Exception ex) {
return false;
}
}
}
@@ -0,0 +1,31 @@
package com.gas.fin.order.controller;
import com.gas.fin.common.api.R;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import com.gas.fin.order.dto.ApproverResponse;
import com.gas.fin.order.service.OrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/admin/approvers")
public class ApproverController {
private final OrderService orderService;
public ApproverController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping
@RequirePermission(value = {PermissionRegistry.RECHARGE_CONFIRM, PermissionRegistry.REFUND_REVIEW,
PermissionRegistry.ACCOUNT_ADJUST}, anyOf = true)
public R<List<ApproverResponse>> list() {
return R.ok(orderService.approvers(AuthContext.require()));
}
}
@@ -0,0 +1,83 @@
package com.gas.fin.order.controller;
import com.gas.fin.common.api.PageResult;
import com.gas.fin.common.api.R;
import com.gas.fin.common.security.AuthContext;
import com.gas.fin.common.security.PermissionRegistry;
import com.gas.fin.common.security.RequirePermission;
import com.gas.fin.order.dto.OrderCancelRequest;
import com.gas.fin.order.dto.OrderConfirmRequest;
import com.gas.fin.order.dto.OrderDetailResponse;
import com.gas.fin.order.dto.OrderInfoResponse;
import com.gas.fin.order.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/admin/orders")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping
@RequirePermission(PermissionRegistry.VIEW)
public R<PageResult<OrderInfoResponse>> list(
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long pageSize,
@RequestParam(required = false) String appCode,
@RequestParam(required = false) String status,
@RequestParam(required = false) String orderType,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) String from,
@RequestParam(required = false) String to) {
return R.ok(orderService.page(page, pageSize, appCode, status, orderType, keyword, from, to));
}
@GetMapping("/export")
@RequirePermission(PermissionRegistry.EXPORT)
public R<List<OrderInfoResponse>> export(
@RequestParam(required = false) String appCode,
@RequestParam(required = false) String status,
@RequestParam(required = false) String orderType,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) String from,
@RequestParam(required = false) String to,
HttpServletRequest httpRequest) {
return R.ok(orderService.export(appCode, status, orderType, keyword, from, to,
AuthContext.require(), httpRequest));
}
@GetMapping("/{id}")
@RequirePermission(PermissionRegistry.VIEW)
public R<OrderDetailResponse> detail(@PathVariable Long id) {
return R.ok(orderService.detail(id));
}
@PostMapping("/{id}/confirm")
@RequirePermission(PermissionRegistry.RECHARGE_CONFIRM)
public R<OrderInfoResponse> confirm(@PathVariable Long id,
@RequestBody OrderConfirmRequest request,
HttpServletRequest httpRequest) {
return R.ok(orderService.confirm(id, request, AuthContext.require(), httpRequest));
}
@PostMapping("/{id}/cancel")
@RequirePermission(PermissionRegistry.ORDER_CANCEL)
public R<OrderInfoResponse> cancel(@PathVariable Long id,
@RequestBody OrderCancelRequest request,
HttpServletRequest httpRequest) {
return R.ok(orderService.cancel(id, request, AuthContext.require(), httpRequest));
}
}
@@ -0,0 +1,4 @@
package com.gas.fin.order.dto;
public record ApproverResponse(Long id, String username, String role) {
}
@@ -0,0 +1,4 @@
package com.gas.fin.order.dto;
public record OrderCancelRequest(String reason, String totp) {
}
@@ -0,0 +1,4 @@
package com.gas.fin.order.dto;
public record OrderConfirmRequest(String voucherNo, String receiveAt, Long secondApproverId, String totp) {
}
@@ -0,0 +1,14 @@
package com.gas.fin.order.dto;
import com.gas.fin.refund.dto.RefundInfoResponse;
import java.time.LocalDateTime;
import java.util.List;
public record OrderDetailResponse(OrderInfoResponse order, List<RefundInfoResponse> refunds,
List<CashFlow> cashFlows) {
public record CashFlow(Long id, String direction, Long amountCent, LocalDateTime receivedAt,
String voucherNo, String remark) {
}
}
@@ -0,0 +1,65 @@
package com.gas.fin.order.dto;
import com.gas.fin.order.entity.OrderEntity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class OrderInfoResponse {
private Long id;
private String outTradeNo;
private String appCode;
private String appName;
private String businessUserId;
private String usernameSnapshot;
private String orderType;
private String payMethod;
private Long amountCent;
private Long pointsGained;
private String vipPlanCode;
private String status;
private LocalDateTime expiresAt;
private LocalDateTime paidAt;
private Long confirmedByAdminId;
private String confirmedByAdminName;
private Long secondApproverId;
private String secondApproverName;
private String remark;
private LocalDateTime createTime;
private Long refundedAmountCent;
private Long cashInCent;
private Long cashOutCent;
private boolean needDualControl;
public static OrderInfoResponse from(OrderEntity entity, String appName, long cashInCent,
long cashOutCent, boolean needDualControl) {
OrderInfoResponse response = new OrderInfoResponse();
response.setId(entity.getId());
response.setOutTradeNo(entity.getOutTradeNo());
response.setAppCode(entity.getAppCode());
response.setAppName(appName == null ? entity.getAppCode() : appName);
response.setBusinessUserId(entity.getBusinessUserId());
response.setUsernameSnapshot(entity.getUsernameSnapshot());
response.setOrderType(entity.getOrderType());
response.setPayMethod(entity.getPayMethod());
response.setAmountCent(entity.getAmountCent());
response.setPointsGained(entity.getPointsGained());
response.setVipPlanCode(entity.getVipPlanCode());
response.setStatus(entity.getStatus());
response.setExpiresAt(entity.getExpiresAt());
response.setPaidAt(entity.getPaidAt());
response.setConfirmedByAdminId(entity.getConfirmedByAdminId());
response.setConfirmedByAdminName(entity.getConfirmedByAdminName());
response.setSecondApproverId(entity.getSecondApproverId());
response.setSecondApproverName(entity.getSecondApproverName());
response.setRemark(entity.getRemark() == null ? "" : entity.getRemark());
response.setCreateTime(entity.getCreateTime());
response.setRefundedAmountCent(entity.getRefundedAmountCent() == null ? 0L : entity.getRefundedAmountCent());
response.setCashInCent(cashInCent);
response.setCashOutCent(cashOutCent);
response.setNeedDualControl(needDualControl);
return response;
}
}
@@ -0,0 +1,28 @@
package com.gas.fin.order.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_cash_ledger")
public class CashLedgerEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String appCode;
private Long orderId;
private Long refundId;
private String direction;
private Long amountCent;
private LocalDateTime receivedAt;
private String voucherNo;
private Long operatorAdminId;
private String operatorAdminName;
private String remark;
private LocalDateTime createTime;
}
@@ -0,0 +1,39 @@
package com.gas.fin.order.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("fin_order")
public class OrderEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
private String outTradeNo;
private String appCode;
private String businessUserId;
private String usernameSnapshot;
private String orderType;
private String payMethod;
private Long amountCent;
private Long pointsGained;
private Integer pointsPerYuanSnapshot;
private String vipPlanCode;
private String status;
private LocalDateTime expiresAt;
private LocalDateTime paidAt;
private Long confirmedByAdminId;
private String confirmedByAdminName;
private Long secondApproverId;
private String secondApproverName;
private String remark;
private Long refundedAmountCent;
private Integer versionNo;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,9 @@
package com.gas.fin.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.order.entity.CashLedgerEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CashLedgerMapper extends BaseMapper<CashLedgerEntity> {
}
@@ -0,0 +1,9 @@
package com.gas.fin.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gas.fin.order.entity.OrderEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface OrderMapper extends BaseMapper<OrderEntity> {
}
@@ -0,0 +1,470 @@
package com.gas.fin.order.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gas.fin.account.entity.AccountEntity;
import com.gas.fin.account.mapper.AccountMapper;
import com.gas.fin.admin.entity.AdminEntity;
import com.gas.fin.admin.mapper.AdminMapper;
import com.gas.fin.app.entity.AppEntity;
import com.gas.fin.app.mapper.AppMapper;
import com.gas.fin.common.api.PageResult;
import com.gas.fin.common.error.BizException;
import com.gas.fin.common.error.ErrorCode;
import com.gas.fin.common.security.AdminAuditor;
import com.gas.fin.common.security.TotpVerifier;
import com.gas.fin.common.util.HashUtils;
import com.gas.fin.common.web.QueryUtils;
import com.gas.fin.order.dto.ApproverResponse;
import com.gas.fin.order.dto.OrderCancelRequest;
import com.gas.fin.order.dto.OrderConfirmRequest;
import com.gas.fin.order.dto.OrderDetailResponse;
import com.gas.fin.order.dto.OrderInfoResponse;
import com.gas.fin.order.entity.CashLedgerEntity;
import com.gas.fin.order.entity.OrderEntity;
import com.gas.fin.order.mapper.CashLedgerMapper;
import com.gas.fin.order.mapper.OrderMapper;
import com.gas.fin.pricing.service.PricingService;
import com.gas.fin.refund.dto.RefundInfoResponse;
import com.gas.fin.refund.entity.RefundEntity;
import com.gas.fin.refund.mapper.RefundMapper;
import com.gas.fin.transaction.entity.TransactionEntity;
import com.gas.fin.transaction.mapper.TransactionMapper;
import com.gas.fin.vip.entity.VipHolderEntity;
import com.gas.fin.vip.entity.VipPlanEntity;
import com.gas.fin.vip.mapper.VipHolderMapper;
import com.gas.fin.vip.mapper.VipPlanMapper;
import com.gas.fin.webhook.service.WebhookService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 充值/VIP 订单:查询、确认到账、关单、审批人列表。
*/
@Service
public class OrderService {
private static final int EXPORT_LIMIT = 10000;
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final OrderMapper orderMapper;
private final CashLedgerMapper cashLedgerMapper;
private final RefundMapper refundMapper;
private final AccountMapper accountMapper;
private final VipPlanMapper vipPlanMapper;
private final VipHolderMapper vipHolderMapper;
private final TransactionMapper transactionMapper;
private final AdminMapper adminMapper;
private final AppMapper appMapper;
private final PricingService pricingService;
private final WebhookService webhookService;
private final TotpVerifier totpVerifier;
private final AdminAuditor adminAuditor;
private final ObjectMapper objectMapper;
public OrderService(OrderMapper orderMapper, CashLedgerMapper cashLedgerMapper,
RefundMapper refundMapper, AccountMapper accountMapper,
VipPlanMapper vipPlanMapper, VipHolderMapper vipHolderMapper,
TransactionMapper transactionMapper, AdminMapper adminMapper, AppMapper appMapper,
PricingService pricingService, WebhookService webhookService,
TotpVerifier totpVerifier, AdminAuditor adminAuditor, ObjectMapper objectMapper) {
this.orderMapper = orderMapper;
this.cashLedgerMapper = cashLedgerMapper;
this.refundMapper = refundMapper;
this.accountMapper = accountMapper;
this.vipPlanMapper = vipPlanMapper;
this.vipHolderMapper = vipHolderMapper;
this.transactionMapper = transactionMapper;
this.adminMapper = adminMapper;
this.appMapper = appMapper;
this.pricingService = pricingService;
this.webhookService = webhookService;
this.totpVerifier = totpVerifier;
this.adminAuditor = adminAuditor;
this.objectMapper = objectMapper;
}
public PageResult<OrderInfoResponse> page(long page, long pageSize, String appCode, String status,
String orderType, String keyword, String from, String to) {
QueryUtils.checkPage(page, pageSize);
Page<OrderEntity> result = orderMapper.selectPage(new Page<>(page, pageSize),
wrapper(appCode, status, orderType, keyword, from, to));
return PageResult.of(enrich(result.getRecords()), result.getTotal(), page, pageSize);
}
public List<OrderInfoResponse> export(String appCode, String status, String orderType, String keyword,
String from, String to, AdminEntity current,
HttpServletRequest httpRequest) {
LambdaQueryWrapper<OrderEntity> wrapper = wrapper(appCode, status, orderType, keyword, from, to);
wrapper.last("LIMIT " + (EXPORT_LIMIT + 1));
List<OrderEntity> list = orderMapper.selectList(wrapper);
if (list.size() > EXPORT_LIMIT) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "导出数据超过 10000 行,请缩小查询范围");
}
adminAuditor.success(current, "ORDER_EXPORT", "导出订单(" + list.size() + " 条)",
"ORDER", null, null, Map.of("appCode", appCode == null ? "" : appCode,
"status", status == null ? "" : status, "count", list.size()), httpRequest);
return enrich(list);
}
public OrderDetailResponse detail(Long id) {
OrderEntity order = requireOrder(id);
List<OrderInfoResponse> enriched = enrich(List.of(order));
List<RefundEntity> refunds = refundMapper.selectList(new LambdaQueryWrapper<RefundEntity>()
.eq(RefundEntity::getOrderId, id)
.orderByDesc(RefundEntity::getCreateTime).orderByDesc(RefundEntity::getId));
List<CashLedgerEntity> cash = cashLedgerMapper.selectList(new LambdaQueryWrapper<CashLedgerEntity>()
.eq(CashLedgerEntity::getOrderId, id)
.orderByDesc(CashLedgerEntity::getReceivedAt));
String appName = appNames().get(order.getAppCode());
List<OrderDetailResponse.CashFlow> flows = cash.stream()
.map(item -> new OrderDetailResponse.CashFlow(item.getId(), item.getDirection(),
item.getAmountCent(), item.getReceivedAt(), item.getVoucherNo(),
item.getRemark() == null ? "" : item.getRemark()))
.toList();
return new OrderDetailResponse(enriched.get(0),
refunds.stream().map(item -> RefundInfoResponse.from(item, appName)).toList(), flows);
}
@Transactional
public OrderInfoResponse confirm(Long id, OrderConfirmRequest request, AdminEntity current,
HttpServletRequest httpRequest) {
OrderEntity order = requireOrder(id);
if (!"PENDING".equals(order.getStatus())) {
throw new BizException(ErrorCode.STATUS_CONFLICT, "订单当前状态不可确认到账,请刷新后重试");
}
String voucherNo = QueryUtils.text(request.voucherNo());
if (voucherNo.length() < 6 || voucherNo.length() > 32) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写银行回单/转账凭证号(6~32 位)");
}
LocalDateTime now = LocalDateTime.now().withNano(0);
LocalDateTime receiveAt = parseReceiveAt(request.receiveAt(), now);
if (receiveAt.isBefore(order.getCreateTime())) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间不能早于订单创建时间");
}
if (receiveAt.isAfter(now)) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间不能晚于当前时间");
}
totpVerifier.verify(current, request.totp(), "ORDER_CONFIRM", "确认订单到账", httpRequest);
Long used = cashLedgerMapper.selectCount(new LambdaQueryWrapper<CashLedgerEntity>()
.eq(CashLedgerEntity::getDirection, "IN")
.eq(CashLedgerEntity::getVoucherNo, voucherNo)
.ne(CashLedgerEntity::getOrderId, id));
if (used != null && used > 0) {
throw new BizException(ErrorCode.DUPLICATE_VOUCHER);
}
long threshold = pricingService.thresholdOf(order.getAppCode());
AdminEntity approver = null;
if (order.getAmountCent() >= threshold) {
if (request.secondApproverId() == null) {
throw new BizException(ErrorCode.SECOND_APPROVER_REQUIRED,
"订单金额达到 " + (threshold / 100) + " 元,必须由第二人复核后才能入账");
}
if (request.secondApproverId().equals(current.getId())) {
throw new BizException(ErrorCode.INVALID_APPROVER, "复核人不得与确认人为同一人");
}
approver = adminMapper.selectById(request.secondApproverId());
if (approver == null || !Integer.valueOf(1).equals(approver.getIsActive())) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "复核管理员不存在或已停用");
}
if (!"SUPER_ADMIN".equals(approver.getRole()) && !"FINANCE".equals(approver.getRole())) {
throw new BizException(ErrorCode.INVALID_APPROVER, "复核人必须具备资金操作权限");
}
}
VipPlanEntity plan = null;
if ("vip".equals(order.getOrderType())) {
plan = vipPlanMapper.selectOne(new LambdaQueryWrapper<VipPlanEntity>()
.eq(VipPlanEntity::getAppCode, order.getAppCode())
.eq(VipPlanEntity::getPlanCode, order.getVipPlanCode())
.eq(VipPlanEntity::getEnabled, 1)
.last("LIMIT 1"));
if (plan == null) {
throw new BizException(ErrorCode.BIZ_OBJECT_UNAVAILABLE, "VIP 档位不存在或已下架");
}
}
AccountEntity account = "vip".equals(order.getOrderType()) ? null
: findAccount(order.getAppCode(), order.getBusinessUserId());
if (!"vip".equals(order.getOrderType()) && order.getPointsGained() > 0 && account == null) {
throw new BizException(ErrorCode.NOT_FOUND, "业务用户钱包不存在,无法入账");
}
int version = order.getVersionNo() == null ? 0 : order.getVersionNo();
LambdaUpdateWrapper<OrderEntity> update = new LambdaUpdateWrapper<OrderEntity>()
.eq(OrderEntity::getId, id)
.eq(OrderEntity::getStatus, "PENDING")
.set(OrderEntity::getStatus, "PAID")
.set(OrderEntity::getPaidAt, now)
.set(OrderEntity::getConfirmedByAdminId, current.getId())
.set(OrderEntity::getConfirmedByAdminName, current.getUsername())
.set(OrderEntity::getVersionNo, version + 1)
.set(OrderEntity::getUpdateTime, now);
if (approver != null) {
update.set(OrderEntity::getSecondApproverId, approver.getId())
.set(OrderEntity::getSecondApproverName, approver.getUsername());
}
if (orderMapper.update(null, update) == 0) {
throw new BizException(ErrorCode.STATUS_CONFLICT, "订单当前状态不可确认到账,请刷新后重试");
}
CashLedgerEntity cash = new CashLedgerEntity();
cash.setAppCode(order.getAppCode());
cash.setOrderId(order.getId());
cash.setDirection("IN");
cash.setAmountCent(order.getAmountCent());
cash.setReceivedAt(receiveAt);
cash.setVoucherNo(voucherNo);
cash.setOperatorAdminId(current.getId());
cash.setOperatorAdminName(current.getUsername());
cash.setRemark("管理员确认到账");
cash.setCreateTime(now);
cashLedgerMapper.insert(cash);
if (plan != null) {
applyVip(order, plan, now);
} else if (order.getPointsGained() > 0) {
applyRecharge(order, account, current, now);
}
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("outTradeNo", order.getOutTradeNo());
payload.put("amountCent", order.getAmountCent());
payload.put("points", order.getPointsGained());
webhookService.enqueue(order.getAppCode(), eventId("order.paid", order.getOutTradeNo(), now),
"order.paid", toJson(payload));
Map<String, Object> before = new LinkedHashMap<>();
before.put("status", "PENDING");
Map<String, Object> after = new LinkedHashMap<>();
after.put("status", "PAID");
after.put("voucherNo", voucherNo);
after.put("secondApproverId", approver == null ? null : approver.getId());
adminAuditor.success(current, "ORDER_CONFIRM", "确认订单到账", "ORDER", id, before, after, httpRequest);
return enrich(List.of(requireOrder(id))).get(0);
}
@Transactional
public OrderInfoResponse cancel(Long id, OrderCancelRequest request, AdminEntity current,
HttpServletRequest httpRequest) {
OrderEntity order = requireOrder(id);
if (!"PENDING".equals(order.getStatus())) {
throw new BizException(ErrorCode.STATUS_CONFLICT, "仅待确认订单可以关单");
}
String reason = QueryUtils.text(request.reason());
if (reason.length() < 5 || reason.length() > 255) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写关单原因(不少于 5 个字)");
}
totpVerifier.verify(current, request.totp(), "ORDER_CANCEL", "关闭订单", httpRequest);
int version = order.getVersionNo() == null ? 0 : order.getVersionNo();
int rows = orderMapper.update(null, new LambdaUpdateWrapper<OrderEntity>()
.eq(OrderEntity::getId, id)
.eq(OrderEntity::getStatus, "PENDING")
.set(OrderEntity::getStatus, "CANCELLED")
.set(OrderEntity::getRemark, reason)
.set(OrderEntity::getVersionNo, version + 1)
.set(OrderEntity::getUpdateTime, LocalDateTime.now().withNano(0)));
if (rows == 0) {
throw new BizException(ErrorCode.STATUS_CONFLICT, "仅待确认订单可以关单");
}
Map<String, Object> after = new LinkedHashMap<>();
after.put("status", "CANCELLED");
after.put("reason", reason);
adminAuditor.success(current, "ORDER_CANCEL", "关闭订单", "ORDER", id, null, after, httpRequest);
return enrich(List.of(requireOrder(id))).get(0);
}
public List<ApproverResponse> approvers(AdminEntity current) {
return adminMapper.selectList(new LambdaQueryWrapper<AdminEntity>()
.eq(AdminEntity::getIsActive, 1)
.ne(AdminEntity::getId, current.getId())
.in(AdminEntity::getRole, List.of("SUPER_ADMIN", "FINANCE"))
.orderByAsc(AdminEntity::getUsername))
.stream()
.map(item -> new ApproverResponse(item.getId(), item.getUsername(), item.getRole()))
.toList();
}
private void applyRecharge(OrderEntity order, AccountEntity account, AdminEntity current, LocalDateTime now) {
long before = account.getBalance();
long after = before + order.getPointsGained();
int version = account.getVersionNo() == null ? 0 : account.getVersionNo();
int rows = accountMapper.update(null, new LambdaUpdateWrapper<AccountEntity>()
.eq(AccountEntity::getId, account.getId())
.eq(AccountEntity::getVersionNo, version)
.set(AccountEntity::getBalance, after)
.set(AccountEntity::getVersionNo, version + 1)
.set(AccountEntity::getUpdateTime, now));
if (rows == 0) {
throw new BizException(ErrorCode.CONCURRENT_CONFLICT);
}
TransactionEntity tx = new TransactionEntity();
tx.setAppCode(order.getAppCode());
tx.setBusinessUserId(order.getBusinessUserId());
tx.setUsernameSnapshot(order.getUsernameSnapshot());
tx.setType("RECHARGE");
tx.setAmount(order.getPointsGained());
tx.setBalanceBefore(before);
tx.setBalanceAfter(after);
tx.setBusinessRefId(order.getOutTradeNo());
tx.setIdempotencyKey("order:" + order.getOutTradeNo());
tx.setOrderId(order.getId());
tx.setOutTradeNo(order.getOutTradeNo());
tx.setRefundedPoints(0L);
tx.setOperatorAdminId(current.getId());
tx.setOperatorAdminName(current.getUsername());
tx.setRemark("充值确认到账");
tx.setCreateTime(now);
transactionMapper.insert(tx);
}
private void applyVip(OrderEntity order, VipPlanEntity plan, LocalDateTime now) {
VipHolderEntity holder = vipHolderMapper.selectOne(new LambdaQueryWrapper<VipHolderEntity>()
.eq(VipHolderEntity::getAppCode, order.getAppCode())
.eq(VipHolderEntity::getBusinessUserId, order.getBusinessUserId())
.last("LIMIT 1"));
LocalDateTime base = holder != null && holder.getVipUntil().isAfter(now) ? holder.getVipUntil() : now;
LocalDateTime vipUntil = base.plusDays(plan.getDurationDays());
if (holder == null) {
VipHolderEntity entity = new VipHolderEntity();
entity.setAppCode(order.getAppCode());
entity.setBusinessUserId(order.getBusinessUserId());
entity.setVipPlanCode(plan.getPlanCode());
entity.setVipUntil(vipUntil);
entity.setCreateTime(now);
entity.setUpdateTime(now);
vipHolderMapper.insert(entity);
} else {
vipHolderMapper.update(null, new LambdaUpdateWrapper<VipHolderEntity>()
.eq(VipHolderEntity::getId, holder.getId())
.set(VipHolderEntity::getVipPlanCode, plan.getPlanCode())
.set(VipHolderEntity::getVipUntil, vipUntil)
.set(VipHolderEntity::getUpdateTime, now));
}
AccountEntity account = findAccount(order.getAppCode(), order.getBusinessUserId());
if (account != null) {
accountMapper.update(null, new LambdaUpdateWrapper<AccountEntity>()
.eq(AccountEntity::getId, account.getId())
.set(AccountEntity::getVipPlanCode, plan.getPlanCode())
.set(AccountEntity::getVipUntil, vipUntil)
.set(AccountEntity::getUpdateTime, now));
}
}
private List<OrderInfoResponse> enrich(List<OrderEntity> orders) {
if (orders.isEmpty()) {
return List.of();
}
List<Long> ids = orders.stream().map(OrderEntity::getId).toList();
Map<Long, Long> cashIn = new HashMap<>();
Map<Long, Long> cashOut = new HashMap<>();
cashLedgerMapper.selectList(new LambdaQueryWrapper<CashLedgerEntity>()
.in(CashLedgerEntity::getOrderId, ids))
.forEach(item -> {
Map<Long, Long> target = "IN".equals(item.getDirection()) ? cashIn : cashOut;
target.merge(item.getOrderId(), item.getAmountCent(), Long::sum);
});
Map<String, String> appNames = appNames();
Map<String, Long> thresholds = new HashMap<>();
List<OrderInfoResponse> result = new ArrayList<>();
for (OrderEntity order : orders) {
long threshold = thresholds.computeIfAbsent(order.getAppCode(), pricingService::thresholdOf);
result.add(OrderInfoResponse.from(order, appNames.get(order.getAppCode()),
cashIn.getOrDefault(order.getId(), 0L), cashOut.getOrDefault(order.getId(), 0L),
order.getAmountCent() >= threshold));
}
return result;
}
private LambdaQueryWrapper<OrderEntity> wrapper(String appCode, String status, String orderType,
String keyword, String from, String to) {
LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
if (appCode != null && !appCode.isBlank()) {
wrapper.eq(OrderEntity::getAppCode, appCode.trim());
}
if (status != null && !status.isBlank()) {
wrapper.eq(OrderEntity::getStatus, status.trim());
}
if (orderType != null && !orderType.isBlank()) {
wrapper.eq(OrderEntity::getOrderType, orderType.trim());
}
if (keyword != null && !keyword.isBlank()) {
String value = keyword.trim();
wrapper.and(w -> w.like(OrderEntity::getOutTradeNo, value)
.or().like(OrderEntity::getBusinessUserId, value)
.or().like(OrderEntity::getUsernameSnapshot, value));
}
LocalDateTime fromTime = QueryUtils.parseFrom(from);
LocalDateTime toTime = QueryUtils.parseTo(to);
if (fromTime != null) {
wrapper.ge(OrderEntity::getCreateTime, fromTime);
}
if (toTime != null) {
wrapper.le(OrderEntity::getCreateTime, toTime);
}
wrapper.orderByDesc(OrderEntity::getCreateTime).orderByDesc(OrderEntity::getId);
return wrapper;
}
private OrderEntity requireOrder(Long id) {
OrderEntity order = orderMapper.selectById(id);
if (order == null) {
throw new BizException(ErrorCode.NOT_FOUND, "订单不存在");
}
return order;
}
private AccountEntity findAccount(String appCode, String businessUserId) {
return accountMapper.selectOne(new LambdaQueryWrapper<AccountEntity>()
.eq(AccountEntity::getAppCode, appCode)
.eq(AccountEntity::getBusinessUserId, businessUserId)
.last("LIMIT 1"));
}
private LocalDateTime parseReceiveAt(String value, LocalDateTime now) {
if (value == null || value.isBlank()) {
return now;
}
String text = value.trim();
if (!text.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间格式不合法");
}
try {
return LocalDateTime.parse(text, TIME_FORMAT);
} catch (DateTimeParseException ex) {
throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间格式不合法");
}
}
private String eventId(String type, String tradeNo, LocalDateTime now) {
return "evt_" + HashUtils.sha256Hex(type + "|" + tradeNo + "|" + now).substring(0, 20);
}
private String toJson(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException ex) {
throw new IllegalStateException("webhook payload 序列化失败", ex);
}
}
private Map<String, String> appNames() {
return appMapper.selectList(null).stream()
.collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a));
}
}
@@ -0,0 +1,52 @@
package com.gas.fin.pay.controller;
import com.gas.fin.common.api.R;
import com.gas.fin.pay.dto.DemoTicketResponse;
import com.gas.fin.pay.dto.PayCreateRequest;
import com.gas.fin.pay.dto.PayOrderResponse;
import com.gas.fin.pay.dto.PayPreviewResponse;
import com.gas.fin.pay.dto.PayStatusResponse;
import com.gas.fin.pay.service.PayService;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 公开收银台:不走管理端认证拦截器(/api/pay/**)。
*/
@RestController
@RequestMapping("/api/pay")
public class PayController {
private final PayService payService;
public PayController(PayService payService) {
this.payService = payService;
}
@GetMapping("/preview")
public R<PayPreviewResponse> preview(@RequestParam String appCode,
@RequestParam String ticket,
@RequestParam(required = false) String redirectUri) {
return R.ok(payService.preview(appCode, ticket, redirectUri));
}
@PostMapping("/orders")
public R<PayOrderResponse> create(@RequestBody PayCreateRequest request) {
return R.ok(payService.create(request));
}
@GetMapping("/orders/{outTradeNo}/status")
public R<PayStatusResponse> status(@PathVariable String outTradeNo) {
return R.ok(payService.status(outTradeNo));
}
@GetMapping("/demo-ticket")
public R<DemoTicketResponse> demoTicket(@RequestParam(required = false) String appCode) {
return R.ok(payService.demoTicket(appCode));
}
}
@@ -0,0 +1,7 @@
package com.gas.fin.pay.dto;
import java.time.LocalDateTime;
public record DemoTicketResponse(String appCode, String ticket, String businessUserId, String username,
String redirectUri, LocalDateTime expiresAt) {
}

Some files were not shown because too many files have changed in this diff Show More