package com.yau.digitalrmb.walletopening.application; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.infrastructure.InstitutionIdentifierApplicationEntity; import com.yau.digitalrmb.institutionidentity.infrastructure.InstitutionIdentifierApplicationMapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.yau.digitalrmb.security.context.JwtUser; import com.yau.digitalrmb.shared.api.ErrorCode; import com.yau.digitalrmb.shared.exception.BusinessException; import com.yau.digitalrmb.walletopening.domain.BankReceivedApplication; import com.yau.digitalrmb.walletopening.domain.BankReceivedApplicationRepository; import com.yau.digitalrmb.walletopening.domain.WalletApplication; import com.yau.digitalrmb.walletopening.domain.WalletApplicationRepository; import com.yau.digitalrmb.walletopening.interfaces.rest.dto.WalletApplicationRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Service public class WalletOpeningService { private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); /** 原型“用户信息”面板中的默认身份信息:当用户档案里没有对应字段时作为兜底 */ private static final String FIXED_PHONE = "13800138000"; private static final String FIXED_ID_NUMBER = "110101199001011234"; private static final String FIXED_BANK_CARD_NUMBER = "6216610100001234567"; @Resource private WalletApplicationRepository walletRepository; @Resource private BankReceivedApplicationRepository bankReceivedRepository; @Resource private InstitutionIdentifierApplicationMapper institutionIdentifierMapper; @Resource private WalletOpeningScoreService scoreService; @Transactional(readOnly = true) public UserWalletPageResult getPage(InstitutionKeySubject subject, JwtUser jwtUser) { WalletApplication app = walletRepository.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()) .orElseGet(() -> { // 未创建记录时,返回一个只包含JWT用户信息的临时对象,不保存到数据库 WalletApplication temp = WalletApplication.create( subject.getUserId(), subject.getSchoolId(), subject.getClassId(), jwtUser.getUserName(), jwtUser.getPhone()); return temp; }); // 以当前登录用户身份为准刷新“用户信息”面板,避免展示首次登录时落库的旧手机号 app.refreshTokenUserInfo(jwtUser.getUserName(), jwtUser.getPhone()); return new UserWalletPageResult(app); } @Transactional public FaceRecognitionResult updateFaceRecognition(InstitutionKeySubject subject, JwtUser jwtUser, int status) { WalletApplication app = walletRepository.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()) .orElseGet(() -> { // 首次人脸识别时创建记录 WalletApplication newApp = WalletApplication.create( subject.getUserId(), subject.getSchoolId(), subject.getClassId(), jwtUser.getUserName(), jwtUser.getPhone()); return walletRepository.save(newApp); }); app.refreshTokenUserInfo(jwtUser.getUserName(), jwtUser.getPhone()); app.updateFaceRecognition(status); walletRepository.update(app); return new FaceRecognitionResult(status); } @Transactional public WalletApplicationMessageResult outputApplication(InstitutionKeySubject subject, JwtUser jwtUser, WalletApplicationRequest request) { WalletApplication app = walletRepository.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()) .orElseGet(() -> { // 首次输出申请报文时创建记录 WalletApplication newApp = WalletApplication.create( subject.getUserId(), subject.getSchoolId(), subject.getClassId(), jwtUser.getUserName(), jwtUser.getPhone()); return walletRepository.save(newApp); }); app.refreshTokenUserInfo(jwtUser.getUserName(), jwtUser.getPhone()); // 支持重复点击:已输出过则按最新表单内容重新生成报文并覆盖,不再拦截 if (app.getFaceRecognitionStatus() == null || app.getFaceRecognitionStatus() != 2) { throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成人脸识别"); } if (request.getWalletType() == null || request.getWalletType().trim().isEmpty()) { throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请选择数字钱包类型"); } // 校验手机号、身份证号、银行卡号必须与“用户信息”面板一致,不一致则错误数+1 validateFixedUserInfo(subject, app, request); BigDecimal accountBalance = request.getAccountBalance(); if (accountBalance == null || accountBalance.compareTo(BigDecimal.ZERO) <= 0) { accountBalance = new BigDecimal("50000.00"); } app.fillForm(request.getSelectedBank(), request.getWalletType(), request.getInputPhone(), request.getInputIdNumber(), request.getInputBankCardNumber(), request.getSignaturePhotoPath(), request.getIdNumber(), request.getAccountBank(), request.getBankCardNumber(), accountBalance); String applyTime = LocalDateTime.now().format(TIMESTAMP_FORMAT); String applicationId = "APP_" + applyTime; String concatenatedMessage = buildConcatenatedMessage(app, applyTime); String applicationMessage = buildApplicationMessage(app, applicationId, applyTime); app.outputApplication(applicationId, concatenatedMessage, applicationMessage, applyTime); walletRepository.update(app); return new WalletApplicationMessageResult(app); } @Transactional public WalletSendResult sendApplication(InstitutionKeySubject subject, JwtUser jwtUser) { WalletApplication app = walletRepository.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()) .orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "钱包申请不存在,请先输出申请报文")); if (app.getStatus() == null || app.getStatus().ordinal() < WalletApplication.Status.OUTPUT.ordinal()) { throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先输出申请报文"); } // 支持重复点击:重复发送只刷新发送状态与商业银行接收记录内容 app.submit(); walletRepository.update(app); String receiveTime = LocalDateTime.now().format(TIMESTAMP_FORMAT); String receiveId = "BK_RECEIVE_" + receiveTime; String orgCode = resolveOrgCode(subject); String effectiveIdNumber = app.getInputIdNumber() != null ? app.getInputIdNumber() : app.getIdNumber(); String effectivePhone = app.getInputPhone() != null ? app.getInputPhone() : app.getPhone(); String effectiveBankCardNumber = app.getInputBankCardNumber() != null ? app.getInputBankCardNumber() : app.getBankCardNumber(); java.util.Optional existing = bankReceivedRepository .findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()); if (existing.isPresent()) { BankReceivedApplication received = existing.get(); received.setReceiveId(receiveId); received.setApplicationId(app.getApplicationId()); received.setOrgCode(orgCode); received.setReceiveTime(receiveTime); received.setUserName(app.getUserName()); received.setIdNumber(effectiveIdNumber); received.setPhone(effectivePhone); received.setBankCardNumber(effectiveBankCardNumber); received.setWalletType(app.getWalletType()); received.setApplyTime(app.getApplyTime()); bankReceivedRepository.update(received); } else { BankReceivedApplication received = BankReceivedApplication.receive( subject.getUserId(), subject.getSchoolId(), subject.getClassId(), receiveId, app.getApplicationId(), orgCode, receiveTime, app.getUserName(), effectiveIdNumber, effectivePhone, effectiveBankCardNumber, app.getWalletType(), app.getApplyTime()); bankReceivedRepository.save(received); } return new WalletSendResult("已提交"); } /** * 校验手机号、身份证号、银行卡号必须与“用户信息”面板一致。 * 期望值优先取用户档案(手机号来自登录用户,身份证/银行卡来自钱包申请记录), * 档案缺失时回退原型固定值;手机号额外兼容原型演示号码 13800138000。 * 任一字段不一致:错误数+1(独立事务记录),并拒绝本次输出。 */ private void validateFixedUserInfo(InstitutionKeySubject subject, WalletApplication app, WalletApplicationRequest request) { java.util.List mismatches = new java.util.ArrayList<>(); String expectedPhone = firstNonBlank(app.getPhone(), FIXED_PHONE); String phone = normalized(request.getInputPhone()); // 兼容两种通过方式:与“用户信息”面板的手机号一致,或直接使用原型演示号码 13800138000 if (!expectedPhone.equals(phone) && !FIXED_PHONE.equals(phone)) { mismatches.add("手机号"); } String expectedIdNumber = firstNonBlank(app.getIdNumber(), FIXED_ID_NUMBER); String idNumber = normalized(firstNonBlank(request.getInputIdNumber(), request.getIdNumber())); if (!expectedIdNumber.equals(idNumber)) { mismatches.add("身份证号"); } String expectedBankCardNumber = firstNonBlank(app.getBankCardNumber(), FIXED_BANK_CARD_NUMBER); String bankCardNumber = normalized(firstNonBlank(request.getInputBankCardNumber(), request.getBankCardNumber())); if (!expectedBankCardNumber.equals(bankCardNumber)) { mismatches.add("银行卡号"); } if (!mismatches.isEmpty()) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, String.join("、", mismatches) + "与用户信息不一致,错误数+1"); } } /** 取第一个去除首尾空格后非空的值,用于“用户填写值优先、档案值兜底” */ private String firstNonBlank(String primary, String fallback) { return normalized(primary).isEmpty() ? normalized(fallback) : normalized(primary); } /** 去除空格与全角空格后比较,兼容“621661 010000 1234567”这类带分隔的输入 */ private String normalized(String value) { if (value == null) { return ""; } return value.replace(" ", "").replace("\u3000", "").trim(); } private String resolveOrgCode(InstitutionKeySubject subject) { InstitutionIdentifierApplicationEntity entity = institutionIdentifierMapper.selectOne( new LambdaQueryWrapper() .eq(InstitutionIdentifierApplicationEntity::getUserId, subject.getUserId()) .eq(InstitutionIdentifierApplicationEntity::getSchoolId, subject.getSchoolId()) .eq(InstitutionIdentifierApplicationEntity::getClassId, subject.getClassId()) .eq(InstitutionIdentifierApplicationEntity::getDeleted, false) .isNotNull(InstitutionIdentifierApplicationEntity::getInstitutionIdentifier) .orderByDesc(InstitutionIdentifierApplicationEntity::getCreatedAt) .last("LIMIT 1")); return entity == null ? null : entity.getBankCode(); } private String buildConcatenatedMessage(WalletApplication app, String applyTime) { String idNumber = app.getInputIdNumber() != null ? app.getInputIdNumber() : app.getIdNumber(); String phone = app.getInputPhone() != null ? app.getInputPhone() : app.getPhone(); String bankCardNumber = app.getInputBankCardNumber() != null ? app.getInputBankCardNumber() : app.getBankCardNumber(); return "APPLY|" + app.getUserName() + "|" + idNumber + "|" + phone + "|" + bankCardNumber + "|" + app.getWalletType() + "|" + applyTime; } private String buildApplicationMessage(WalletApplication app, String applicationId, String applyTime) { String idNumber = app.getInputIdNumber() != null ? app.getInputIdNumber() : app.getIdNumber(); String phone = app.getInputPhone() != null ? app.getInputPhone() : app.getPhone(); String bankCardNumber = app.getInputBankCardNumber() != null ? app.getInputBankCardNumber() : app.getBankCardNumber(); return "{\"applicationId\":\"" + applicationId + "\"," + "\"userName\":\"" + app.getUserName() + "\"," + "\"idNumber\":\"" + idNumber + "\"," + "\"phone\":\"" + phone + "\"," + "\"bankCardNumber\":\"" + bankCardNumber + "\"," + "\"walletType\":\"" + app.getWalletType() + "\"," + "\"applyTime\":\"" + applyTime + "\"," + "\"status\":\"已提交\"}"; } }