This commit is contained in:
liangzai
2025-07-20 20:53:26 +08:00
parent 83bf9aea7d
commit 8ad1d7288e
158 changed files with 18156 additions and 13188 deletions

View File

@@ -10,39 +10,24 @@ import (
// CertificationApplicationService 认证应用服务接口
type CertificationApplicationService interface {
// 认证申请管理
CreateCertification(ctx context.Context, cmd *commands.CreateCertificationCommand) (*responses.CertificationResponse, error)
// 认证状态查询
GetCertificationStatus(ctx context.Context, query *queries.GetCertificationStatusQuery) (*responses.CertificationResponse, error)
GetCertificationDetails(ctx context.Context, query *queries.GetCertificationDetailsQuery) (*responses.CertificationResponse, error)
GetCertificationProgress(ctx context.Context, userID string) (map[string]interface{}, error)
// 企业信息管理
CreateEnterpriseInfo(ctx context.Context, cmd *commands.CreateEnterpriseInfoCommand) (*responses.EnterpriseInfoResponse, error)
SubmitEnterpriseInfo(ctx context.Context, cmd *commands.SubmitEnterpriseInfoCommand) (*responses.EnterpriseInfoResponse, error)
SubmitEnterpriseInfo(ctx context.Context, cmd *commands.SubmitEnterpriseInfoCommand) (*responses.CertificationResponse, error)
// 营业执照上传
UploadLicense(ctx context.Context, cmd *commands.UploadLicenseCommand) (*responses.UploadLicenseResponse, error)
GetLicenseOCRResult(ctx context.Context, recordID string) (*responses.UploadLicenseResponse, error)
// UploadBusinessLicense 上传营业执照并同步OCR识别
UploadBusinessLicense(ctx context.Context, userID string, fileBytes []byte, fileName string) (*responses.UploadLicenseResponse, error)
// 人脸识别
InitiateFaceVerify(ctx context.Context, cmd *commands.InitiateFaceVerifyCommand) (*responses.FaceVerifyResponse, error)
CompleteFaceVerify(ctx context.Context, faceVerifyID string, isSuccess bool) error
RetryFaceVerify(ctx context.Context, userID string) (*responses.FaceVerifyResponse, error)
// 企业认证
GetEnterpriseAuthURL(ctx context.Context, userID string) (*responses.EnterpriseAuthURLResponse, error)
// 合同管理
ApplyContract(ctx context.Context, userID string) (*responses.CertificationResponse, error)
ApproveContract(ctx context.Context, certificationID, adminID, signingURL, approvalNotes string) error
RejectContract(ctx context.Context, certificationID, adminID, rejectReason string) error
CompleteContractSign(ctx context.Context, certificationID, contractURL string) error
RetryContractSign(ctx context.Context, userID string) (*responses.CertificationResponse, error)
// 认证完成
CompleteCertification(ctx context.Context, certificationID string) error
// 重试和重启
RetryStep(ctx context.Context, cmd *commands.RetryStepCommand) error
RestartCertification(ctx context.Context, certificationID string) error
GetContractSignURL(ctx context.Context, cmd *commands.GetContractSignURLCommand) (*responses.ContractSignURLResponse, error)
}
// EsignCallbackApplicationService e签宝回调应用服务接口
type EsignCallbackApplicationService interface {
// 处理e签宝回调
HandleCallback(ctx context.Context, callbackData map[string]interface{}, headers map[string]string, queryParams map[string]string) error
}

View File

@@ -2,112 +2,74 @@ package certification
import (
"context"
"errors"
"fmt"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
"tyapi-server/internal/application/certification/dto/commands"
"tyapi-server/internal/application/certification/dto/queries"
"tyapi-server/internal/application/certification/dto/responses"
"tyapi-server/internal/domains/certification/entities"
"tyapi-server/internal/domains/certification/repositories"
"tyapi-server/internal/domains/certification/enums"
"tyapi-server/internal/domains/certification/services"
user_entities "tyapi-server/internal/domains/user/entities"
user_repositories "tyapi-server/internal/domains/user/repositories"
"tyapi-server/internal/shared/ocr"
"tyapi-server/internal/shared/storage"
user_services "tyapi-server/internal/domains/user/services"
"tyapi-server/internal/shared/database"
esign_service "tyapi-server/internal/shared/esign"
)
// CertificationApplicationServiceImpl 认证应用服务实现
// 负责业务流程编排、事务管理、数据转换,不直接操作仓库
type CertificationApplicationServiceImpl struct {
certRepo repositories.CertificationRepository
licenseRepo repositories.LicenseUploadRecordRepository
faceVerifyRepo repositories.FaceVerifyRecordRepository
contractRepo repositories.ContractRecordRepository
certService *services.CertificationService
stateMachine *services.CertificationStateMachine
storageService storage.StorageService
ocrService ocr.OCRService
enterpriseInfoRepo user_repositories.EnterpriseInfoRepository
logger *zap.Logger
certManagementService *services.CertificationManagementService
certWorkflowService *services.CertificationWorkflowService
certificationEsignService *services.CertificationEsignService
enterpriseService *user_services.EnterpriseService
esignService *esign_service.Client
enterpriseRecordService *services.EnterpriseInfoSubmitRecordService
smsCodeService *user_services.SMSCodeService
txManager *database.TransactionManager
logger *zap.Logger
}
// NewCertificationApplicationService 创建认证应用服务
func NewCertificationApplicationService(
certRepo repositories.CertificationRepository,
licenseRepo repositories.LicenseUploadRecordRepository,
faceVerifyRepo repositories.FaceVerifyRecordRepository,
contractRepo repositories.ContractRecordRepository,
certService *services.CertificationService,
stateMachine *services.CertificationStateMachine,
storageService storage.StorageService,
ocrService ocr.OCRService,
enterpriseInfoRepo user_repositories.EnterpriseInfoRepository,
certManagementService *services.CertificationManagementService,
certWorkflowService *services.CertificationWorkflowService,
certificationEsignService *services.CertificationEsignService,
enterpriseService *user_services.EnterpriseService,
esignService *esign_service.Client,
enterpriseRecordService *services.EnterpriseInfoSubmitRecordService,
smsCodeService *user_services.SMSCodeService,
txManager *database.TransactionManager,
logger *zap.Logger,
) CertificationApplicationService {
return &CertificationApplicationServiceImpl{
certRepo: certRepo,
licenseRepo: licenseRepo,
faceVerifyRepo: faceVerifyRepo,
contractRepo: contractRepo,
certService: certService,
stateMachine: stateMachine,
storageService: storageService,
ocrService: ocrService,
enterpriseInfoRepo: enterpriseInfoRepo,
logger: logger,
certManagementService: certManagementService,
certWorkflowService: certWorkflowService,
certificationEsignService: certificationEsignService,
enterpriseService: enterpriseService,
esignService: esignService,
enterpriseRecordService: enterpriseRecordService,
smsCodeService: smsCodeService,
txManager: txManager,
logger: logger,
}
}
// CreateCertification 创建认证申请
func (s *CertificationApplicationServiceImpl) CreateCertification(ctx context.Context, cmd *commands.CreateCertificationCommand) (*responses.CertificationResponse, error) {
// 使用领域服务创建认证申请
certification, err := s.certService.CreateCertification(ctx, cmd.UserID)
if err != nil {
return nil, err
// SubmitEnterpriseInfo 提交企业信息
// 业务流程1. 验证企业信息 2. 创建或获取认证申请 3. 使用事务执行状态转换和创建记录
func (s *CertificationApplicationServiceImpl) SubmitEnterpriseInfo(ctx context.Context, cmd *commands.SubmitEnterpriseInfoCommand) (*responses.CertificationResponse, error) {
// 1. 验证短信验证码
if err := s.smsCodeService.VerifyCode(ctx, cmd.LegalPersonPhone, cmd.VerificationCode, user_entities.SMSSceneCertification); err != nil {
return nil, fmt.Errorf("验证码错误或已过期")
}
// 构建响应
response := &responses.CertificationResponse{
ID: certification.ID,
UserID: certification.UserID,
Status: certification.Status,
StatusName: string(certification.Status),
Progress: certification.GetProgressPercentage(),
IsUserActionRequired: certification.IsUserActionRequired(),
IsAdminActionRequired: certification.IsAdminActionRequired(),
InfoSubmittedAt: certification.InfoSubmittedAt,
FaceVerifiedAt: certification.FaceVerifiedAt,
ContractAppliedAt: certification.ContractAppliedAt,
ContractApprovedAt: certification.ContractApprovedAt,
ContractSignedAt: certification.ContractSignedAt,
CompletedAt: certification.CompletedAt,
ContractURL: certification.ContractURL,
SigningURL: certification.SigningURL,
RejectReason: certification.RejectReason,
CreatedAt: certification.CreatedAt,
UpdatedAt: certification.UpdatedAt,
}
s.logger.Info("认证申请创建成功",
zap.String("certification_id", certification.ID),
zap.String("user_id", cmd.UserID),
)
return response, nil
}
// CreateEnterpriseInfo 创建企业信息
func (s *CertificationApplicationServiceImpl) CreateEnterpriseInfo(ctx context.Context, cmd *commands.CreateEnterpriseInfoCommand) (*responses.EnterpriseInfoResponse, error) {
// 检查用户是否已有企业信息
existingInfo, err := s.enterpriseInfoRepo.GetByUserID(ctx, cmd.UserID)
if err == nil && existingInfo != nil {
return nil, fmt.Errorf("用户已有企业信息")
}
// 检查统一社会信用代码是否已存在
exists, err := s.enterpriseInfoRepo.CheckUnifiedSocialCodeExists(ctx, cmd.UnifiedSocialCode, "")
// 2. 验证企业信息(检查统一社会信用代码是否已存在)
exists, err := s.enterpriseService.CheckUnifiedSocialCodeExists(ctx, cmd.UnifiedSocialCode, "")
if err != nil {
return nil, fmt.Errorf("检查企业信息失败: %w", err)
}
@@ -115,494 +77,379 @@ func (s *CertificationApplicationServiceImpl) CreateEnterpriseInfo(ctx context.C
return nil, fmt.Errorf("统一社会信用代码已存在")
}
// 创建企业信息
enterpriseInfo := &user_entities.EnterpriseInfo{
UserID: cmd.UserID,
CompanyName: cmd.CompanyName,
UnifiedSocialCode: cmd.UnifiedSocialCode,
LegalPersonName: cmd.LegalPersonName,
LegalPersonID: cmd.LegalPersonID,
// 3. 获取或创建认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, cmd.UserID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
certification, err = s.certManagementService.CreateCertification(ctx, cmd.UserID)
if err != nil {
return nil, fmt.Errorf("创建认证申请失败: %w", err)
}
} else {
return nil, fmt.Errorf("获取认证申请失败: %w", err)
}
}
createdEnterpriseInfo, err := s.enterpriseInfoRepo.Create(ctx, *enterpriseInfo)
if err != nil {
s.logger.Error("创建企业信息失败", zap.Error(err))
return nil, fmt.Errorf("创建企业信息失败: %w", err)
// 4. 创建记录
if certification.Status != enums.StatusPending && certification.Status != enums.StatusInfoSubmitted {
return nil, fmt.Errorf("当前状态不允许提交企业信息")
}
s.logger.Info("企业信息创建成功",
_, err = s.enterpriseRecordService.CreateEnterpriseInfoSubmitRecord(ctx, cmd.UserID, cmd.CompanyName, cmd.UnifiedSocialCode, cmd.LegalPersonName, cmd.LegalPersonID, cmd.LegalPersonPhone)
if err != nil {
return nil, fmt.Errorf("企业信息提交失败: %w", err)
}
s.logger.Info("企业信息提交成功",
zap.String("user_id", cmd.UserID),
zap.String("enterprise_id", enterpriseInfo.ID),
zap.String("certification_id", certification.ID),
zap.String("company_name", cmd.CompanyName),
)
return &responses.EnterpriseInfoResponse{
ID: createdEnterpriseInfo.ID,
CompanyName: enterpriseInfo.CompanyName,
UnifiedSocialCode: enterpriseInfo.UnifiedSocialCode,
LegalPersonName: enterpriseInfo.LegalPersonName,
LegalPersonID: enterpriseInfo.LegalPersonID,
IsOCRVerified: enterpriseInfo.IsOCRVerified,
IsFaceVerified: enterpriseInfo.IsFaceVerified,
CreatedAt: enterpriseInfo.CreatedAt,
UpdatedAt: enterpriseInfo.UpdatedAt,
}, nil
// 转换状态
err = s.certWorkflowService.SubmitEnterpriseInfo(ctx, certification.ID)
if err != nil {
return nil, fmt.Errorf("转换状态失败: %w", err)
}
// 5. 检查企业是否已经认证
hasCertification, err := s.certManagementService.CheckCertification(ctx, cmd.CompanyName, cmd.UnifiedSocialCode)
if err != nil {
return nil, fmt.Errorf("检查企业认证状态失败: %w", err)
}
if hasCertification {
// 如果企业已经认证,则直接完成认证
err = s.completeEnterpriseAuth(ctx, certification)
if err != nil {
return nil, fmt.Errorf("完成企业认证失败: %w", err)
}
}
// 6. 重新获取认证申请数据
certification, err = s.certManagementService.GetCertificationByID(ctx, certification.ID)
if err != nil {
return nil, fmt.Errorf("获取认证申请失败: %w", err)
}
return s.buildCertificationResponse(certification), nil
}
// UploadLicense 上传营业执照
func (s *CertificationApplicationServiceImpl) UploadLicense(ctx context.Context, cmd *commands.UploadLicenseCommand) (*responses.UploadLicenseResponse, error) {
// 1. 业务规则验证 - 调用领域服务
if err := s.certService.ValidateLicenseUpload(ctx, cmd.UserID, cmd.FileName, cmd.FileSize); err != nil {
return nil, err
}
// 2. 上传文件到存储服务
uploadResult, err := s.storageService.UploadFile(ctx, cmd.FileBytes, cmd.FileName)
if err != nil {
s.logger.Error("上传营业执照失败", zap.Error(err))
return nil, fmt.Errorf("上传营业执照失败: %w", err)
}
// 3. 创建营业执照上传记录 - 调用领域服务
licenseRecord, err := s.certService.CreateLicenseUploadRecord(ctx, cmd.UserID, cmd.FileName, cmd.FileSize, uploadResult)
if err != nil {
s.logger.Error("创建营业执照记录失败", zap.Error(err))
return nil, fmt.Errorf("创建营业执照记录失败: %w", err)
}
// 4. 异步处理OCR识别 - 使用任务队列或后台任务
go s.processOCRAsync(ctx, licenseRecord.ID, cmd.FileBytes)
s.logger.Info("营业执照上传成功",
zap.String("user_id", cmd.UserID),
zap.String("license_id", licenseRecord.ID),
zap.String("file_url", uploadResult.URL),
)
// 5. 构建响应
response := &responses.UploadLicenseResponse{
UploadRecordID: licenseRecord.ID,
FileURL: uploadResult.URL,
OCRProcessed: false,
OCRSuccess: false,
}
// 6. 如果OCR处理很快完成尝试获取结果
// 这里可以添加一个简单的轮询机制或者使用WebSocket推送结果
// 暂时返回基础信息前端可以通过查询接口获取OCR结果
return response, nil
}
// UploadBusinessLicense 上传营业执照并同步OCR识别
func (s *CertificationApplicationServiceImpl) UploadBusinessLicense(ctx context.Context, userID string, fileBytes []byte, fileName string) (*responses.UploadLicenseResponse, error) {
s.logger.Info("开始处理营业执照上传",
zap.String("user_id", userID),
zap.String("file_name", fileName),
)
// 调用领域服务进行上传和OCR识别
uploadRecord, ocrResult, err := s.certService.UploadBusinessLicense(ctx, userID, fileBytes, fileName)
if err != nil {
s.logger.Error("营业执照上传失败", zap.Error(err))
return nil, err
}
// 构建响应
response := &responses.UploadLicenseResponse{
UploadRecordID: uploadRecord.ID,
FileURL: uploadRecord.FileURL,
OCRProcessed: uploadRecord.OCRProcessed,
OCRSuccess: uploadRecord.OCRSuccess,
OCRConfidence: uploadRecord.OCRConfidence,
OCRErrorMessage: uploadRecord.OCRErrorMessage,
}
// 如果OCR成功添加识别结果
if ocrResult != nil && uploadRecord.OCRSuccess {
response.EnterpriseName = ocrResult.CompanyName
response.CreditCode = ocrResult.UnifiedSocialCode
response.LegalPerson = ocrResult.LegalPersonName
}
s.logger.Info("营业执照上传完成",
zap.String("user_id", userID),
zap.String("upload_record_id", uploadRecord.ID),
zap.Bool("ocr_success", uploadRecord.OCRSuccess),
)
return response, nil
}
// SubmitEnterpriseInfo 提交企业信息
func (s *CertificationApplicationServiceImpl) SubmitEnterpriseInfo(ctx context.Context, cmd *commands.SubmitEnterpriseInfoCommand) (*responses.EnterpriseInfoResponse, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, cmd.UserID)
// GetEnterpriseAuthURL 获取企业认证链接
// 业务流程1. 获取认证申请 2. 获取企业信息提交记录 3. 生成e签宝认证文件 4. 返回认证链接
func (s *CertificationApplicationServiceImpl) GetEnterpriseAuthURL(ctx context.Context, userID string) (*responses.EnterpriseAuthURLResponse, error) {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, userID)
if err != nil {
return nil, fmt.Errorf("用户尚未创建认证申请: %w", err)
}
// 设置认证ID
cmd.CertificationID = certification.ID
// 2. 检查认证状态
if certification.Status != enums.StatusInfoSubmitted {
return nil, fmt.Errorf("当前状态不允许进行企业认证")
}
// 调用领域服务提交企业信息
if err := s.certService.SubmitEnterpriseInfo(ctx, certification.ID); err != nil {
// 3. 获取企业信息提交记录
enterpriseRecord, err := s.enterpriseRecordService.GetLatestByUserID(ctx, userID)
if err != nil {
return nil, fmt.Errorf("获取企业信息失败: %w", err)
}
// 4. 生成e签宝认证文件
authReq := &esign_service.EnterpriseAuthRequest{
CompanyName: enterpriseRecord.CompanyName,
UnifiedSocialCode: enterpriseRecord.UnifiedSocialCode,
LegalPersonName: enterpriseRecord.LegalPersonName,
LegalPersonID: enterpriseRecord.LegalPersonID,
TransactorName: enterpriseRecord.LegalPersonName,
TransactorMobile: enterpriseRecord.LegalPersonPhone,
TransactorID: enterpriseRecord.LegalPersonID,
}
authResp, err := s.esignService.GenerateEnterpriseAuth(authReq)
if err != nil {
s.logger.Error("生成企业认证文件失败",
zap.String("user_id", userID),
zap.String("certification_id", certification.ID),
zap.Error(err),
)
return nil, fmt.Errorf("生成企业认证文件失败: %w", err)
}
s.logger.Info("获取企业认证链接成功",
zap.String("user_id", userID),
zap.String("certification_id", certification.ID),
zap.String("esign_flow_id", authResp.AuthFlowID),
)
return &responses.EnterpriseAuthURLResponse{
AuthURL: authResp.AuthURL,
ShortURL: authResp.AuthShortURL,
ExpireAt: time.Now().AddDate(0, 0, 7).Format(time.RFC3339),
}, nil
}
// ApplyContract 申请合同文件
// 业务流程1. 获取认证申请 2. 获取企业信息 3. 生成e签宝合同文件
func (s *CertificationApplicationServiceImpl) ApplyContract(ctx context.Context, userID string) (*responses.CertificationResponse, error) {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, userID)
if err != nil {
return nil, fmt.Errorf("用户尚未创建认证申请: %w", err)
}
// 2. 获取企业信息
enterpriseInfo, err := s.enterpriseService.GetEnterpriseInfo(ctx, userID)
if err != nil {
return nil, fmt.Errorf("获取企业信息失败: %w", err)
}
// 4. 生成e签宝合同
components := map[string]string{
"JFQY": "海南学宇思网络科技有限公司",
"JFFR": "刘福思",
"YFQY": enterpriseInfo.CompanyName,
"YFFR": enterpriseInfo.LegalPersonName,
"QDRQ": time.Now().Format("2006-01-02"),
}
_, err = s.certificationEsignService.FillTemplate(ctx, certification, components)
if err != nil {
return nil, fmt.Errorf("生成e签宝合同失败: %w", err)
}
// 6. 重新获取更新后的认证申请数据
updatedCertification, err := s.certManagementService.GetCertificationByID(ctx, certification.ID)
if err != nil {
return nil, err
}
return s.buildCertificationResponse(updatedCertification), nil
}
// GetContractSignURL 获取合同签署链接
// 业务流程1. 获取认证申请 2. 获取企业信息 3. 获取签署链接
func (s *CertificationApplicationServiceImpl) GetContractSignURL(ctx context.Context, cmd *commands.GetContractSignURLCommand) (*responses.ContractSignURLResponse, error) {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, cmd.UserID)
if err != nil {
return nil, fmt.Errorf("用户尚未创建认证申请: %w", err)
}
// 2. 检查认证状态
if certification.Status != enums.StatusContractApplied {
return nil, fmt.Errorf("当前状态不允许获取签署链接")
}
// 3. 获取企业信息
enterpriseInfo, err := s.enterpriseService.GetEnterpriseInfo(ctx, cmd.UserID)
if err != nil {
return nil, fmt.Errorf("获取企业信息失败: %w", err)
}
if certification.ContractFileID == "" {
return nil, fmt.Errorf("请先申请合同文件")
}
// 5. 发起签署
signRecord, err := s.certificationEsignService.InitiateSign(ctx, certification, enterpriseInfo)
if err != nil {
return nil, fmt.Errorf("获取签署链接失败: %w", err)
}
// 转换状态
err = s.certWorkflowService.ApplyContract(ctx, certification.ID)
if err != nil {
return nil, fmt.Errorf("转换状态失败: %w", err)
}
// 6. 计算过期时间7天后
expireAt := time.Now().AddDate(0, 0, 7).Format(time.RFC3339)
s.logger.Info("获取签署链接成功",
zap.String("user_id", cmd.UserID),
zap.String("certification_id", certification.ID),
zap.String("sign_flow_id", signRecord.EsignFlowID),
)
return &responses.ContractSignURLResponse{
SignURL: signRecord.SignURL,
ShortURL: signRecord.SignShortURL,
SignFlowID: signRecord.EsignFlowID,
ExpireAt: expireAt,
}, nil
}
// CompleteContractSign 完成合同签署
// 业务流程1. 获取认证申请 2. 完成合同签署 3. 自动完成认证
func (s *CertificationApplicationServiceImpl) CompleteContractSign(ctx context.Context, cmd *commands.CompleteContractSignCommand) error {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, cmd.UserID)
if err != nil {
return fmt.Errorf("用户尚未创建认证申请: %w", err)
}
if certification.Status != enums.StatusContractApplied {
return fmt.Errorf("当前状态不允许完成合同签署")
}
// 2. 完成合同签署(状态转换)
if err := s.certWorkflowService.CompleteContractSign(ctx, certification.ID, cmd.ContractURL); err != nil {
return err
}
// 3. 重新获取认证申请
updatedCertification, err := s.certManagementService.GetCertificationByID(ctx, certification.ID)
if err != nil {
return err
}
// 4. 如果合同已签署,自动完成认证
if updatedCertification.Status == enums.StatusContractSigned {
if err := s.certWorkflowService.CompleteCertification(ctx, certification.ID); err != nil {
return err
}
}
s.logger.Info("合同签署完成",
zap.String("user_id", cmd.UserID),
zap.String("certification_id", certification.ID),
zap.String("contract_url", cmd.ContractURL),
)
return nil
}
// GetCertificationStatus 获取认证状态
// 业务流程1. 获取认证申请 2. 构建响应数据
func (s *CertificationApplicationServiceImpl) GetCertificationStatus(ctx context.Context, query *queries.GetCertificationStatusQuery) (*responses.CertificationResponse, error) {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, query.UserID)
if err != nil {
// 如果用户没有认证申请,返回一个表示未开始的状态
if errors.Is(err, gorm.ErrRecordNotFound) {
return &responses.CertificationResponse{
ID: "",
UserID: query.UserID,
Status: "not_started",
StatusName: "未开始认证",
Progress: 0,
IsUserActionRequired: true,
InfoSubmittedAt: nil,
EnterpriseVerifiedAt: nil,
ContractAppliedAt: nil,
ContractSignedAt: nil,
CompletedAt: nil,
ContractURL: "",
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
}, nil
}
return nil, err
}
// 创建企业信息
enterpriseInfo := &user_entities.EnterpriseInfo{
UserID: cmd.UserID,
CompanyName: cmd.CompanyName,
UnifiedSocialCode: cmd.UnifiedSocialCode,
LegalPersonName: cmd.LegalPersonName,
LegalPersonID: cmd.LegalPersonID,
}
// 2. 构建响应
return s.buildCertificationResponse(certification), nil
}
*enterpriseInfo, err = s.enterpriseInfoRepo.Create(ctx, *enterpriseInfo)
// GetCertificationDetails 获取认证详情
// 业务流程1. 获取认证申请 2. 获取企业信息 3. 构建响应数据
func (s *CertificationApplicationServiceImpl) GetCertificationDetails(ctx context.Context, query *queries.GetCertificationDetailsQuery) (*responses.CertificationResponse, error) {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, query.UserID)
if err != nil {
s.logger.Error("创建企业信息失败", zap.Error(err))
return nil, fmt.Errorf("创建企业信息失败: %w", err)
// 如果用户没有认证申请,返回错误
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("用户尚未创建认证申请")
}
return nil, err
}
s.logger.Info("企业信息提交成功",
zap.String("user_id", cmd.UserID),
zap.String("certification_id", certification.ID),
zap.String("enterprise_id", enterpriseInfo.ID),
)
// 2. 构建响应
response := s.buildCertificationResponse(certification)
// 3. 添加企业信息
if certification.UserID != "" {
enterpriseInfo, err := s.enterpriseService.GetEnterpriseInfo(ctx, certification.UserID)
if err == nil && enterpriseInfo != nil {
response.Enterprise = s.buildEnterpriseInfoResponse(enterpriseInfo)
}
}
return response, nil
}
// GetCertificationProgress 获取认证进度
// 业务流程1. 获取认证申请 2. 获取进度信息
func (s *CertificationApplicationServiceImpl) GetCertificationProgress(ctx context.Context, userID string) (map[string]interface{}, error) {
// 1. 获取认证申请
certification, err := s.certManagementService.GetCertificationByUserID(ctx, userID)
if err != nil {
// 如果用户没有认证申请,返回未开始状态
if errors.Is(err, gorm.ErrRecordNotFound) {
return map[string]interface{}{
"certification_id": "",
"user_id": userID,
"current_status": "not_started",
"status_name": "未开始认证",
"progress_percentage": 0,
"is_user_action_required": true,
"next_valid_statuses": []string{"pending"},
"message": "用户尚未开始认证流程",
"created_at": nil,
"updated_at": nil,
}, nil
}
return nil, err
}
// 2. 获取认证进度
return s.certManagementService.GetCertificationProgress(ctx, certification.ID)
}
// buildCertificationResponse 构建认证响应
func (s *CertificationApplicationServiceImpl) buildCertificationResponse(certification *entities.Certification) *responses.CertificationResponse {
return &responses.CertificationResponse{
ID: certification.ID,
UserID: certification.UserID,
Status: certification.Status,
StatusName: certification.GetStatusName(),
Progress: certification.GetProgressPercentage(),
IsUserActionRequired: certification.IsUserActionRequired(),
InfoSubmittedAt: certification.InfoSubmittedAt,
EnterpriseVerifiedAt: certification.EnterpriseVerifiedAt,
ContractAppliedAt: certification.ContractAppliedAt,
ContractSignedAt: certification.ContractSignedAt,
CompletedAt: certification.CompletedAt,
ContractURL: certification.ContractURL,
CreatedAt: certification.CreatedAt,
UpdatedAt: certification.UpdatedAt,
}
}
// buildEnterpriseInfoResponse 构建企业信息响应
func (s *CertificationApplicationServiceImpl) buildEnterpriseInfoResponse(enterpriseInfo *user_entities.EnterpriseInfo) *responses.EnterpriseInfoResponse {
return &responses.EnterpriseInfoResponse{
ID: enterpriseInfo.ID,
CompanyName: enterpriseInfo.CompanyName,
UnifiedSocialCode: enterpriseInfo.UnifiedSocialCode,
LegalPersonName: enterpriseInfo.LegalPersonName,
LegalPersonID: enterpriseInfo.LegalPersonID,
IsOCRVerified: enterpriseInfo.IsOCRVerified,
IsFaceVerified: enterpriseInfo.IsFaceVerified,
CreatedAt: enterpriseInfo.CreatedAt,
UpdatedAt: enterpriseInfo.UpdatedAt,
}, nil
}
}
// InitiateFaceVerify 发起人脸识别验证
func (s *CertificationApplicationServiceImpl) InitiateFaceVerify(ctx context.Context, cmd *commands.InitiateFaceVerifyCommand) (*responses.FaceVerifyResponse, error) {
// 根据用户ID获取认证申请 - 这里需要从Handler传入用户ID
// 由于cmd中没有UserID字段我们需要修改Handler的调用方式
// 暂时使用certificationID来获取认证申请
certification, err := s.certRepo.GetByID(ctx, cmd.CertificationID)
if err != nil {
return nil, fmt.Errorf("认证申请不存在: %w", err)
}
// 调用领域服务发起人脸识别
faceVerifyRecord, err := s.certService.InitiateFaceVerify(ctx, certification.ID, cmd.RealName, cmd.IDCardNumber)
if err != nil {
return nil, err
}
// 构建验证URL这里应该根据实际的人脸识别服务生成
verifyURL := fmt.Sprintf("/api/certification/face-verify/%s?return_url=%s", faceVerifyRecord.ID, cmd.ReturnURL)
s.logger.Info("人脸识别验证发起成功",
zap.String("certification_id", certification.ID),
zap.String("face_verify_id", faceVerifyRecord.ID),
)
return &responses.FaceVerifyResponse{
CertifyID: faceVerifyRecord.ID,
VerifyURL: verifyURL,
ExpiresAt: faceVerifyRecord.ExpiresAt,
}, nil
}
// ApplyContract 申请合同
func (s *CertificationApplicationServiceImpl) ApplyContract(ctx context.Context, userID string) (*responses.CertificationResponse, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, userID)
if err != nil {
return nil, fmt.Errorf("用户尚未创建认证申请: %w", err)
}
// 调用领域服务申请合同
if err := s.certService.ApplyContract(ctx, certification.ID); err != nil {
return nil, err
}
// 重新获取更新后的认证申请
updatedCertification, err := s.certRepo.GetByID(ctx, certification.ID)
if err != nil {
return nil, err
}
s.logger.Info("合同申请成功",
zap.String("user_id", userID),
zap.String("certification_id", certification.ID),
)
return s.buildCertificationResponse(&updatedCertification), nil
}
// GetCertificationStatus 获取认证状态
func (s *CertificationApplicationServiceImpl) GetCertificationStatus(ctx context.Context, query *queries.GetCertificationStatusQuery) (*responses.CertificationResponse, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, query.UserID)
if err != nil {
// 如果用户没有认证申请,返回一个表示未开始的状态
if err.Error() == "认证申请不存在" || err.Error() == "record not found" {
return &responses.CertificationResponse{
ID: "",
UserID: query.UserID,
Status: "not_started",
StatusName: "未开始认证",
Progress: 0,
IsUserActionRequired: true,
IsAdminActionRequired: false,
InfoSubmittedAt: nil,
FaceVerifiedAt: nil,
ContractAppliedAt: nil,
ContractApprovedAt: nil,
ContractSignedAt: nil,
CompletedAt: nil,
ContractURL: "",
SigningURL: "",
RejectReason: "",
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
}, nil
// 企业认证成功后操作
func (s *CertificationApplicationServiceImpl) completeEnterpriseAuth(ctx context.Context, certification *entities.Certification) error {
err := s.txManager.ExecuteInTx(ctx, func(txCtx context.Context) error {
// 1. 获取企业信息提交记录
enterpriseRecord, err := s.enterpriseRecordService.GetLatestByUserID(txCtx, certification.UserID)
if err != nil {
return fmt.Errorf("获取企业信息失败: %w", err)
}
return nil, err
}
// 构建响应
response := s.buildCertificationResponse(certification)
return response, nil
}
// GetCertificationDetails 获取认证详情
func (s *CertificationApplicationServiceImpl) GetCertificationDetails(ctx context.Context, query *queries.GetCertificationDetailsQuery) (*responses.CertificationResponse, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, query.UserID)
if err != nil {
// 如果用户没有认证申请,返回错误
if err.Error() == "认证申请不存在" || err.Error() == "record not found" {
return nil, fmt.Errorf("用户尚未创建认证申请")
// 2. 转换状态
if err := s.certWorkflowService.CompleteEnterpriseVerification(txCtx, certification.ID); err != nil {
return err
}
return nil, err
}
// 获取认证申请详细信息
certificationWithDetails, err := s.certService.GetCertificationWithDetails(ctx, certification.ID)
if err != nil {
return nil, err
}
// 构建响应
response := s.buildCertificationResponse(certificationWithDetails)
// 添加企业信息
if certification.UserID != "" {
enterpriseInfo, err := s.enterpriseInfoRepo.GetByUserID(ctx, certification.UserID)
if err == nil && enterpriseInfo != nil {
response.Enterprise = &responses.EnterpriseInfoResponse{
ID: enterpriseInfo.ID,
CompanyName: enterpriseInfo.CompanyName,
UnifiedSocialCode: enterpriseInfo.UnifiedSocialCode,
LegalPersonName: enterpriseInfo.LegalPersonName,
LegalPersonID: enterpriseInfo.LegalPersonID,
IsOCRVerified: enterpriseInfo.IsOCRVerified,
IsFaceVerified: enterpriseInfo.IsFaceVerified,
CreatedAt: enterpriseInfo.CreatedAt,
UpdatedAt: enterpriseInfo.UpdatedAt,
}
// 3. 创建企业信息
_, err = s.enterpriseService.CreateEnterpriseInfo(txCtx, certification.UserID, enterpriseRecord.CompanyName, enterpriseRecord.UnifiedSocialCode, enterpriseRecord.LegalPersonName, enterpriseRecord.LegalPersonID)
if err != nil {
s.logger.Warn("创建用户企业信息失败", zap.Error(err))
return err
}
}
return response, nil
}
// CompleteFaceVerify 完成人脸识别验证
func (s *CertificationApplicationServiceImpl) CompleteFaceVerify(ctx context.Context, faceVerifyID string, isSuccess bool) error {
return s.certService.CompleteFaceVerify(ctx, faceVerifyID, isSuccess)
}
// ApproveContract 管理员审核合同
func (s *CertificationApplicationServiceImpl) ApproveContract(ctx context.Context, certificationID, adminID, signingURL, approvalNotes string) error {
return s.certService.ApproveContract(ctx, certificationID, adminID, signingURL, approvalNotes)
}
// RejectContract 管理员拒绝合同
func (s *CertificationApplicationServiceImpl) RejectContract(ctx context.Context, certificationID, adminID, rejectReason string) error {
return s.certService.RejectContract(ctx, certificationID, adminID, rejectReason)
}
// CompleteContractSign 完成合同签署
func (s *CertificationApplicationServiceImpl) CompleteContractSign(ctx context.Context, certificationID, contractURL string) error {
return s.certService.CompleteContractSign(ctx, certificationID, contractURL)
}
// CompleteCertification 完成认证
func (s *CertificationApplicationServiceImpl) CompleteCertification(ctx context.Context, certificationID string) error {
return s.certService.CompleteCertification(ctx, certificationID)
}
// RetryStep 重试认证步骤
func (s *CertificationApplicationServiceImpl) RetryStep(ctx context.Context, cmd *commands.RetryStepCommand) error {
switch cmd.Step {
case "face_verify":
return s.certService.RetryFaceVerify(ctx, cmd.CertificationID)
case "restart":
return s.certService.RestartCertification(ctx, cmd.CertificationID)
default:
return fmt.Errorf("不支持的重试步骤: %s", cmd.Step)
}
}
// GetCertificationProgress 获取认证进度
func (s *CertificationApplicationServiceImpl) GetCertificationProgress(ctx context.Context, userID string) (map[string]interface{}, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, userID)
return nil
})
if err != nil {
// 如果用户没有认证申请,返回未开始状态
if err.Error() == "认证申请不存在" || err.Error() == "record not found" {
return map[string]interface{}{
"certification_id": "",
"user_id": userID,
"current_status": "not_started",
"status_name": "未开始认证",
"progress_percentage": 0,
"is_user_action_required": true,
"is_admin_action_required": false,
"next_valid_statuses": []string{"pending"},
"message": "用户尚未开始认证流程",
"created_at": nil,
"updated_at": nil,
}, nil
}
return nil, err
return fmt.Errorf("完成企业认证失败: %w", err)
}
// 获取认证进度
return s.certService.GetCertificationProgress(ctx, certification.ID)
}
// RetryFaceVerify 重试人脸识别
func (s *CertificationApplicationServiceImpl) RetryFaceVerify(ctx context.Context, userID string) (*responses.FaceVerifyResponse, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, userID)
if err != nil {
return nil, fmt.Errorf("用户尚未创建认证申请: %w", err)
}
// 调用领域服务重试人脸识别
if err := s.certService.RetryFaceVerify(ctx, certification.ID); err != nil {
return nil, err
}
// 重新发起人脸识别
faceVerifyRecord, err := s.certService.InitiateFaceVerify(ctx, certification.ID, "", "")
if err != nil {
return nil, err
}
// 构建验证URL
verifyURL := fmt.Sprintf("/api/certification/face-verify/%s", faceVerifyRecord.ID)
return &responses.FaceVerifyResponse{
CertifyID: faceVerifyRecord.ID,
VerifyURL: verifyURL,
ExpiresAt: faceVerifyRecord.ExpiresAt,
}, nil
}
// RetryContractSign 重试合同签署
func (s *CertificationApplicationServiceImpl) RetryContractSign(ctx context.Context, userID string) (*responses.CertificationResponse, error) {
// 根据用户ID获取认证申请
certification, err := s.certRepo.GetByUserID(ctx, userID)
if err != nil {
return nil, fmt.Errorf("用户尚未创建认证申请: %w", err)
}
// 重新获取更新后的认证申请
updatedCertification, err := s.certRepo.GetByID(ctx, certification.ID)
if err != nil {
return nil, err
}
s.logger.Info("合同签署重试准备完成",
zap.String("user_id", userID),
zap.String("certification_id", certification.ID),
)
return s.buildCertificationResponse(&updatedCertification), nil
}
// RestartCertification 重新开始认证
func (s *CertificationApplicationServiceImpl) RestartCertification(ctx context.Context, certificationID string) error {
return s.certService.RestartCertification(ctx, certificationID)
}
// buildCertificationResponse 构建认证响应
func (s *CertificationApplicationServiceImpl) buildCertificationResponse(certification *entities.Certification) *responses.CertificationResponse {
return &responses.CertificationResponse{
ID: certification.ID,
UserID: certification.UserID,
Status: certification.Status,
StatusName: string(certification.Status),
Progress: certification.GetProgressPercentage(),
IsUserActionRequired: certification.IsUserActionRequired(),
IsAdminActionRequired: certification.IsAdminActionRequired(),
InfoSubmittedAt: certification.InfoSubmittedAt,
FaceVerifiedAt: certification.FaceVerifiedAt,
ContractAppliedAt: certification.ContractAppliedAt,
ContractApprovedAt: certification.ContractApprovedAt,
ContractSignedAt: certification.ContractSignedAt,
CompletedAt: certification.CompletedAt,
ContractURL: certification.ContractURL,
SigningURL: certification.SigningURL,
RejectReason: certification.RejectReason,
CreatedAt: certification.CreatedAt,
UpdatedAt: certification.UpdatedAt,
}
}
// processOCRAsync 异步处理OCR识别
func (s *CertificationApplicationServiceImpl) processOCRAsync(ctx context.Context, licenseID string, fileBytes []byte) {
// 调用领域服务处理OCR识别
if err := s.certService.ProcessOCRAsync(ctx, licenseID, fileBytes); err != nil {
s.logger.Error("OCR处理失败",
zap.String("license_id", licenseID),
zap.Error(err),
)
}
}
// GetLicenseOCRResult 获取营业执照OCR识别结果
func (s *CertificationApplicationServiceImpl) GetLicenseOCRResult(ctx context.Context, recordID string) (*responses.UploadLicenseResponse, error) {
// 获取营业执照上传记录
licenseRecord, err := s.licenseRepo.GetByID(ctx, recordID)
if err != nil {
s.logger.Error("获取营业执照记录失败", zap.Error(err))
return nil, fmt.Errorf("获取营业执照记录失败: %w", err)
}
// 构建响应
response := &responses.UploadLicenseResponse{
UploadRecordID: licenseRecord.ID,
FileURL: licenseRecord.FileURL,
OCRProcessed: licenseRecord.OCRProcessed,
OCRSuccess: licenseRecord.OCRSuccess,
OCRConfidence: licenseRecord.OCRConfidence,
OCRErrorMessage: licenseRecord.OCRErrorMessage,
}
// 如果OCR成功解析OCR结果
if licenseRecord.OCRSuccess && licenseRecord.OCRRawData != "" {
// 这里可以解析OCR原始数据提取企业信息
// 简化处理,直接返回原始数据中的关键信息
// 实际项目中可以使用JSON解析
response.EnterpriseName = "已识别" // 从OCR数据中提取
response.CreditCode = "已识别" // 从OCR数据中提取
response.LegalPerson = "已识别" // 从OCR数据中提取
}
return response, nil
return nil
}

View File

@@ -1,62 +1,21 @@
package commands
// CreateCertificationCommand 创建认证申请命令
// 用于用户发起企业认证流程的初始请求
type CreateCertificationCommand struct {
UserID string `json:"user_id" binding:"required" comment:"用户唯一标识从JWT token获取"`
}
// UploadLicenseCommand 上传营业执照命令
// 用于处理营业执照文件上传的业务逻辑
type UploadLicenseCommand struct {
UserID string `json:"-" comment:"用户唯一标识从JWT token获取不在JSON中暴露"`
FileBytes []byte `json:"-" comment:"营业执照文件的二进制内容从multipart/form-data获取"`
FileName string `json:"-" comment:"营业执照文件的原始文件名从multipart/form-data获取"`
FileSize int64 `json:"-" comment:"营业执照文件的大小字节从multipart/form-data获取"`
}
// SubmitEnterpriseInfoCommand 提交企业信息命令
// 用于用户提交企业四要素信息,完成企业信息验证
// 如果用户没有认证申请,系统会自动创建
type SubmitEnterpriseInfoCommand struct {
UserID string `json:"-" comment:"用户唯一标识从JWT token获取不在JSON中暴露"`
CertificationID string `json:"-" comment:"认证申请唯一标识从URL路径获取不在JSON中暴露"`
CompanyName string `json:"company_name" binding:"required" comment:"企业名称,如:北京科技有限公司"`
UnifiedSocialCode string `json:"unified_social_code" binding:"required" comment:"统一社会信用代码18位企业唯一标识91110000123456789X"`
LegalPersonName string `json:"legal_person_name" binding:"required" comment:"法定代表人姓名,如:张三"`
LegalPersonID string `json:"legal_person_id" binding:"required" comment:"法定代表人身份证号码18位110101199001011234"`
LicenseUploadRecordID string `json:"license_upload_record_id" binding:"required" comment:"营业执照上传记录唯一标识,关联已上传的营业执照文件"`
}
// InitiateFaceVerifyCommand 初始化人脸识别命令
// 用于发起人脸识别验证流程,验证法定代表人身份
type InitiateFaceVerifyCommand struct {
CertificationID string `json:"-" comment:"认证申请唯一标识从URL路径获取不在JSON中暴露"`
RealName string `json:"real_name" binding:"required" comment:"真实姓名,必须与营业执照上的法定代表人姓名一致"`
IDCardNumber string `json:"id_card_number" binding:"required" comment:"身份证号码18位用于人脸识别身份验证"`
ReturnURL string `json:"return_url" binding:"required" comment:"人脸识别完成后的回调地址,用于跳转回应用"`
}
// ApplyContractCommand 申请合同命令
// 用于用户申请电子合同,进入合同签署流程
type ApplyContractCommand struct {
CertificationID string `json:"-" comment:"认证申请唯一标识从URL路径获取不在JSON中暴露"`
}
// RetryStepCommand 重试认证步骤命令
// 用于用户重试失败的认证步骤,如人脸识别失败后的重试
type RetryStepCommand struct {
UserID string `json:"-" comment:"用户唯一标识从JWT token获取不在JSON中暴露"`
CertificationID string `json:"-" comment:"认证申请唯一标识从URL路径获取不在JSON中暴露"`
Step string `json:"step" binding:"required" comment:"重试的步骤名称face_verify人脸识别、contract_sign合同签署"`
}
// CreateEnterpriseInfoCommand 创建企业信息命令
// 用于创建企业基本信息,通常在企业认证流程中使用
// @Description 创建企业信息请求参数
type CreateEnterpriseInfoCommand struct {
UserID string `json:"-" comment:"用户唯一标识从JWT token获取不在JSON中暴露"`
CompanyName string `json:"company_name" binding:"required" example:"示例企业有限公司" comment:"企业名称,如:示例企业有限公司"`
UnifiedSocialCode string `json:"unified_social_code" binding:"required" example:"91110000123456789X" comment:"统一社会信用代码18位企业唯一标识91110000123456789X"`
LegalPersonName string `json:"legal_person_name" binding:"required" example:"张三" comment:"法定代表人姓名,如:张三"`
LegalPersonID string `json:"legal_person_id" binding:"required" example:"110101199001011234" comment:"法定代表人身份证号码18位110101199001011234"`
CompanyName string `json:"company_name" binding:"required,min=2,max=100" comment:"企业名称,如:北京科技有限公司"`
UnifiedSocialCode string `json:"unified_social_code" binding:"required,social_credit_code" comment:"统一社会信用代码18位企业唯一标识91110000123456789X"`
LegalPersonName string `json:"legal_person_name" binding:"required,min=2,max=20" comment:"法定代表人姓名,如:张三"`
LegalPersonID string `json:"legal_person_id" binding:"required,id_card" comment:"法定代表人身份证号码18位110101199001011234"`
LegalPersonPhone string `json:"legal_person_phone" binding:"required,phone" comment:"法定代表人手机号11位13800138000"`
VerificationCode string `json:"verification_code" binding:"required,len=6" comment:"验证码"`
}
// CompleteContractSignCommand 完成合同签署命令
// 用于用户完成合同签署提交合同URL
type CompleteContractSignCommand struct {
UserID string `json:"-" comment:"用户唯一标识从JWT token获取不在JSON中暴露"`
ContractURL string `json:"contract_url" binding:"required,url,min=10,max=500" comment:"合同签署后的URL地址"`
}

View File

@@ -0,0 +1,6 @@
package commands
// GetContractSignURLCommand 获取合同签署链接命令
type GetContractSignURLCommand struct {
UserID string `json:"user_id" binding:"required,uuid" comment:"用户ID"`
}

View File

@@ -3,11 +3,11 @@ package queries
// GetCertificationStatusQuery 获取认证状态查询
// 用于查询用户当前认证申请的进度状态
type GetCertificationStatusQuery struct {
UserID string `json:"user_id" binding:"required" comment:"用户唯一标识,用于查询该用户的认证申请状态"`
UserID string `json:"user_id" binding:"required,uuid" comment:"用户唯一标识,用于查询该用户的认证申请状态"`
}
// GetCertificationDetailsQuery 获取认证详情查询
// 用于查询用户认证申请的详细信息,包括所有相关记录
type GetCertificationDetailsQuery struct {
UserID string `json:"user_id" binding:"required" comment:"用户唯一标识,用于查询该用户的认证申请详细信息"`
UserID string `json:"user_id" binding:"required,uuid" comment:"用户唯一标识,用于查询该用户的认证申请详细信息"`
}

View File

@@ -8,59 +8,38 @@ import (
// CertificationResponse 认证响应
type CertificationResponse struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Status enums.CertificationStatus `json:"status"`
StatusName string `json:"status_name"`
Progress int `json:"progress"`
IsUserActionRequired bool `json:"is_user_action_required"`
IsAdminActionRequired bool `json:"is_admin_action_required"`
InfoSubmittedAt *time.Time `json:"info_submitted_at,omitempty"`
FaceVerifiedAt *time.Time `json:"face_verified_at,omitempty"`
ContractAppliedAt *time.Time `json:"contract_applied_at,omitempty"`
ContractApprovedAt *time.Time `json:"contract_approved_at,omitempty"`
ContractSignedAt *time.Time `json:"contract_signed_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Enterprise *EnterpriseInfoResponse `json:"enterprise,omitempty"`
ContractURL string `json:"contract_url,omitempty"`
SigningURL string `json:"signing_url,omitempty"`
RejectReason string `json:"reject_reason,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
UserID string `json:"user_id"`
Status enums.CertificationStatus `json:"status"`
StatusName string `json:"status_name"`
Progress int `json:"progress"`
IsUserActionRequired bool `json:"is_user_action_required"`
InfoSubmittedAt *time.Time `json:"info_submitted_at,omitempty"`
EnterpriseVerifiedAt *time.Time `json:"enterprise_verified_at,omitempty"`
ContractAppliedAt *time.Time `json:"contract_applied_at,omitempty"`
ContractSignedAt *time.Time `json:"contract_signed_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Enterprise *EnterpriseInfoResponse `json:"enterprise,omitempty"`
ContractURL string `json:"contract_url,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// EnterpriseInfoResponse 企业信息响应
type EnterpriseInfoResponse struct {
ID string `json:"id"`
CertificationID string `json:"certification_id"`
CompanyName string `json:"company_name"`
UnifiedSocialCode string `json:"unified_social_code"`
LegalPersonName string `json:"legal_person_name"`
LegalPersonID string `json:"legal_person_id"`
LicenseUploadRecordID string `json:"license_upload_record_id"`
IsOCRVerified bool `json:"is_ocr_verified"`
IsFaceVerified bool `json:"is_face_verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
CompanyName string `json:"company_name"`
UnifiedSocialCode string `json:"unified_social_code"`
LegalPersonName string `json:"legal_person_name"`
LegalPersonID string `json:"legal_person_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// UploadLicenseResponse 上传营业执照响应
type UploadLicenseResponse struct {
UploadRecordID string `json:"upload_record_id"`
FileURL string `json:"file_url"`
OCRProcessed bool `json:"ocr_processed"`
OCRSuccess bool `json:"ocr_success"`
// OCR识别结果如果成功
EnterpriseName string `json:"enterprise_name,omitempty"`
CreditCode string `json:"credit_code,omitempty"`
LegalPerson string `json:"legal_person,omitempty"`
OCRConfidence float64 `json:"ocr_confidence,omitempty"`
OCRErrorMessage string `json:"ocr_error_message,omitempty"`
}
// FaceVerifyResponse 人脸识别响应
type FaceVerifyResponse struct {
CertifyID string `json:"certify_id"`
VerifyURL string `json:"verify_url"`
ExpiresAt time.Time `json:"expires_at"`
// EnterpriseAuthURLResponse 企业认证链接响应
type EnterpriseAuthURLResponse struct {
EsignFlowID string `json:"esign_flow_id"` // e签宝认证流程ID
AuthURL string `json:"auth_url"` // 认证链接
ShortURL string `json:"short_url"` // 短链接
ExpireAt string `json:"expire_at"` // 过期时间
}

View File

@@ -0,0 +1,9 @@
package responses
// ContractSignURLResponse 合同签署链接响应
type ContractSignURLResponse struct {
SignURL string `json:"sign_url"` // 签署链接
ShortURL string `json:"short_url"` // 短链接
SignFlowID string `json:"sign_flow_id"` // 签署流程ID
ExpireAt string `json:"expire_at"` // 过期时间
}

View File

@@ -0,0 +1,385 @@
package certification
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"go.uber.org/zap"
"tyapi-server/internal/domains/certification/entities"
"tyapi-server/internal/domains/certification/enums"
"tyapi-server/internal/domains/certification/services"
user_services "tyapi-server/internal/domains/user/services"
"tyapi-server/internal/shared/database"
esign_service "tyapi-server/internal/shared/esign"
)
// EsignCallbackData e签宝回调数据结构
type EsignCallbackData struct {
Action string `json:"action"`
Timestamp int64 `json:"timestamp"`
AuthFlowId string `json:"authFlowId,omitempty"`
SignFlowId string `json:"signFlowId,omitempty"`
CustomBizNum string `json:"customBizNum,omitempty"`
SignOrder int `json:"signOrder,omitempty"`
OperateTime int64 `json:"operateTime,omitempty"`
SignResult int `json:"signResult,omitempty"`
ResultDescription string `json:"resultDescription,omitempty"`
AuthType string `json:"authType,omitempty"`
SignFlowStatus string `json:"signFlowStatus,omitempty"`
Operator *EsignOperator `json:"operator,omitempty"`
PsnInfo *EsignPsnInfo `json:"psnInfo,omitempty"`
Organization *EsignOrganization `json:"organization,omitempty"`
}
// EsignOperator 签署人信息
type EsignOperator struct {
PsnId string `json:"psnId"`
PsnAccount *EsignPsnAccount `json:"psnAccount"`
}
// EsignPsnInfo 个人认证信息
type EsignPsnInfo struct {
PsnId string `json:"psnId"`
PsnAccount *EsignPsnAccount `json:"psnAccount"`
}
// EsignPsnAccount 个人账户信息
type EsignPsnAccount struct {
AccountMobile string `json:"accountMobile"`
AccountEmail string `json:"accountEmail"`
}
// EsignOrganization 企业信息
type EsignOrganization struct {
OrgName string `json:"orgName"`
// 可以根据需要添加更多企业信息字段
}
// EsignCallbackApplicationServiceImpl e签宝回调应用服务实现
type EsignCallbackApplicationServiceImpl struct {
certManagementService *services.CertificationManagementService
certWorkflowService *services.CertificationWorkflowService
certificationEsignService *services.CertificationEsignService
enterpriseService *user_services.EnterpriseService
esignService *esign_service.Client
enterpriseRecordService *services.EnterpriseInfoSubmitRecordService
txManager *database.TransactionManager
logger *zap.Logger
}
// NewEsignCallbackApplicationService 创建e签宝回调应用服务
func NewEsignCallbackApplicationService(
certManagementService *services.CertificationManagementService,
certWorkflowService *services.CertificationWorkflowService,
certificationEsignService *services.CertificationEsignService,
enterpriseService *user_services.EnterpriseService,
esignService *esign_service.Client,
enterpriseRecordService *services.EnterpriseInfoSubmitRecordService,
txManager *database.TransactionManager,
logger *zap.Logger,
) EsignCallbackApplicationService {
return &EsignCallbackApplicationServiceImpl{
certManagementService: certManagementService,
certWorkflowService: certWorkflowService,
certificationEsignService: certificationEsignService,
enterpriseService: enterpriseService,
esignService: esignService,
enterpriseRecordService: enterpriseRecordService,
txManager: txManager,
logger: logger,
}
}
// HandleCallback 处理e签宝回调
func (s *EsignCallbackApplicationServiceImpl) HandleCallback(ctx context.Context, callbackData map[string]interface{}, headers map[string]string, queryParams map[string]string) error {
s.logger.Info("开始处理e签宝回调", zap.Any("callback_data", callbackData))
// 1. 验签
if err := s.verifySignature(callbackData, headers, queryParams); err != nil {
s.logger.Error("e签宝回调验签失败", zap.Error(err))
return fmt.Errorf("验签失败: %w", err)
}
// 2. 解析回调数据为结构体
var callback EsignCallbackData
jsonBytes, err := json.Marshal(callbackData)
if err != nil {
return fmt.Errorf("序列化回调数据失败: %w", err)
}
if err := json.Unmarshal(jsonBytes, &callback); err != nil {
return fmt.Errorf("解析回调数据失败: %w", err)
}
// 3. 记录回调信息
s.logger.Info("e签宝回调信息解析",
zap.String("action", callback.Action),
zap.String("auth_flow_id", callback.AuthFlowId),
zap.String("sign_flow_id", callback.SignFlowId),
zap.String("auth_type", callback.AuthType),
zap.String("sign_flow_status", callback.SignFlowStatus),
zap.Int64("timestamp", callback.Timestamp),
)
// 4. 根据回调类型处理业务逻辑
switch callback.Action {
case "AUTH_PASS":
// 只处理企业认证通过
if callback.AuthType == "ORG" {
return s.handleEnterpriseAuthPass(ctx, &callback)
}
s.logger.Info("忽略非企业认证通过回调", zap.String("auth_type", callback.AuthType))
return nil
case "AUTH_FAIL":
// 只处理企业认证失败
if callback.AuthType == "ORG" {
return s.handleEnterpriseAuthFail(ctx, &callback)
}
s.logger.Info("忽略非企业认证失败回调", zap.String("auth_type", callback.AuthType))
return nil
case "SIGN_FLOW_COMPLETE":
// 合同签署流程完成
return s.handleContractSignFlowComplete(ctx, &callback)
default:
s.logger.Info("忽略未知的回调动作", zap.String("action", callback.Action))
return nil
}
}
// verifySignature 验证e签宝回调签名
func (s *EsignCallbackApplicationServiceImpl) verifySignature(callbackData map[string]interface{}, headers map[string]string, queryParams map[string]string) error {
// 1. 获取签名相关参数
signature, ok := headers["X-Tsign-Open-Signature"]
if !ok {
return fmt.Errorf("缺少签名头: X-Tsign-Open-Signature")
}
timestamp, ok := headers["X-Tsign-Open-Timestamp"]
if !ok {
return fmt.Errorf("缺少时间戳头: X-Tsign-Open-Timestamp")
}
// 2. 构建查询参数字符串
var queryKeys []string
for key := range queryParams {
queryKeys = append(queryKeys, key)
}
sort.Strings(queryKeys) // 按ASCII码升序排序
var queryValues []string
for _, key := range queryKeys {
queryValues = append(queryValues, queryParams[key])
}
queryString := strings.Join(queryValues, "")
// 3. 获取请求体数据
bodyData, err := s.getRequestBodyString(callbackData)
if err != nil {
return fmt.Errorf("获取请求体数据失败: %w", err)
}
// 4. 构建验签数据
data := timestamp + queryString + bodyData
// 5. 计算签名
expectedSignature := s.calculateSignature(data, s.esignService.GetConfig().AppSecret)
// 6. 比较签名
if strings.ToLower(expectedSignature) != strings.ToLower(signature) {
s.logger.Error("签名验证失败",
zap.String("expected", strings.ToLower(expectedSignature)),
zap.String("received", strings.ToLower(signature)),
zap.String("data", data),
)
return fmt.Errorf("签名验证失败")
}
s.logger.Info("e签宝回调验签成功")
return nil
}
// calculateSignature 计算HMAC-SHA256签名
func (s *EsignCallbackApplicationServiceImpl) calculateSignature(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
}
// getRequestBodyString 获取请求体字符串
func (s *EsignCallbackApplicationServiceImpl) getRequestBodyString(callbackData map[string]interface{}) (string, error) {
// 将map转换为JSON字符串
jsonBytes, err := json.Marshal(callbackData)
if err != nil {
return "", fmt.Errorf("JSON序列化失败: %w", err)
}
return string(jsonBytes), nil
}
// handleEnterpriseAuthPass 处理企业认证通过回调
func (s *EsignCallbackApplicationServiceImpl) handleEnterpriseAuthPass(ctx context.Context, callback *EsignCallbackData) error {
s.logger.Info("处理企业认证通过回调")
if callback.Organization == nil {
return fmt.Errorf("回调数据中缺少organization字段")
}
if callback.AuthFlowId == "" {
return fmt.Errorf("回调数据中缺少authFlowId字段")
}
// 查找对应的认证申请
certification, err := s.certManagementService.GetCertificationByAuthFlowID(ctx, callback.AuthFlowId)
if err != nil {
return fmt.Errorf("查找认证申请失败: %w", err)
}
if certification.Status != enums.StatusInfoSubmitted {
s.logger.Warn("当前状态不允许完成企业认证", zap.String("status", string(certification.Status)))
return nil
}
if err := s.completeEnterpriseAuth(ctx, certification); err != nil {
return fmt.Errorf("完成企业认证失败: %w", err)
}
s.logger.Info("企业认证通过处理完成",
zap.String("user_id", certification.UserID),
zap.String("certification_id", certification.ID),
zap.String("org_name", callback.Organization.OrgName),
)
return nil
}
// handleEnterpriseAuthFail 处理企业认证失败回调
func (s *EsignCallbackApplicationServiceImpl) handleEnterpriseAuthFail(ctx context.Context, callback *EsignCallbackData) error {
s.logger.Info("处理企业认证失败回调")
if callback.Organization == nil {
return fmt.Errorf("回调数据中缺少organization字段")
}
// 暂时忽略
return nil
}
// handleContractSignFlowComplete 处理合同签署流程完成回调
func (s *EsignCallbackApplicationServiceImpl) handleContractSignFlowComplete(ctx context.Context, callback *EsignCallbackData) error {
s.logger.Info("处理合同签署流程完成回调")
if callback.SignFlowId == "" {
return fmt.Errorf("回调数据中缺少signFlowId字段")
}
if callback.SignFlowStatus == "" {
return fmt.Errorf("回调数据中缺少signFlowStatus字段")
}
// 查找对应的认证申请
certification, err := s.certManagementService.GetCertificationByEsignFlowID(ctx, callback.SignFlowId)
if err != nil {
return fmt.Errorf("查找认证申请失败: %w", err)
}
// 根据签署流程状态处理
switch callback.SignFlowStatus {
case "2": // 已完成(所有签署方完成签署)
s.logger.Info("合同签署流程已完成,所有签署方完成签署")
// 完成合同签署
if err := s.certWorkflowService.CompleteContractSign(ctx, certification.ID, "所有签署方完成签署"); err != nil {
return fmt.Errorf("完成合同签署失败: %w", err)
}
// 自动完成认证
if err := s.certWorkflowService.CompleteCertification(ctx, certification.ID); err != nil {
return fmt.Errorf("完成认证失败: %w", err)
}
s.logger.Info("合同签署流程完成处理成功",
zap.String("user_id", certification.UserID),
zap.String("certification_id", certification.ID),
zap.String("sign_flow_id", callback.SignFlowId),
zap.String("sign_flow_status", callback.SignFlowStatus),
)
case "3": // 已撤销(发起方撤销签署任务)
s.logger.Info("合同签署流程已撤销")
// 可以在这里添加撤销处理逻辑
s.logger.Info("合同签署流程撤销处理完成",
zap.String("user_id", certification.UserID),
zap.String("certification_id", certification.ID),
zap.String("sign_flow_id", callback.SignFlowId),
zap.String("sign_flow_status", callback.SignFlowStatus),
)
// 暂无撤销业务逻辑
case "5": // 已过期(签署截止日到期后触发)
s.logger.Info("合同签署流程已过期")
// 可以在这里添加过期处理逻辑
s.logger.Info("合同签署流程过期处理完成",
zap.String("user_id", certification.UserID),
zap.String("certification_id", certification.ID),
zap.String("sign_flow_id", callback.SignFlowId),
zap.String("sign_flow_status", callback.SignFlowStatus),
)
// 暂无过期业务逻辑
case "7": // 已拒签(签署方拒绝签署)
s.logger.Info("合同签署流程已拒签")
// 可以在这里添加拒签处理逻辑
s.logger.Info("合同签署流程拒签处理完成",
zap.String("user_id", certification.UserID),
zap.String("certification_id", certification.ID),
zap.String("sign_flow_id", callback.SignFlowId),
zap.String("sign_flow_status", callback.SignFlowStatus),
)
default:
s.logger.Warn("未知的签署流程状态",
zap.String("sign_flow_status", callback.SignFlowStatus),
zap.String("sign_flow_id", callback.SignFlowId),
)
// 暂无拒签业务逻辑
}
return nil
}
// 企业认证成功后操作
func (s *EsignCallbackApplicationServiceImpl) completeEnterpriseAuth(ctx context.Context, certification *entities.Certification) error {
err := s.txManager.ExecuteInTx(ctx, func(txCtx context.Context) error {
// 1. 获取企业信息提交记录
enterpriseRecord, err := s.enterpriseRecordService.GetLatestByUserID(txCtx, certification.UserID)
if err != nil {
return fmt.Errorf("获取企业信息失败: %w", err)
}
// 2. 转换状态
if err := s.certWorkflowService.CompleteEnterpriseVerification(txCtx, certification.ID); err != nil {
return err
}
// 3. 创建企业信息
_, err = s.enterpriseService.CreateEnterpriseInfo(txCtx, certification.UserID, enterpriseRecord.CompanyName, enterpriseRecord.UnifiedSocialCode, enterpriseRecord.LegalPersonName, enterpriseRecord.LegalPersonID)
if err != nil {
s.logger.Warn("创建用户企业信息失败", zap.Error(err))
return err
}
return nil
})
if err != nil {
return fmt.Errorf("完成企业认证失败: %w", err)
}
return nil
}