temp
This commit is contained in:
110
internal/domains/certification/dto/certification_dto.go
Normal file
110
internal/domains/certification/dto/certification_dto.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"tyapi-server/internal/domains/certification/enums"
|
||||
)
|
||||
|
||||
// CertificationCreateRequest 创建认证申请请求
|
||||
type CertificationCreateRequest struct {
|
||||
UserID string `json:"user_id" binding:"required"`
|
||||
}
|
||||
|
||||
// CertificationCreateResponse 创建认证申请响应
|
||||
type CertificationCreateResponse struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Status enums.CertificationStatus `json:"status"`
|
||||
}
|
||||
|
||||
// CertificationStatusResponse 认证状态响应
|
||||
type CertificationStatusResponse 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"`
|
||||
}
|
||||
|
||||
// SubmitEnterpriseInfoRequest 提交企业信息请求
|
||||
type SubmitEnterpriseInfoRequest struct {
|
||||
CompanyName string `json:"company_name" binding:"required"`
|
||||
UnifiedSocialCode string `json:"unified_social_code" binding:"required"`
|
||||
LegalPersonName string `json:"legal_person_name" binding:"required"`
|
||||
LegalPersonID string `json:"legal_person_id" binding:"required"`
|
||||
LicenseUploadRecordID string `json:"license_upload_record_id" binding:"required"`
|
||||
}
|
||||
|
||||
// SubmitEnterpriseInfoResponse 提交企业信息响应
|
||||
type SubmitEnterpriseInfoResponse struct {
|
||||
ID string `json:"id"`
|
||||
Status enums.CertificationStatus `json:"status"`
|
||||
Enterprise *EnterpriseInfoResponse `json:"enterprise"`
|
||||
}
|
||||
|
||||
// FaceVerifyRequest 人脸识别请求
|
||||
type FaceVerifyRequest struct {
|
||||
RealName string `json:"real_name" binding:"required"`
|
||||
IDCardNumber string `json:"id_card_number" binding:"required"`
|
||||
ReturnURL string `json:"return_url" binding:"required"`
|
||||
}
|
||||
|
||||
// FaceVerifyResponse 人脸识别响应
|
||||
type FaceVerifyResponse struct {
|
||||
CertifyID string `json:"certify_id"`
|
||||
VerifyURL string `json:"verify_url"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// ApplyContractRequest 申请合同请求(无需额外参数)
|
||||
type ApplyContractRequest struct{}
|
||||
|
||||
// ApplyContractResponse 申请合同响应
|
||||
type ApplyContractResponse struct {
|
||||
ID string `json:"id"`
|
||||
Status enums.CertificationStatus `json:"status"`
|
||||
ContractAppliedAt time.Time `json:"contract_applied_at"`
|
||||
}
|
||||
|
||||
// SignContractRequest 签署合同请求
|
||||
type SignContractRequest struct {
|
||||
SignatureData string `json:"signature_data,omitempty"`
|
||||
}
|
||||
|
||||
// SignContractResponse 签署合同响应
|
||||
type SignContractResponse struct {
|
||||
ID string `json:"id"`
|
||||
Status enums.CertificationStatus `json:"status"`
|
||||
ContractSignedAt time.Time `json:"contract_signed_at"`
|
||||
}
|
||||
|
||||
// CertificationDetailResponse 认证详情响应
|
||||
type CertificationDetailResponse struct {
|
||||
*CertificationStatusResponse
|
||||
|
||||
// 详细记录
|
||||
LicenseUploadRecord *LicenseUploadRecordResponse `json:"license_upload_record,omitempty"`
|
||||
FaceVerifyRecords []FaceVerifyRecordResponse `json:"face_verify_records,omitempty"`
|
||||
ContractRecords []ContractRecordResponse `json:"contract_records,omitempty"`
|
||||
NotificationRecords []NotificationRecordResponse `json:"notification_records,omitempty"`
|
||||
}
|
||||
108
internal/domains/certification/dto/enterprise_dto.go
Normal file
108
internal/domains/certification/dto/enterprise_dto.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// 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"`
|
||||
OCRRawData string `json:"ocr_raw_data,omitempty"`
|
||||
OCRConfidence float64 `json:"ocr_confidence,omitempty"`
|
||||
IsOCRVerified bool `json:"is_ocr_verified"`
|
||||
IsFaceVerified bool `json:"is_face_verified"`
|
||||
VerificationData string `json:"verification_data,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// LicenseUploadRecordResponse 营业执照上传记录响应
|
||||
type LicenseUploadRecordResponse struct {
|
||||
ID string `json:"id"`
|
||||
CertificationID *string `json:"certification_id,omitempty"`
|
||||
UserID string `json:"user_id"`
|
||||
OriginalFileName string `json:"original_file_name"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
FileType string `json:"file_type"`
|
||||
FileURL string `json:"file_url"`
|
||||
QiNiuKey string `json:"qiniu_key"`
|
||||
OCRProcessed bool `json:"ocr_processed"`
|
||||
OCRSuccess bool `json:"ocr_success"`
|
||||
OCRConfidence float64 `json:"ocr_confidence,omitempty"`
|
||||
OCRRawData string `json:"ocr_raw_data,omitempty"`
|
||||
OCRErrorMessage string `json:"ocr_error_message,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// FaceVerifyRecordResponse 人脸识别记录响应
|
||||
type FaceVerifyRecordResponse struct {
|
||||
ID string `json:"id"`
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
CertifyID string `json:"certify_id"`
|
||||
VerifyURL string `json:"verify_url,omitempty"`
|
||||
ReturnURL string `json:"return_url,omitempty"`
|
||||
RealName string `json:"real_name"`
|
||||
IDCardNumber string `json:"id_card_number"`
|
||||
Status string `json:"status"`
|
||||
StatusName string `json:"status_name"`
|
||||
ResultCode string `json:"result_code,omitempty"`
|
||||
ResultMessage string `json:"result_message,omitempty"`
|
||||
VerifyScore float64 `json:"verify_score,omitempty"`
|
||||
InitiatedAt time.Time `json:"initiated_at"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ContractRecordResponse 合同记录响应
|
||||
type ContractRecordResponse struct {
|
||||
ID string `json:"id"`
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
AdminID *string `json:"admin_id,omitempty"`
|
||||
ContractType string `json:"contract_type"`
|
||||
ContractURL string `json:"contract_url,omitempty"`
|
||||
SigningURL string `json:"signing_url,omitempty"`
|
||||
SignatureData string `json:"signature_data,omitempty"`
|
||||
SignedAt *time.Time `json:"signed_at,omitempty"`
|
||||
ClientIP string `json:"client_ip,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
Status string `json:"status"`
|
||||
StatusName string `json:"status_name"`
|
||||
ApprovalNotes string `json:"approval_notes,omitempty"`
|
||||
RejectReason string `json:"reject_reason,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// NotificationRecordResponse 通知记录响应
|
||||
type NotificationRecordResponse struct {
|
||||
ID string `json:"id"`
|
||||
CertificationID *string `json:"certification_id,omitempty"`
|
||||
UserID *string `json:"user_id,omitempty"`
|
||||
NotificationType string `json:"notification_type"`
|
||||
NotificationTypeName string `json:"notification_type_name"`
|
||||
NotificationScene string `json:"notification_scene"`
|
||||
NotificationSceneName string `json:"notification_scene_name"`
|
||||
Recipient string `json:"recipient"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Content string `json:"content"`
|
||||
TemplateID string `json:"template_id,omitempty"`
|
||||
TemplateParams string `json:"template_params,omitempty"`
|
||||
Status string `json:"status"`
|
||||
StatusName string `json:"status_name"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
SentAt *time.Time `json:"sent_at,omitempty"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
MaxRetryCount int `json:"max_retry_count"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
77
internal/domains/certification/dto/ocr_dto.go
Normal file
77
internal/domains/certification/dto/ocr_dto.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package dto
|
||||
|
||||
// BusinessLicenseResult 营业执照识别结果
|
||||
type BusinessLicenseResult struct {
|
||||
CompanyName string `json:"company_name"` // 公司名称
|
||||
LegalRepresentative string `json:"legal_representative"` // 法定代表人
|
||||
RegisteredCapital string `json:"registered_capital"` // 注册资本
|
||||
RegisteredAddress string `json:"registered_address"` // 注册地址
|
||||
RegistrationNumber string `json:"registration_number"` // 统一社会信用代码
|
||||
BusinessScope string `json:"business_scope"` // 经营范围
|
||||
RegistrationDate string `json:"registration_date"` // 成立日期
|
||||
ValidDate string `json:"valid_date"` // 营业期限
|
||||
Confidence float64 `json:"confidence"` // 识别置信度
|
||||
Words []string `json:"words"` // 识别的所有文字
|
||||
}
|
||||
|
||||
// IDCardResult 身份证识别结果
|
||||
type IDCardResult struct {
|
||||
Side string `json:"side"` // 身份证面(front/back)
|
||||
Name string `json:"name"` // 姓名(正面)
|
||||
Sex string `json:"sex"` // 性别(正面)
|
||||
Nation string `json:"nation"` // 民族(正面)
|
||||
BirthDate string `json:"birth_date"` // 出生日期(正面)
|
||||
Address string `json:"address"` // 住址(正面)
|
||||
IDNumber string `json:"id_number"` // 身份证号码(正面)
|
||||
IssuingAuthority string `json:"issuing_authority"` // 签发机关(背面)
|
||||
ValidDate string `json:"valid_date"` // 有效期限(背面)
|
||||
Confidence float64 `json:"confidence"` // 识别置信度
|
||||
Words []string `json:"words"` // 识别的所有文字
|
||||
}
|
||||
|
||||
// GeneralTextResult 通用文字识别结果
|
||||
type GeneralTextResult struct {
|
||||
Words []string `json:"words"` // 识别的文字列表
|
||||
Confidence float64 `json:"confidence"` // 识别置信度
|
||||
}
|
||||
|
||||
// OCREnterpriseInfo OCR识别的企业信息
|
||||
type OCREnterpriseInfo struct {
|
||||
CompanyName string `json:"company_name"` // 企业名称
|
||||
UnifiedSocialCode string `json:"unified_social_code"` // 统一社会信用代码
|
||||
LegalPersonName string `json:"legal_person_name"` // 法人姓名
|
||||
LegalPersonID string `json:"legal_person_id"` // 法人身份证号
|
||||
Confidence float64 `json:"confidence"` // 识别置信度
|
||||
}
|
||||
|
||||
// LicenseProcessResult 营业执照处理结果
|
||||
type LicenseProcessResult struct {
|
||||
LicenseURL string `json:"license_url"` // 营业执照文件URL
|
||||
EnterpriseInfo *OCREnterpriseInfo `json:"enterprise_info"` // OCR识别的企业信息
|
||||
OCRSuccess bool `json:"ocr_success"` // OCR是否成功
|
||||
OCRError string `json:"ocr_error,omitempty"` // OCR错误信息
|
||||
}
|
||||
|
||||
// UploadLicenseRequest 上传营业执照请求
|
||||
type UploadLicenseRequest struct {
|
||||
// 文件通过multipart/form-data上传,这里定义验证规则
|
||||
}
|
||||
|
||||
// UploadLicenseResponse 上传营业执照响应
|
||||
type UploadLicenseResponse struct {
|
||||
UploadRecordID string `json:"upload_record_id"` // 上传记录ID
|
||||
FileURL string `json:"file_url"` // 文件URL
|
||||
OCRProcessed bool `json:"ocr_processed"` // OCR是否已处理
|
||||
OCRSuccess bool `json:"ocr_success"` // OCR是否成功
|
||||
EnterpriseInfo *OCREnterpriseInfo `json:"enterprise_info"` // OCR识别的企业信息(如果成功)
|
||||
OCRErrorMessage string `json:"ocr_error_message,omitempty"` // OCR错误信息(如果失败)
|
||||
}
|
||||
|
||||
// UploadResult 上传结果
|
||||
type UploadResult struct {
|
||||
Key string `json:"key"` // 文件key
|
||||
URL string `json:"url"` // 文件访问URL
|
||||
MimeType string `json:"mime_type"` // MIME类型
|
||||
Size int64 `json:"size"` // 文件大小
|
||||
Hash string `json:"hash"` // 文件哈希值
|
||||
}
|
||||
179
internal/domains/certification/entities/certification.go
Normal file
179
internal/domains/certification/entities/certification.go
Normal file
@@ -0,0 +1,179 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"tyapi-server/internal/domains/certification/enums"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Certification 认证申请实体
|
||||
// 这是企业认证流程的核心实体,负责管理整个认证申请的生命周期
|
||||
// 包含认证状态、时间节点、审核信息、合同信息等核心数据
|
||||
type Certification struct {
|
||||
// 基础信息
|
||||
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"认证申请唯一标识"`
|
||||
UserID string `gorm:"type:varchar(36);not null;index" json:"user_id" comment:"申请用户ID"`
|
||||
EnterpriseID *string `gorm:"type:varchar(36);index" json:"enterprise_id" comment:"关联的企业信息ID"`
|
||||
Status enums.CertificationStatus `gorm:"type:varchar(50);not null;index" json:"status" comment:"当前认证状态"`
|
||||
|
||||
// 流程节点时间戳 - 记录每个关键步骤的完成时间
|
||||
InfoSubmittedAt *time.Time `json:"info_submitted_at,omitempty" comment:"企业信息提交时间"`
|
||||
FaceVerifiedAt *time.Time `json:"face_verified_at,omitempty" comment:"人脸识别完成时间"`
|
||||
ContractAppliedAt *time.Time `json:"contract_applied_at,omitempty" comment:"合同申请时间"`
|
||||
ContractApprovedAt *time.Time `json:"contract_approved_at,omitempty" comment:"合同审核通过时间"`
|
||||
ContractSignedAt *time.Time `json:"contract_signed_at,omitempty" comment:"合同签署完成时间"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty" comment:"认证完成时间"`
|
||||
|
||||
// 审核信息 - 管理员审核相关数据
|
||||
AdminID *string `gorm:"type:varchar(36)" json:"admin_id,omitempty" comment:"审核管理员ID"`
|
||||
ApprovalNotes string `gorm:"type:text" json:"approval_notes,omitempty" comment:"审核备注信息"`
|
||||
RejectReason string `gorm:"type:text" json:"reject_reason,omitempty" comment:"拒绝原因说明"`
|
||||
|
||||
// 合同信息 - 电子合同相关链接
|
||||
ContractURL string `gorm:"type:varchar(500)" json:"contract_url,omitempty" comment:"合同文件访问链接"`
|
||||
SigningURL string `gorm:"type:varchar(500)" json:"signing_url,omitempty" comment:"电子签署链接"`
|
||||
|
||||
// OCR识别信息 - 营业执照OCR识别结果
|
||||
OCRRequestID string `gorm:"type:varchar(100)" json:"ocr_request_id,omitempty" comment:"OCR识别请求ID"`
|
||||
OCRConfidence float64 `gorm:"type:decimal(5,2)" json:"ocr_confidence,omitempty" comment:"OCR识别置信度(0-1)"`
|
||||
|
||||
// 时间戳字段
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
|
||||
|
||||
// 关联关系 - 与其他实体的关联
|
||||
Enterprise *Enterprise `gorm:"foreignKey:EnterpriseID" json:"enterprise,omitempty" comment:"关联的企业信息"`
|
||||
LicenseUploadRecord *LicenseUploadRecord `gorm:"foreignKey:CertificationID" json:"license_upload_record,omitempty" comment:"关联的营业执照上传记录"`
|
||||
FaceVerifyRecords []FaceVerifyRecord `gorm:"foreignKey:CertificationID" json:"face_verify_records,omitempty" comment:"关联的人脸识别记录列表"`
|
||||
ContractRecords []ContractRecord `gorm:"foreignKey:CertificationID" json:"contract_records,omitempty" comment:"关联的合同记录列表"`
|
||||
NotificationRecords []NotificationRecord `gorm:"foreignKey:CertificationID" json:"notification_records,omitempty" comment:"关联的通知记录列表"`
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (Certification) TableName() string {
|
||||
return "certifications"
|
||||
}
|
||||
|
||||
// IsStatusChangeable 检查状态是否可以变更
|
||||
// 只有非最终状态(完成/拒绝)的认证申请才能进行状态变更
|
||||
func (c *Certification) IsStatusChangeable() bool {
|
||||
return !enums.IsFinalStatus(c.Status)
|
||||
}
|
||||
|
||||
// CanRetryFaceVerify 检查是否可以重试人脸识别
|
||||
// 只有人脸识别失败状态的申请才能重试
|
||||
func (c *Certification) CanRetryFaceVerify() bool {
|
||||
return c.Status == enums.StatusFaceFailed
|
||||
}
|
||||
|
||||
// CanRetrySign 检查是否可以重试签署
|
||||
// 只有签署失败状态的申请才能重试
|
||||
func (c *Certification) CanRetrySign() bool {
|
||||
return c.Status == enums.StatusSignFailed
|
||||
}
|
||||
|
||||
// CanRestart 检查是否可以重新开始流程
|
||||
// 只有被拒绝的申请才能重新开始认证流程
|
||||
func (c *Certification) CanRestart() bool {
|
||||
return c.Status == enums.StatusRejected
|
||||
}
|
||||
|
||||
// GetNextValidStatuses 获取当前状态可以转换到的下一个状态列表
|
||||
// 根据状态机规则,返回所有合法的下一个状态
|
||||
func (c *Certification) GetNextValidStatuses() []enums.CertificationStatus {
|
||||
switch c.Status {
|
||||
case enums.StatusPending:
|
||||
return []enums.CertificationStatus{enums.StatusInfoSubmitted}
|
||||
case enums.StatusInfoSubmitted:
|
||||
return []enums.CertificationStatus{enums.StatusFaceVerified, enums.StatusFaceFailed}
|
||||
case enums.StatusFaceVerified:
|
||||
return []enums.CertificationStatus{enums.StatusContractApplied}
|
||||
case enums.StatusContractApplied:
|
||||
return []enums.CertificationStatus{enums.StatusContractPending}
|
||||
case enums.StatusContractPending:
|
||||
return []enums.CertificationStatus{enums.StatusContractApproved, enums.StatusRejected}
|
||||
case enums.StatusContractApproved:
|
||||
return []enums.CertificationStatus{enums.StatusContractSigned, enums.StatusSignFailed}
|
||||
case enums.StatusContractSigned:
|
||||
return []enums.CertificationStatus{enums.StatusCompleted}
|
||||
case enums.StatusFaceFailed:
|
||||
return []enums.CertificationStatus{enums.StatusFaceVerified}
|
||||
case enums.StatusSignFailed:
|
||||
return []enums.CertificationStatus{enums.StatusContractSigned}
|
||||
case enums.StatusRejected:
|
||||
return []enums.CertificationStatus{enums.StatusInfoSubmitted}
|
||||
default:
|
||||
return []enums.CertificationStatus{}
|
||||
}
|
||||
}
|
||||
|
||||
// CanTransitionTo 检查是否可以转换到指定状态
|
||||
// 验证状态转换的合法性,确保状态机规则得到遵守
|
||||
func (c *Certification) CanTransitionTo(targetStatus enums.CertificationStatus) bool {
|
||||
validStatuses := c.GetNextValidStatuses()
|
||||
for _, status := range validStatuses {
|
||||
if status == targetStatus {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GetProgressPercentage 获取认证进度百分比
|
||||
// 根据当前状态计算认证流程的完成进度,用于前端进度条显示
|
||||
func (c *Certification) GetProgressPercentage() int {
|
||||
switch c.Status {
|
||||
case enums.StatusPending:
|
||||
return 0
|
||||
case enums.StatusInfoSubmitted:
|
||||
return 12
|
||||
case enums.StatusFaceVerified:
|
||||
return 25
|
||||
case enums.StatusContractApplied:
|
||||
return 37
|
||||
case enums.StatusContractPending:
|
||||
return 50
|
||||
case enums.StatusContractApproved:
|
||||
return 75
|
||||
case enums.StatusContractSigned:
|
||||
return 87
|
||||
case enums.StatusCompleted:
|
||||
return 100
|
||||
case enums.StatusFaceFailed, enums.StatusSignFailed:
|
||||
return c.GetProgressPercentage() // 失败状态保持原进度
|
||||
case enums.StatusRejected:
|
||||
return 0
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// IsUserActionRequired 检查是否需要用户操作
|
||||
// 判断当前状态是否需要用户进行下一步操作,用于前端提示
|
||||
func (c *Certification) IsUserActionRequired() bool {
|
||||
userActionStatuses := []enums.CertificationStatus{
|
||||
enums.StatusPending,
|
||||
enums.StatusInfoSubmitted,
|
||||
enums.StatusFaceVerified,
|
||||
enums.StatusContractApproved,
|
||||
enums.StatusFaceFailed,
|
||||
enums.StatusSignFailed,
|
||||
enums.StatusRejected,
|
||||
}
|
||||
|
||||
for _, status := range userActionStatuses {
|
||||
if c.Status == status {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsAdminActionRequired 检查是否需要管理员操作
|
||||
// 判断当前状态是否需要管理员审核,用于后台管理界面
|
||||
func (c *Certification) IsAdminActionRequired() bool {
|
||||
return c.Status == enums.StatusContractPending
|
||||
}
|
||||
98
internal/domains/certification/entities/contract_record.go
Normal file
98
internal/domains/certification/entities/contract_record.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ContractRecord 合同记录实体
|
||||
// 记录电子合同的详细信息,包括合同生成、审核、签署的完整流程
|
||||
// 支持合同状态跟踪、签署信息记录、审核流程管理等功能
|
||||
type ContractRecord struct {
|
||||
// 基础标识
|
||||
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"合同记录唯一标识"`
|
||||
CertificationID string `gorm:"type:varchar(36);not null;index" json:"certification_id" comment:"关联的认证申请ID"`
|
||||
UserID string `gorm:"type:varchar(36);not null;index" json:"user_id" comment:"合同申请人ID"`
|
||||
AdminID *string `gorm:"type:varchar(36);index" json:"admin_id,omitempty" comment:"审核管理员ID"`
|
||||
|
||||
// 合同信息 - 电子合同的基本信息
|
||||
ContractType string `gorm:"type:varchar(50);not null" json:"contract_type" comment:"合同类型(ENTERPRISE_CERTIFICATION)"`
|
||||
ContractURL string `gorm:"type:varchar(500)" json:"contract_url,omitempty" comment:"合同文件访问链接"`
|
||||
SigningURL string `gorm:"type:varchar(500)" json:"signing_url,omitempty" comment:"电子签署链接"`
|
||||
|
||||
// 签署信息 - 记录用户签署的详细信息
|
||||
SignatureData string `gorm:"type:text" json:"signature_data,omitempty" comment:"签署数据(JSON格式)"`
|
||||
SignedAt *time.Time `json:"signed_at,omitempty" comment:"签署完成时间"`
|
||||
ClientIP string `gorm:"type:varchar(50)" json:"client_ip,omitempty" comment:"签署客户端IP"`
|
||||
UserAgent string `gorm:"type:varchar(500)" json:"user_agent,omitempty" comment:"签署客户端信息"`
|
||||
|
||||
// 状态信息 - 合同的生命周期状态
|
||||
Status string `gorm:"type:varchar(50);not null;index" json:"status" comment:"合同状态(PENDING/APPROVED/SIGNED/EXPIRED)"`
|
||||
ApprovalNotes string `gorm:"type:text" json:"approval_notes,omitempty" comment:"审核备注信息"`
|
||||
RejectReason string `gorm:"type:text" json:"reject_reason,omitempty" comment:"拒绝原因说明"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty" comment:"合同过期时间"`
|
||||
|
||||
// 时间戳字段
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
|
||||
|
||||
// 关联关系
|
||||
Certification *Certification `gorm:"foreignKey:CertificationID" json:"certification,omitempty" comment:"关联的认证申请"`
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (ContractRecord) TableName() string {
|
||||
return "contract_records"
|
||||
}
|
||||
|
||||
// IsPending 检查合同是否待审核
|
||||
// 判断合同是否处于等待管理员审核的状态
|
||||
func (c *ContractRecord) IsPending() bool {
|
||||
return c.Status == "PENDING"
|
||||
}
|
||||
|
||||
// IsApproved 检查合同是否已审核通过
|
||||
// 判断合同是否已通过管理员审核,可以进入签署阶段
|
||||
func (c *ContractRecord) IsApproved() bool {
|
||||
return c.Status == "APPROVED"
|
||||
}
|
||||
|
||||
// IsSigned 检查合同是否已签署
|
||||
// 判断合同是否已完成电子签署,认证流程即将完成
|
||||
func (c *ContractRecord) IsSigned() bool {
|
||||
return c.Status == "SIGNED"
|
||||
}
|
||||
|
||||
// IsExpired 检查合同是否已过期
|
||||
// 判断合同是否已超过有效期,过期后需要重新申请
|
||||
func (c *ContractRecord) IsExpired() bool {
|
||||
if c.ExpiresAt == nil {
|
||||
return false
|
||||
}
|
||||
return time.Now().After(*c.ExpiresAt)
|
||||
}
|
||||
|
||||
// HasSigningURL 检查是否有签署链接
|
||||
// 判断是否已生成电子签署链接,用于前端判断是否显示签署按钮
|
||||
func (c *ContractRecord) HasSigningURL() bool {
|
||||
return c.SigningURL != ""
|
||||
}
|
||||
|
||||
// GetStatusName 获取状态的中文名称
|
||||
// 将英文状态码转换为中文显示名称,用于前端展示和用户理解
|
||||
func (c *ContractRecord) GetStatusName() string {
|
||||
statusNames := map[string]string{
|
||||
"PENDING": "待审核",
|
||||
"APPROVED": "已审核",
|
||||
"SIGNED": "已签署",
|
||||
"EXPIRED": "已过期",
|
||||
"REJECTED": "已拒绝",
|
||||
}
|
||||
|
||||
if name, exists := statusNames[c.Status]; exists {
|
||||
return name
|
||||
}
|
||||
return c.Status
|
||||
}
|
||||
66
internal/domains/certification/entities/enterprise.go
Normal file
66
internal/domains/certification/entities/enterprise.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Enterprise 企业信息实体
|
||||
// 存储企业认证的核心信息,包括企业四要素和验证状态
|
||||
// 与认证申请是一对一关系,每个认证申请对应一个企业信息
|
||||
type Enterprise struct {
|
||||
// 基础标识
|
||||
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"企业信息唯一标识"`
|
||||
CertificationID string `gorm:"type:varchar(36);not null;index" json:"certification_id" comment:"关联的认证申请ID"`
|
||||
|
||||
// 企业四要素 - 企业认证的核心信息
|
||||
CompanyName string `gorm:"type:varchar(255);not null" json:"company_name" comment:"企业名称"`
|
||||
UnifiedSocialCode string `gorm:"type:varchar(50);not null;index" json:"unified_social_code" comment:"统一社会信用代码"`
|
||||
LegalPersonName string `gorm:"type:varchar(100);not null" json:"legal_person_name" comment:"法定代表人姓名"`
|
||||
LegalPersonID string `gorm:"type:varchar(50);not null" json:"legal_person_id" comment:"法定代表人身份证号"`
|
||||
|
||||
// 关联的营业执照上传记录
|
||||
LicenseUploadRecordID string `gorm:"type:varchar(36);not null;index" json:"license_upload_record_id" comment:"关联的营业执照上传记录ID"`
|
||||
|
||||
// OCR识别结果 - 从营业执照中自动识别的信息
|
||||
OCRRawData string `gorm:"type:text" json:"ocr_raw_data,omitempty" comment:"OCR原始返回数据(JSON格式)"`
|
||||
OCRConfidence float64 `gorm:"type:decimal(5,2)" json:"ocr_confidence,omitempty" comment:"OCR识别置信度(0-1)"`
|
||||
|
||||
// 验证状态 - 各环节的验证结果
|
||||
IsOCRVerified bool `gorm:"default:false" json:"is_ocr_verified" comment:"OCR验证是否通过"`
|
||||
IsFaceVerified bool `gorm:"default:false" json:"is_face_verified" comment:"人脸识别是否通过"`
|
||||
VerificationData string `gorm:"type:text" json:"verification_data,omitempty" comment:"验证数据(JSON格式)"`
|
||||
|
||||
// 时间戳字段
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
|
||||
|
||||
// 关联关系
|
||||
Certification *Certification `gorm:"foreignKey:CertificationID" json:"certification,omitempty" comment:"关联的认证申请"`
|
||||
LicenseUploadRecord *LicenseUploadRecord `gorm:"foreignKey:LicenseUploadRecordID" json:"license_upload_record,omitempty" comment:"关联的营业执照上传记录"`
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (Enterprise) TableName() string {
|
||||
return "enterprises"
|
||||
}
|
||||
|
||||
// IsComplete 检查企业四要素是否完整
|
||||
// 验证企业名称、统一社会信用代码、法定代表人姓名、身份证号是否都已填写
|
||||
func (e *Enterprise) IsComplete() bool {
|
||||
return e.CompanyName != "" &&
|
||||
e.UnifiedSocialCode != "" &&
|
||||
e.LegalPersonName != "" &&
|
||||
e.LegalPersonID != ""
|
||||
}
|
||||
|
||||
// Validate 验证企业信息是否有效
|
||||
// 这里可以添加企业信息的业务验证逻辑
|
||||
// 比如统一社会信用代码格式验证、身份证号格式验证等
|
||||
func (e *Enterprise) Validate() error {
|
||||
// 这里可以添加企业信息的业务验证逻辑
|
||||
// 比如统一社会信用代码格式验证、身份证号格式验证等
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// FaceVerifyRecord 人脸识别记录实体
|
||||
// 记录用户进行人脸识别验证的详细信息,包括验证状态、结果和身份信息
|
||||
// 支持多次验证尝试,每次验证都会生成独立的记录,便于追踪和重试
|
||||
type FaceVerifyRecord struct {
|
||||
// 基础标识
|
||||
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"人脸识别记录唯一标识"`
|
||||
CertificationID string `gorm:"type:varchar(36);not null;index" json:"certification_id" comment:"关联的认证申请ID"`
|
||||
UserID string `gorm:"type:varchar(36);not null;index" json:"user_id" comment:"进行验证的用户ID"`
|
||||
|
||||
// 阿里云人脸识别信息 - 第三方服务的相关数据
|
||||
CertifyID string `gorm:"type:varchar(100);not null;index" json:"certify_id" comment:"阿里云人脸识别任务ID"`
|
||||
VerifyURL string `gorm:"type:varchar(500)" json:"verify_url,omitempty" comment:"人脸识别验证页面URL"`
|
||||
ReturnURL string `gorm:"type:varchar(500)" json:"return_url,omitempty" comment:"验证完成后的回调URL"`
|
||||
|
||||
// 身份信息 - 用于人脸识别的身份验证数据
|
||||
RealName string `gorm:"type:varchar(100);not null" json:"real_name" comment:"真实姓名"`
|
||||
IDCardNumber string `gorm:"type:varchar(50);not null" json:"id_card_number" comment:"身份证号码"`
|
||||
|
||||
// 验证结果 - 记录验证的详细结果信息
|
||||
Status string `gorm:"type:varchar(50);not null;index" json:"status" comment:"验证状态(PROCESSING/SUCCESS/FAIL)"`
|
||||
ResultCode string `gorm:"type:varchar(50)" json:"result_code,omitempty" comment:"结果代码"`
|
||||
ResultMessage string `gorm:"type:varchar(500)" json:"result_message,omitempty" comment:"结果描述信息"`
|
||||
VerifyScore float64 `gorm:"type:decimal(5,2)" json:"verify_score,omitempty" comment:"验证分数(0-1)"`
|
||||
|
||||
// 时间信息 - 验证流程的时间节点
|
||||
InitiatedAt time.Time `gorm:"autoCreateTime" json:"initiated_at" comment:"验证发起时间"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty" comment:"验证完成时间"`
|
||||
ExpiresAt time.Time `gorm:"not null" json:"expires_at" comment:"验证链接过期时间"`
|
||||
|
||||
// 时间戳字段
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
|
||||
|
||||
// 关联关系
|
||||
Certification *Certification `gorm:"foreignKey:CertificationID" json:"certification,omitempty" comment:"关联的认证申请"`
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (FaceVerifyRecord) TableName() string {
|
||||
return "face_verify_records"
|
||||
}
|
||||
|
||||
// IsSuccess 检查人脸识别是否成功
|
||||
// 判断验证状态是否为成功状态
|
||||
func (f *FaceVerifyRecord) IsSuccess() bool {
|
||||
return f.Status == "SUCCESS"
|
||||
}
|
||||
|
||||
// IsProcessing 检查是否正在处理中
|
||||
// 判断验证是否正在进行中,等待用户完成验证
|
||||
func (f *FaceVerifyRecord) IsProcessing() bool {
|
||||
return f.Status == "PROCESSING"
|
||||
}
|
||||
|
||||
// IsFailed 检查是否失败
|
||||
// 判断验证是否失败,包括超时、验证不通过等情况
|
||||
func (f *FaceVerifyRecord) IsFailed() bool {
|
||||
return f.Status == "FAIL"
|
||||
}
|
||||
|
||||
// IsExpired 检查是否已过期
|
||||
// 判断验证链接是否已超过有效期,过期后需要重新发起验证
|
||||
func (f *FaceVerifyRecord) IsExpired() bool {
|
||||
return time.Now().After(f.ExpiresAt)
|
||||
}
|
||||
|
||||
// GetStatusName 获取状态的中文名称
|
||||
// 将英文状态码转换为中文显示名称,用于前端展示
|
||||
func (f *FaceVerifyRecord) GetStatusName() string {
|
||||
statusNames := map[string]string{
|
||||
"PROCESSING": "处理中",
|
||||
"SUCCESS": "成功",
|
||||
"FAIL": "失败",
|
||||
}
|
||||
|
||||
if name, exists := statusNames[f.Status]; exists {
|
||||
return name
|
||||
}
|
||||
return f.Status
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// LicenseUploadRecord 营业执照上传记录实体
|
||||
// 记录用户上传营业执照文件的详细信息,包括文件元数据和OCR处理结果
|
||||
// 支持多种文件格式,自动进行OCR识别,为后续企业信息验证提供数据支持
|
||||
type LicenseUploadRecord struct {
|
||||
// 基础标识
|
||||
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"上传记录唯一标识"`
|
||||
CertificationID *string `gorm:"type:varchar(36);index" json:"certification_id,omitempty" comment:"关联的认证申请ID(可为空,表示独立上传)"`
|
||||
UserID string `gorm:"type:varchar(36);not null;index" json:"user_id" comment:"上传用户ID"`
|
||||
|
||||
// 文件信息 - 存储文件的元数据信息
|
||||
OriginalFileName string `gorm:"type:varchar(255);not null" json:"original_file_name" comment:"原始文件名"`
|
||||
FileSize int64 `gorm:"not null" json:"file_size" comment:"文件大小(字节)"`
|
||||
FileType string `gorm:"type:varchar(50);not null" json:"file_type" comment:"文件MIME类型"`
|
||||
FileURL string `gorm:"type:varchar(500);not null" json:"file_url" comment:"文件访问URL"`
|
||||
QiNiuKey string `gorm:"type:varchar(255);not null;index" json:"qiniu_key" comment:"七牛云存储的Key"`
|
||||
|
||||
// OCR处理结果 - 记录OCR识别的详细结果
|
||||
OCRProcessed bool `gorm:"default:false" json:"ocr_processed" comment:"是否已进行OCR处理"`
|
||||
OCRSuccess bool `gorm:"default:false" json:"ocr_success" comment:"OCR识别是否成功"`
|
||||
OCRConfidence float64 `gorm:"type:decimal(5,2)" json:"ocr_confidence,omitempty" comment:"OCR识别置信度(0-1)"`
|
||||
OCRRawData string `gorm:"type:text" json:"ocr_raw_data,omitempty" comment:"OCR原始返回数据(JSON格式)"`
|
||||
OCRErrorMessage string `gorm:"type:varchar(500)" json:"ocr_error_message,omitempty" comment:"OCR处理错误信息"`
|
||||
|
||||
// 时间戳字段
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
|
||||
|
||||
// 关联关系
|
||||
Certification *Certification `gorm:"foreignKey:CertificationID" json:"certification,omitempty" comment:"关联的认证申请"`
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (LicenseUploadRecord) TableName() string {
|
||||
return "license_upload_records"
|
||||
}
|
||||
|
||||
// IsOCRSuccess 检查OCR是否成功
|
||||
// 判断OCR处理已完成且识别成功
|
||||
func (l *LicenseUploadRecord) IsOCRSuccess() bool {
|
||||
return l.OCRProcessed && l.OCRSuccess
|
||||
}
|
||||
|
||||
// GetFileExtension 获取文件扩展名
|
||||
// 从原始文件名中提取文件扩展名,用于文件类型判断
|
||||
func (l *LicenseUploadRecord) GetFileExtension() string {
|
||||
// 从OriginalFileName提取扩展名的逻辑
|
||||
// 这里简化处理,实际使用时可以用path.Ext()
|
||||
return l.FileType
|
||||
}
|
||||
|
||||
// IsValidForOCR 检查文件是否适合OCR处理
|
||||
// 验证文件类型是否支持OCR识别,目前支持JPEG、PNG格式
|
||||
func (l *LicenseUploadRecord) IsValidForOCR() bool {
|
||||
validTypes := []string{"image/jpeg", "image/png", "image/jpg"}
|
||||
for _, validType := range validTypes {
|
||||
if l.FileType == validType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
127
internal/domains/certification/entities/notification_record.go
Normal file
127
internal/domains/certification/entities/notification_record.go
Normal file
@@ -0,0 +1,127 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NotificationRecord 通知记录实体
|
||||
// 记录系统发送的所有通知信息,包括短信、企业微信、邮件等多种通知渠道
|
||||
// 支持通知状态跟踪、重试机制、模板化消息等功能,确保通知的可靠送达
|
||||
type NotificationRecord struct {
|
||||
// 基础标识
|
||||
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"通知记录唯一标识"`
|
||||
CertificationID *string `gorm:"type:varchar(36);index" json:"certification_id,omitempty" comment:"关联的认证申请ID(可为空)"`
|
||||
UserID *string `gorm:"type:varchar(36);index" json:"user_id,omitempty" comment:"接收用户ID(可为空)"`
|
||||
|
||||
// 通知类型和渠道 - 定义通知的发送方式和业务场景
|
||||
NotificationType string `gorm:"type:varchar(50);not null;index" json:"notification_type" comment:"通知类型(SMS/WECHAT_WORK/EMAIL)"`
|
||||
NotificationScene string `gorm:"type:varchar(50);not null;index" json:"notification_scene" comment:"通知场景(ADMIN_NEW_APPLICATION/USER_CONTRACT_READY等)"`
|
||||
|
||||
// 接收方信息 - 通知的目标接收者
|
||||
Recipient string `gorm:"type:varchar(255);not null" json:"recipient" comment:"接收方标识(手机号/邮箱/用户ID)"`
|
||||
|
||||
// 消息内容 - 通知的具体内容信息
|
||||
Title string `gorm:"type:varchar(255)" json:"title,omitempty" comment:"通知标题"`
|
||||
Content string `gorm:"type:text;not null" json:"content" comment:"通知内容"`
|
||||
TemplateID string `gorm:"type:varchar(100)" json:"template_id,omitempty" comment:"消息模板ID"`
|
||||
TemplateParams string `gorm:"type:text" json:"template_params,omitempty" comment:"模板参数(JSON格式)"`
|
||||
|
||||
// 发送状态 - 记录通知的发送过程和结果
|
||||
Status string `gorm:"type:varchar(50);not null;index" json:"status" comment:"发送状态(PENDING/SENT/FAILED)"`
|
||||
ErrorMessage string `gorm:"type:varchar(500)" json:"error_message,omitempty" comment:"发送失败的错误信息"`
|
||||
SentAt *time.Time `json:"sent_at,omitempty" comment:"发送成功时间"`
|
||||
RetryCount int `gorm:"default:0" json:"retry_count" comment:"当前重试次数"`
|
||||
MaxRetryCount int `gorm:"default:3" json:"max_retry_count" comment:"最大重试次数"`
|
||||
|
||||
// 时间戳字段
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
|
||||
|
||||
// 关联关系
|
||||
Certification *Certification `gorm:"foreignKey:CertificationID" json:"certification,omitempty" comment:"关联的认证申请"`
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (NotificationRecord) TableName() string {
|
||||
return "notification_records"
|
||||
}
|
||||
|
||||
// IsPending 检查通知是否待发送
|
||||
// 判断通知是否处于等待发送的状态
|
||||
func (n *NotificationRecord) IsPending() bool {
|
||||
return n.Status == "PENDING"
|
||||
}
|
||||
|
||||
// IsSent 检查通知是否已发送
|
||||
// 判断通知是否已成功发送到接收方
|
||||
func (n *NotificationRecord) IsSent() bool {
|
||||
return n.Status == "SENT"
|
||||
}
|
||||
|
||||
// IsFailed 检查通知是否发送失败
|
||||
// 判断通知是否发送失败,包括网络错误、接收方无效等情况
|
||||
func (n *NotificationRecord) IsFailed() bool {
|
||||
return n.Status == "FAILED"
|
||||
}
|
||||
|
||||
// CanRetry 检查是否可以重试
|
||||
// 判断失败的通知是否还可以进行重试发送
|
||||
func (n *NotificationRecord) CanRetry() bool {
|
||||
return n.IsFailed() && n.RetryCount < n.MaxRetryCount
|
||||
}
|
||||
|
||||
// IncrementRetryCount 增加重试次数
|
||||
// 在重试发送时增加重试计数器
|
||||
func (n *NotificationRecord) IncrementRetryCount() {
|
||||
n.RetryCount++
|
||||
}
|
||||
|
||||
// GetStatusName 获取状态的中文名称
|
||||
// 将英文状态码转换为中文显示名称,用于前端展示
|
||||
func (n *NotificationRecord) GetStatusName() string {
|
||||
statusNames := map[string]string{
|
||||
"PENDING": "待发送",
|
||||
"SENT": "已发送",
|
||||
"FAILED": "发送失败",
|
||||
}
|
||||
|
||||
if name, exists := statusNames[n.Status]; exists {
|
||||
return name
|
||||
}
|
||||
return n.Status
|
||||
}
|
||||
|
||||
// GetNotificationTypeName 获取通知类型的中文名称
|
||||
// 将通知类型转换为中文显示名称,便于用户理解
|
||||
func (n *NotificationRecord) GetNotificationTypeName() string {
|
||||
typeNames := map[string]string{
|
||||
"SMS": "短信",
|
||||
"WECHAT_WORK": "企业微信",
|
||||
"EMAIL": "邮件",
|
||||
}
|
||||
|
||||
if name, exists := typeNames[n.NotificationType]; exists {
|
||||
return name
|
||||
}
|
||||
return n.NotificationType
|
||||
}
|
||||
|
||||
// GetNotificationSceneName 获取通知场景的中文名称
|
||||
// 将通知场景转换为中文显示名称,便于业务人员理解通知的触发原因
|
||||
func (n *NotificationRecord) GetNotificationSceneName() string {
|
||||
sceneNames := map[string]string{
|
||||
"ADMIN_NEW_APPLICATION": "管理员新申请通知",
|
||||
"USER_CONTRACT_READY": "用户合同就绪通知",
|
||||
"USER_CERTIFICATION_COMPLETED": "用户认证完成通知",
|
||||
"USER_FACE_VERIFY_FAILED": "用户人脸识别失败通知",
|
||||
"USER_CONTRACT_REJECTED": "用户合同被拒绝通知",
|
||||
}
|
||||
|
||||
if name, exists := sceneNames[n.NotificationScene]; exists {
|
||||
return name
|
||||
}
|
||||
return n.NotificationScene
|
||||
}
|
||||
88
internal/domains/certification/enums/certification_status.go
Normal file
88
internal/domains/certification/enums/certification_status.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package enums
|
||||
|
||||
// CertificationStatus 认证状态枚举
|
||||
type CertificationStatus string
|
||||
|
||||
const (
|
||||
// 主流程状态
|
||||
StatusPending CertificationStatus = "pending" // 待开始
|
||||
StatusInfoSubmitted CertificationStatus = "info_submitted" // 企业信息已提交
|
||||
StatusFaceVerified CertificationStatus = "face_verified" // 人脸识别完成
|
||||
StatusContractApplied CertificationStatus = "contract_applied" // 已申请合同
|
||||
StatusContractPending CertificationStatus = "contract_pending" // 合同待审核
|
||||
StatusContractApproved CertificationStatus = "contract_approved" // 合同已审核(有链接)
|
||||
StatusContractSigned CertificationStatus = "contract_signed" // 合同已签署
|
||||
StatusCompleted CertificationStatus = "completed" // 认证完成
|
||||
|
||||
// 失败和重试状态
|
||||
StatusFaceFailed CertificationStatus = "face_failed" // 人脸识别失败
|
||||
StatusSignFailed CertificationStatus = "sign_failed" // 签署失败
|
||||
StatusRejected CertificationStatus = "rejected" // 已拒绝
|
||||
)
|
||||
|
||||
// IsValidStatus 检查状态是否有效
|
||||
func IsValidStatus(status CertificationStatus) bool {
|
||||
validStatuses := []CertificationStatus{
|
||||
StatusPending, StatusInfoSubmitted, StatusFaceVerified,
|
||||
StatusContractApplied, StatusContractPending, StatusContractApproved,
|
||||
StatusContractSigned, StatusCompleted, StatusFaceFailed,
|
||||
StatusSignFailed, StatusRejected,
|
||||
}
|
||||
|
||||
for _, validStatus := range validStatuses {
|
||||
if status == validStatus {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GetStatusName 获取状态的中文名称
|
||||
func GetStatusName(status CertificationStatus) string {
|
||||
statusNames := map[CertificationStatus]string{
|
||||
StatusPending: "待开始",
|
||||
StatusInfoSubmitted: "企业信息已提交",
|
||||
StatusFaceVerified: "人脸识别完成",
|
||||
StatusContractApplied: "已申请合同",
|
||||
StatusContractPending: "合同待审核",
|
||||
StatusContractApproved: "合同已审核",
|
||||
StatusContractSigned: "合同已签署",
|
||||
StatusCompleted: "认证完成",
|
||||
StatusFaceFailed: "人脸识别失败",
|
||||
StatusSignFailed: "签署失败",
|
||||
StatusRejected: "已拒绝",
|
||||
}
|
||||
|
||||
if name, exists := statusNames[status]; exists {
|
||||
return name
|
||||
}
|
||||
return string(status)
|
||||
}
|
||||
|
||||
// IsFinalStatus 判断是否为最终状态
|
||||
func IsFinalStatus(status CertificationStatus) bool {
|
||||
finalStatuses := []CertificationStatus{
|
||||
StatusCompleted, StatusRejected,
|
||||
}
|
||||
|
||||
for _, finalStatus := range finalStatuses {
|
||||
if status == finalStatus {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsFailedStatus 判断是否为失败状态
|
||||
func IsFailedStatus(status CertificationStatus) bool {
|
||||
failedStatuses := []CertificationStatus{
|
||||
StatusFaceFailed, StatusSignFailed, StatusRejected,
|
||||
}
|
||||
|
||||
for _, failedStatus := range failedStatuses {
|
||||
if status == failedStatus {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
526
internal/domains/certification/events/certification_events.go
Normal file
526
internal/domains/certification/events/certification_events.go
Normal file
@@ -0,0 +1,526 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
)
|
||||
|
||||
// 认证事件类型常量
|
||||
const (
|
||||
EventTypeCertificationCreated = "certification.created"
|
||||
EventTypeCertificationSubmitted = "certification.submitted"
|
||||
EventTypeLicenseUploaded = "certification.license.uploaded"
|
||||
EventTypeOCRCompleted = "certification.ocr.completed"
|
||||
EventTypeEnterpriseInfoConfirmed = "certification.enterprise.confirmed"
|
||||
EventTypeFaceVerifyInitiated = "certification.face_verify.initiated"
|
||||
EventTypeFaceVerifyCompleted = "certification.face_verify.completed"
|
||||
EventTypeContractRequested = "certification.contract.requested"
|
||||
EventTypeContractGenerated = "certification.contract.generated"
|
||||
EventTypeContractSigned = "certification.contract.signed"
|
||||
EventTypeCertificationApproved = "certification.approved"
|
||||
EventTypeCertificationRejected = "certification.rejected"
|
||||
EventTypeWalletCreated = "certification.wallet.created"
|
||||
EventTypeCertificationCompleted = "certification.completed"
|
||||
EventTypeCertificationFailed = "certification.failed"
|
||||
)
|
||||
|
||||
// BaseCertificationEvent 认证事件基础结构
|
||||
type BaseCertificationEvent struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Version string `json:"version"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Source string `json:"source"`
|
||||
AggregateID string `json:"aggregate_id"`
|
||||
AggregateType string `json:"aggregate_type"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
Payload interface{} `json:"payload"`
|
||||
}
|
||||
|
||||
// 实现 Event 接口
|
||||
func (e *BaseCertificationEvent) GetID() string { return e.ID }
|
||||
func (e *BaseCertificationEvent) GetType() string { return e.Type }
|
||||
func (e *BaseCertificationEvent) GetVersion() string { return e.Version }
|
||||
func (e *BaseCertificationEvent) GetTimestamp() time.Time { return e.Timestamp }
|
||||
func (e *BaseCertificationEvent) GetSource() string { return e.Source }
|
||||
func (e *BaseCertificationEvent) GetAggregateID() string { return e.AggregateID }
|
||||
func (e *BaseCertificationEvent) GetAggregateType() string { return e.AggregateType }
|
||||
func (e *BaseCertificationEvent) GetPayload() interface{} { return e.Payload }
|
||||
func (e *BaseCertificationEvent) GetMetadata() map[string]interface{} { return e.Metadata }
|
||||
func (e *BaseCertificationEvent) Marshal() ([]byte, error) { return json.Marshal(e) }
|
||||
func (e *BaseCertificationEvent) Unmarshal(data []byte) error { return json.Unmarshal(data, e) }
|
||||
func (e *BaseCertificationEvent) GetDomainVersion() string { return e.Version }
|
||||
func (e *BaseCertificationEvent) GetCausationID() string { return e.ID }
|
||||
func (e *BaseCertificationEvent) GetCorrelationID() string { return e.ID }
|
||||
|
||||
// NewBaseCertificationEvent 创建基础认证事件
|
||||
func NewBaseCertificationEvent(eventType, aggregateID string, payload interface{}) *BaseCertificationEvent {
|
||||
return &BaseCertificationEvent{
|
||||
ID: generateEventID(),
|
||||
Type: eventType,
|
||||
Version: "1.0",
|
||||
Timestamp: time.Now(),
|
||||
Source: "certification-domain",
|
||||
AggregateID: aggregateID,
|
||||
AggregateType: "certification",
|
||||
Metadata: make(map[string]interface{}),
|
||||
Payload: payload,
|
||||
}
|
||||
}
|
||||
|
||||
// CertificationCreatedEvent 认证创建事件
|
||||
type CertificationCreatedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewCertificationCreatedEvent 创建认证创建事件
|
||||
func NewCertificationCreatedEvent(certification *entities.Certification) *CertificationCreatedEvent {
|
||||
event := &CertificationCreatedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeCertificationCreated,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// CertificationSubmittedEvent 认证提交事件
|
||||
type CertificationSubmittedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewCertificationSubmittedEvent 创建认证提交事件
|
||||
func NewCertificationSubmittedEvent(certification *entities.Certification) *CertificationSubmittedEvent {
|
||||
event := &CertificationSubmittedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeCertificationSubmitted,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// LicenseUploadedEvent 营业执照上传事件
|
||||
type LicenseUploadedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
FileURL string `json:"file_url"`
|
||||
FileName string `json:"file_name"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewLicenseUploadedEvent 创建营业执照上传事件
|
||||
func NewLicenseUploadedEvent(certification *entities.Certification, record *entities.LicenseUploadRecord) *LicenseUploadedEvent {
|
||||
event := &LicenseUploadedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeLicenseUploaded,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.FileURL = record.FileURL
|
||||
event.Data.FileName = record.OriginalFileName
|
||||
event.Data.FileSize = record.FileSize
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// OCRCompletedEvent OCR识别完成事件
|
||||
type OCRCompletedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
OCRResult map[string]interface{} `json:"ocr_result"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewOCRCompletedEvent 创建OCR识别完成事件
|
||||
func NewOCRCompletedEvent(certification *entities.Certification, ocrResult map[string]interface{}, confidence float64) *OCRCompletedEvent {
|
||||
event := &OCRCompletedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeOCRCompleted,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.OCRResult = ocrResult
|
||||
event.Data.Confidence = confidence
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// EnterpriseInfoConfirmedEvent 企业信息确认事件
|
||||
type EnterpriseInfoConfirmedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
EnterpriseInfo map[string]interface{} `json:"enterprise_info"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewEnterpriseInfoConfirmedEvent 创建企业信息确认事件
|
||||
func NewEnterpriseInfoConfirmedEvent(certification *entities.Certification, enterpriseInfo map[string]interface{}) *EnterpriseInfoConfirmedEvent {
|
||||
event := &EnterpriseInfoConfirmedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeEnterpriseInfoConfirmed,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.EnterpriseInfo = enterpriseInfo
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// FaceVerifyInitiatedEvent 人脸识别初始化事件
|
||||
type FaceVerifyInitiatedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
VerifyToken string `json:"verify_token"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewFaceVerifyInitiatedEvent 创建人脸识别初始化事件
|
||||
func NewFaceVerifyInitiatedEvent(certification *entities.Certification, verifyToken string) *FaceVerifyInitiatedEvent {
|
||||
event := &FaceVerifyInitiatedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeFaceVerifyInitiated,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.VerifyToken = verifyToken
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// FaceVerifyCompletedEvent 人脸识别完成事件
|
||||
type FaceVerifyCompletedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
VerifyToken string `json:"verify_token"`
|
||||
Success bool `json:"success"`
|
||||
Score float64 `json:"score"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewFaceVerifyCompletedEvent 创建人脸识别完成事件
|
||||
func NewFaceVerifyCompletedEvent(certification *entities.Certification, record *entities.FaceVerifyRecord) *FaceVerifyCompletedEvent {
|
||||
event := &FaceVerifyCompletedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeFaceVerifyCompleted,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.VerifyToken = record.CertifyID
|
||||
event.Data.Success = record.IsSuccess()
|
||||
event.Data.Score = record.VerifyScore
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// ContractRequestedEvent 合同申请事件
|
||||
type ContractRequestedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewContractRequestedEvent 创建合同申请事件
|
||||
func NewContractRequestedEvent(certification *entities.Certification) *ContractRequestedEvent {
|
||||
event := &ContractRequestedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeContractRequested,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// ContractGeneratedEvent 合同生成事件
|
||||
type ContractGeneratedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
ContractURL string `json:"contract_url"`
|
||||
ContractID string `json:"contract_id"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewContractGeneratedEvent 创建合同生成事件
|
||||
func NewContractGeneratedEvent(certification *entities.Certification, record *entities.ContractRecord) *ContractGeneratedEvent {
|
||||
event := &ContractGeneratedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeContractGenerated,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.ContractURL = record.ContractURL
|
||||
event.Data.ContractID = record.ID
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// ContractSignedEvent 合同签署事件
|
||||
type ContractSignedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
ContractID string `json:"contract_id"`
|
||||
SignedAt string `json:"signed_at"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewContractSignedEvent 创建合同签署事件
|
||||
func NewContractSignedEvent(certification *entities.Certification, record *entities.ContractRecord) *ContractSignedEvent {
|
||||
event := &ContractSignedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeContractSigned,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.ContractID = record.ID
|
||||
event.Data.SignedAt = record.SignedAt.Format(time.RFC3339)
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// CertificationApprovedEvent 认证审核通过事件
|
||||
type CertificationApprovedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
AdminID string `json:"admin_id"`
|
||||
ApprovedAt string `json:"approved_at"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewCertificationApprovedEvent 创建认证审核通过事件
|
||||
func NewCertificationApprovedEvent(certification *entities.Certification, adminID string) *CertificationApprovedEvent {
|
||||
event := &CertificationApprovedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeCertificationApproved,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.AdminID = adminID
|
||||
event.Data.ApprovedAt = time.Now().Format(time.RFC3339)
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// CertificationRejectedEvent 认证审核拒绝事件
|
||||
type CertificationRejectedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
AdminID string `json:"admin_id"`
|
||||
RejectReason string `json:"reject_reason"`
|
||||
RejectedAt string `json:"rejected_at"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewCertificationRejectedEvent 创建认证审核拒绝事件
|
||||
func NewCertificationRejectedEvent(certification *entities.Certification, adminID, rejectReason string) *CertificationRejectedEvent {
|
||||
event := &CertificationRejectedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeCertificationRejected,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.AdminID = adminID
|
||||
event.Data.RejectReason = rejectReason
|
||||
event.Data.RejectedAt = time.Now().Format(time.RFC3339)
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// WalletCreatedEvent 钱包创建事件
|
||||
type WalletCreatedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
AccessID string `json:"access_id"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewWalletCreatedEvent 创建钱包创建事件
|
||||
func NewWalletCreatedEvent(certification *entities.Certification, walletID, accessID string) *WalletCreatedEvent {
|
||||
event := &WalletCreatedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeWalletCreated,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.WalletID = walletID
|
||||
event.Data.AccessID = accessID
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// CertificationCompletedEvent 认证完成事件
|
||||
type CertificationCompletedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
CompletedAt string `json:"completed_at"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewCertificationCompletedEvent 创建认证完成事件
|
||||
func NewCertificationCompletedEvent(certification *entities.Certification, walletID string) *CertificationCompletedEvent {
|
||||
event := &CertificationCompletedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeCertificationCompleted,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.WalletID = walletID
|
||||
event.Data.CompletedAt = time.Now().Format(time.RFC3339)
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// CertificationFailedEvent 认证失败事件
|
||||
type CertificationFailedEvent struct {
|
||||
*BaseCertificationEvent
|
||||
Data struct {
|
||||
CertificationID string `json:"certification_id"`
|
||||
UserID string `json:"user_id"`
|
||||
FailedAt string `json:"failed_at"`
|
||||
FailureReason string `json:"failure_reason"`
|
||||
Status string `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewCertificationFailedEvent 创建认证失败事件
|
||||
func NewCertificationFailedEvent(certification *entities.Certification, failureReason string) *CertificationFailedEvent {
|
||||
event := &CertificationFailedEvent{
|
||||
BaseCertificationEvent: NewBaseCertificationEvent(
|
||||
EventTypeCertificationFailed,
|
||||
certification.ID,
|
||||
nil,
|
||||
),
|
||||
}
|
||||
event.Data.CertificationID = certification.ID
|
||||
event.Data.UserID = certification.UserID
|
||||
event.Data.FailedAt = time.Now().Format(time.RFC3339)
|
||||
event.Data.FailureReason = failureReason
|
||||
event.Data.Status = string(certification.Status)
|
||||
event.Payload = event.Data
|
||||
return event
|
||||
}
|
||||
|
||||
// generateEventID 生成事件ID
|
||||
func generateEventID() string {
|
||||
return time.Now().Format("20060102150405") + "-" + generateRandomString(8)
|
||||
}
|
||||
|
||||
// generateRandomString 生成随机字符串
|
||||
func generateRandomString(length int) string {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = charset[time.Now().UnixNano()%int64(len(charset))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
489
internal/domains/certification/events/event_handlers.go
Normal file
489
internal/domains/certification/events/event_handlers.go
Normal file
@@ -0,0 +1,489 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"tyapi-server/internal/shared/interfaces"
|
||||
"tyapi-server/internal/shared/notification"
|
||||
)
|
||||
|
||||
// CertificationEventHandler 认证事件处理器
|
||||
type CertificationEventHandler struct {
|
||||
logger *zap.Logger
|
||||
notification notification.WeChatWorkService
|
||||
name string
|
||||
eventTypes []string
|
||||
isAsync bool
|
||||
}
|
||||
|
||||
// NewCertificationEventHandler 创建认证事件处理器
|
||||
func NewCertificationEventHandler(logger *zap.Logger, notification notification.WeChatWorkService) *CertificationEventHandler {
|
||||
return &CertificationEventHandler{
|
||||
logger: logger,
|
||||
notification: notification,
|
||||
name: "certification-event-handler",
|
||||
eventTypes: []string{
|
||||
EventTypeCertificationCreated,
|
||||
EventTypeCertificationSubmitted,
|
||||
EventTypeLicenseUploaded,
|
||||
EventTypeOCRCompleted,
|
||||
EventTypeEnterpriseInfoConfirmed,
|
||||
EventTypeFaceVerifyInitiated,
|
||||
EventTypeFaceVerifyCompleted,
|
||||
EventTypeContractRequested,
|
||||
EventTypeContractGenerated,
|
||||
EventTypeContractSigned,
|
||||
EventTypeCertificationApproved,
|
||||
EventTypeCertificationRejected,
|
||||
EventTypeWalletCreated,
|
||||
EventTypeCertificationCompleted,
|
||||
EventTypeCertificationFailed,
|
||||
},
|
||||
isAsync: true,
|
||||
}
|
||||
}
|
||||
|
||||
// GetName 获取处理器名称
|
||||
func (h *CertificationEventHandler) GetName() string {
|
||||
return h.name
|
||||
}
|
||||
|
||||
// GetEventTypes 获取支持的事件类型
|
||||
func (h *CertificationEventHandler) GetEventTypes() []string {
|
||||
return h.eventTypes
|
||||
}
|
||||
|
||||
// IsAsync 是否为异步处理器
|
||||
func (h *CertificationEventHandler) IsAsync() bool {
|
||||
return h.isAsync
|
||||
}
|
||||
|
||||
// GetRetryConfig 获取重试配置
|
||||
func (h *CertificationEventHandler) GetRetryConfig() interfaces.RetryConfig {
|
||||
return interfaces.RetryConfig{
|
||||
MaxRetries: 3,
|
||||
RetryDelay: 5 * time.Second,
|
||||
BackoffFactor: 2.0,
|
||||
MaxDelay: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (h *CertificationEventHandler) Handle(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("处理认证事件",
|
||||
zap.String("event_type", event.GetType()),
|
||||
zap.String("event_id", event.GetID()),
|
||||
zap.String("aggregate_id", event.GetAggregateID()),
|
||||
)
|
||||
|
||||
switch event.GetType() {
|
||||
case EventTypeCertificationCreated:
|
||||
return h.handleCertificationCreated(ctx, event)
|
||||
case EventTypeCertificationSubmitted:
|
||||
return h.handleCertificationSubmitted(ctx, event)
|
||||
case EventTypeLicenseUploaded:
|
||||
return h.handleLicenseUploaded(ctx, event)
|
||||
case EventTypeOCRCompleted:
|
||||
return h.handleOCRCompleted(ctx, event)
|
||||
case EventTypeEnterpriseInfoConfirmed:
|
||||
return h.handleEnterpriseInfoConfirmed(ctx, event)
|
||||
case EventTypeFaceVerifyInitiated:
|
||||
return h.handleFaceVerifyInitiated(ctx, event)
|
||||
case EventTypeFaceVerifyCompleted:
|
||||
return h.handleFaceVerifyCompleted(ctx, event)
|
||||
case EventTypeContractRequested:
|
||||
return h.handleContractRequested(ctx, event)
|
||||
case EventTypeContractGenerated:
|
||||
return h.handleContractGenerated(ctx, event)
|
||||
case EventTypeContractSigned:
|
||||
return h.handleContractSigned(ctx, event)
|
||||
case EventTypeCertificationApproved:
|
||||
return h.handleCertificationApproved(ctx, event)
|
||||
case EventTypeCertificationRejected:
|
||||
return h.handleCertificationRejected(ctx, event)
|
||||
case EventTypeWalletCreated:
|
||||
return h.handleWalletCreated(ctx, event)
|
||||
case EventTypeCertificationCompleted:
|
||||
return h.handleCertificationCompleted(ctx, event)
|
||||
case EventTypeCertificationFailed:
|
||||
return h.handleCertificationFailed(ctx, event)
|
||||
default:
|
||||
h.logger.Warn("未知的事件类型", zap.String("event_type", event.GetType()))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// handleCertificationCreated 处理认证创建事件
|
||||
func (h *CertificationEventHandler) handleCertificationCreated(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("认证申请已创建",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("🎉 您的企业认证申请已创建成功!\n\n认证ID: %s\n创建时间: %s\n\n请按照指引完成后续认证步骤。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "认证申请创建成功", message)
|
||||
}
|
||||
|
||||
// handleCertificationSubmitted 处理认证提交事件
|
||||
func (h *CertificationEventHandler) handleCertificationSubmitted(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("认证申请已提交",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给管理员
|
||||
adminMessage := fmt.Sprintf("📋 新的企业认证申请待审核\n\n认证ID: %s\n用户ID: %s\n提交时间: %s\n\n请及时处理审核。",
|
||||
event.GetAggregateID(),
|
||||
h.extractUserID(event),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendAdminNotification(ctx, event, "新认证申请待审核", adminMessage)
|
||||
}
|
||||
|
||||
// handleLicenseUploaded 处理营业执照上传事件
|
||||
func (h *CertificationEventHandler) handleLicenseUploaded(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("营业执照已上传",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("📄 营业执照上传成功!\n\n认证ID: %s\n上传时间: %s\n\n系统正在识别营业执照信息,请稍候...",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "营业执照上传成功", message)
|
||||
}
|
||||
|
||||
// handleOCRCompleted 处理OCR识别完成事件
|
||||
func (h *CertificationEventHandler) handleOCRCompleted(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("OCR识别已完成",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("✅ OCR识别完成!\n\n认证ID: %s\n识别时间: %s\n\n请确认企业信息是否正确,如有问题请及时联系客服。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "OCR识别完成", message)
|
||||
}
|
||||
|
||||
// handleEnterpriseInfoConfirmed 处理企业信息确认事件
|
||||
func (h *CertificationEventHandler) handleEnterpriseInfoConfirmed(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("企业信息已确认",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("✅ 企业信息确认成功!\n\n认证ID: %s\n确认时间: %s\n\n下一步:请完成人脸识别验证。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "企业信息确认成功", message)
|
||||
}
|
||||
|
||||
// handleFaceVerifyInitiated 处理人脸识别初始化事件
|
||||
func (h *CertificationEventHandler) handleFaceVerifyInitiated(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("人脸识别已初始化",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("👤 人脸识别验证已开始!\n\n认证ID: %s\n开始时间: %s\n\n请按照指引完成人脸识别验证。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "人脸识别验证开始", message)
|
||||
}
|
||||
|
||||
// handleFaceVerifyCompleted 处理人脸识别完成事件
|
||||
func (h *CertificationEventHandler) handleFaceVerifyCompleted(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("人脸识别已完成",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("✅ 人脸识别验证完成!\n\n认证ID: %s\n完成时间: %s\n\n下一步:系统将为您申请电子合同。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "人脸识别验证完成", message)
|
||||
}
|
||||
|
||||
// handleContractRequested 处理合同申请事件
|
||||
func (h *CertificationEventHandler) handleContractRequested(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("电子合同申请已提交",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给管理员
|
||||
adminMessage := fmt.Sprintf("📋 新的电子合同申请待审核\n\n认证ID: %s\n用户ID: %s\n申请时间: %s\n\n请及时处理合同审核。",
|
||||
event.GetAggregateID(),
|
||||
h.extractUserID(event),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendAdminNotification(ctx, event, "新合同申请待审核", adminMessage)
|
||||
}
|
||||
|
||||
// handleContractGenerated 处理合同生成事件
|
||||
func (h *CertificationEventHandler) handleContractGenerated(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("电子合同已生成",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("📄 电子合同已生成!\n\n认证ID: %s\n生成时间: %s\n\n请及时签署电子合同以完成认证流程。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "电子合同已生成", message)
|
||||
}
|
||||
|
||||
// handleContractSigned 处理合同签署事件
|
||||
func (h *CertificationEventHandler) handleContractSigned(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("电子合同已签署",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("✅ 电子合同签署成功!\n\n认证ID: %s\n签署时间: %s\n\n您的企业认证申请已进入最终审核阶段。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "电子合同签署成功", message)
|
||||
}
|
||||
|
||||
// handleCertificationApproved 处理认证审核通过事件
|
||||
func (h *CertificationEventHandler) handleCertificationApproved(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("认证申请已审核通过",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("🎉 恭喜!您的企业认证申请已审核通过!\n\n认证ID: %s\n审核时间: %s\n\n系统正在为您创建钱包和访问密钥...",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "认证申请审核通过", message)
|
||||
}
|
||||
|
||||
// handleCertificationRejected 处理认证审核拒绝事件
|
||||
func (h *CertificationEventHandler) handleCertificationRejected(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("认证申请已被拒绝",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("❌ 很抱歉,您的企业认证申请未通过审核\n\n认证ID: %s\n拒绝时间: %s\n\n请根据拒绝原因修改后重新提交申请。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "认证申请审核未通过", message)
|
||||
}
|
||||
|
||||
// handleWalletCreated 处理钱包创建事件
|
||||
func (h *CertificationEventHandler) handleWalletCreated(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("钱包已创建",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("💰 钱包创建成功!\n\n认证ID: %s\n创建时间: %s\n\n您的企业钱包已激活,可以开始使用相关服务。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "钱包创建成功", message)
|
||||
}
|
||||
|
||||
// handleCertificationCompleted 处理认证完成事件
|
||||
func (h *CertificationEventHandler) handleCertificationCompleted(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Info("企业认证已完成",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("🎉 恭喜!您的企业认证已全部完成!\n\n认证ID: %s\n完成时间: %s\n\n您现在可以享受完整的企业级服务功能。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "企业认证完成", message)
|
||||
}
|
||||
|
||||
// handleCertificationFailed 处理认证失败事件
|
||||
func (h *CertificationEventHandler) handleCertificationFailed(ctx context.Context, event interfaces.Event) error {
|
||||
h.logger.Error("企业认证失败",
|
||||
zap.String("certification_id", event.GetAggregateID()),
|
||||
zap.String("user_id", h.extractUserID(event)),
|
||||
)
|
||||
|
||||
// 发送通知给用户
|
||||
message := fmt.Sprintf("❌ 企业认证流程遇到问题\n\n认证ID: %s\n失败时间: %s\n\n请联系客服获取帮助。",
|
||||
event.GetAggregateID(),
|
||||
event.GetTimestamp().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return h.sendUserNotification(ctx, event, "企业认证失败", message)
|
||||
}
|
||||
|
||||
// sendUserNotification 发送用户通知
|
||||
func (h *CertificationEventHandler) sendUserNotification(ctx context.Context, event interfaces.Event, title, message string) error {
|
||||
url := fmt.Sprintf("https://example.com/certification/%s", event.GetAggregateID())
|
||||
btnText := "查看详情"
|
||||
if err := h.notification.SendCardMessage(ctx, title, message, url, btnText); err != nil {
|
||||
h.logger.Error("发送用户通知失败",
|
||||
zap.String("event_type", event.GetType()),
|
||||
zap.String("event_id", event.GetID()),
|
||||
zap.Error(err),
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
h.logger.Info("用户通知发送成功",
|
||||
zap.String("event_type", event.GetType()),
|
||||
zap.String("event_id", event.GetID()),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendAdminNotification 发送管理员通知
|
||||
func (h *CertificationEventHandler) sendAdminNotification(ctx context.Context, event interfaces.Event, title, message string) error {
|
||||
url := fmt.Sprintf("https://admin.example.com/certification/%s", event.GetAggregateID())
|
||||
btnText := "立即处理"
|
||||
if err := h.notification.SendCardMessage(ctx, title, message, url, btnText); err != nil {
|
||||
h.logger.Error("发送管理员通知失败",
|
||||
zap.String("event_type", event.GetType()),
|
||||
zap.String("event_id", event.GetID()),
|
||||
zap.Error(err),
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
h.logger.Info("管理员通知发送成功",
|
||||
zap.String("event_type", event.GetType()),
|
||||
zap.String("event_id", event.GetID()),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractUserID 从事件中提取用户ID
|
||||
func (h *CertificationEventHandler) extractUserID(event interfaces.Event) string {
|
||||
if payload, ok := event.GetPayload().(map[string]interface{}); ok {
|
||||
if userID, exists := payload["user_id"]; exists {
|
||||
if id, ok := userID.(string); ok {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试从事件数据中提取
|
||||
if eventData, ok := event.(*BaseCertificationEvent); ok {
|
||||
if data, ok := eventData.Payload.(map[string]interface{}); ok {
|
||||
if userID, exists := data["user_id"]; exists {
|
||||
if id, ok := userID.(string); ok {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// LoggingEventHandler 日志记录事件处理器
|
||||
type LoggingEventHandler struct {
|
||||
logger *zap.Logger
|
||||
name string
|
||||
eventTypes []string
|
||||
isAsync bool
|
||||
}
|
||||
|
||||
// NewLoggingEventHandler 创建日志记录事件处理器
|
||||
func NewLoggingEventHandler(logger *zap.Logger) *LoggingEventHandler {
|
||||
return &LoggingEventHandler{
|
||||
logger: logger,
|
||||
name: "logging-event-handler",
|
||||
eventTypes: []string{
|
||||
EventTypeCertificationCreated,
|
||||
EventTypeCertificationSubmitted,
|
||||
EventTypeLicenseUploaded,
|
||||
EventTypeOCRCompleted,
|
||||
EventTypeEnterpriseInfoConfirmed,
|
||||
EventTypeFaceVerifyInitiated,
|
||||
EventTypeFaceVerifyCompleted,
|
||||
EventTypeContractRequested,
|
||||
EventTypeContractGenerated,
|
||||
EventTypeContractSigned,
|
||||
EventTypeCertificationApproved,
|
||||
EventTypeCertificationRejected,
|
||||
EventTypeWalletCreated,
|
||||
EventTypeCertificationCompleted,
|
||||
EventTypeCertificationFailed,
|
||||
},
|
||||
isAsync: false, // 同步处理,确保日志及时记录
|
||||
}
|
||||
}
|
||||
|
||||
// GetName 获取处理器名称
|
||||
func (l *LoggingEventHandler) GetName() string {
|
||||
return l.name
|
||||
}
|
||||
|
||||
// GetEventTypes 获取支持的事件类型
|
||||
func (l *LoggingEventHandler) GetEventTypes() []string {
|
||||
return l.eventTypes
|
||||
}
|
||||
|
||||
// IsAsync 是否为异步处理器
|
||||
func (l *LoggingEventHandler) IsAsync() bool {
|
||||
return l.isAsync
|
||||
}
|
||||
|
||||
// GetRetryConfig 获取重试配置
|
||||
func (l *LoggingEventHandler) GetRetryConfig() interfaces.RetryConfig {
|
||||
return interfaces.RetryConfig{
|
||||
MaxRetries: 1,
|
||||
RetryDelay: 1 * time.Second,
|
||||
BackoffFactor: 1.0,
|
||||
MaxDelay: 1 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (l *LoggingEventHandler) Handle(ctx context.Context, event interfaces.Event) error {
|
||||
// 记录结构化日志
|
||||
eventData, _ := json.Marshal(event.GetPayload())
|
||||
|
||||
l.logger.Info("认证事件记录",
|
||||
zap.String("event_id", event.GetID()),
|
||||
zap.String("event_type", event.GetType()),
|
||||
zap.String("aggregate_id", event.GetAggregateID()),
|
||||
zap.String("aggregate_type", event.GetAggregateType()),
|
||||
zap.Time("timestamp", event.GetTimestamp()),
|
||||
zap.String("source", event.GetSource()),
|
||||
zap.String("payload", string(eventData)),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
536
internal/domains/certification/handlers/certification_handler.go
Normal file
536
internal/domains/certification/handlers/certification_handler.go
Normal file
@@ -0,0 +1,536 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"tyapi-server/internal/domains/certification/dto"
|
||||
"tyapi-server/internal/domains/certification/services"
|
||||
"tyapi-server/internal/shared/interfaces"
|
||||
)
|
||||
|
||||
// CertificationHandler 认证处理器
|
||||
type CertificationHandler struct {
|
||||
certificationService *services.CertificationService
|
||||
response interfaces.ResponseBuilder
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewCertificationHandler 创建认证处理器
|
||||
func NewCertificationHandler(
|
||||
certificationService *services.CertificationService,
|
||||
response interfaces.ResponseBuilder,
|
||||
logger *zap.Logger,
|
||||
) *CertificationHandler {
|
||||
return &CertificationHandler{
|
||||
certificationService: certificationService,
|
||||
response: response,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateCertification 创建认证申请
|
||||
// @Summary 创建认证申请
|
||||
// @Description 用户创建企业认证申请
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} dto.CertificationCreateResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/create [post]
|
||||
func (h *CertificationHandler) CreateCertification(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.certificationService.CreateCertification(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
h.logger.Error("创建认证申请失败",
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
h.response.InternalError(c, "创建认证申请失败")
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "认证申请创建成功")
|
||||
}
|
||||
|
||||
// UploadLicense 上传营业执照
|
||||
// @Summary 上传营业执照
|
||||
// @Description 上传营业执照文件并进行OCR识别
|
||||
// @Tags 认证
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param file formData file true "营业执照文件"
|
||||
// @Success 200 {object} dto.UploadLicenseResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/upload-license [post]
|
||||
func (h *CertificationHandler) UploadLicense(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
// 获取上传的文件
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
h.logger.Error("获取上传文件失败", zap.Error(err))
|
||||
h.response.BadRequest(c, "请选择要上传的文件")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 检查文件类型
|
||||
fileName := header.Filename
|
||||
ext := strings.ToLower(filepath.Ext(fileName))
|
||||
allowedExts := []string{".jpg", ".jpeg", ".png", ".pdf"}
|
||||
|
||||
isAllowed := false
|
||||
for _, allowedExt := range allowedExts {
|
||||
if ext == allowedExt {
|
||||
isAllowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isAllowed {
|
||||
h.response.BadRequest(c, "文件格式不支持,仅支持 JPG、PNG、PDF 格式")
|
||||
return
|
||||
}
|
||||
|
||||
// 检查文件大小(限制为10MB)
|
||||
const maxFileSize = 10 * 1024 * 1024 // 10MB
|
||||
if header.Size > maxFileSize {
|
||||
h.response.BadRequest(c, "文件大小不能超过10MB")
|
||||
return
|
||||
}
|
||||
|
||||
// 读取文件内容
|
||||
fileBytes, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
h.logger.Error("读取文件内容失败", zap.Error(err))
|
||||
h.response.InternalError(c, "文件读取失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 调用服务上传文件
|
||||
result, err := h.certificationService.UploadLicense(c.Request.Context(), userID, fileBytes, fileName)
|
||||
if err != nil {
|
||||
h.logger.Error("上传营业执照失败",
|
||||
zap.String("user_id", userID),
|
||||
zap.String("file_name", fileName),
|
||||
zap.Error(err),
|
||||
)
|
||||
h.response.InternalError(c, "上传失败,请稍后重试")
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "营业执照上传成功")
|
||||
}
|
||||
|
||||
// SubmitEnterpriseInfo 提交企业信息
|
||||
// @Summary 提交企业信息
|
||||
// @Description 确认并提交企业四要素信息
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "认证申请ID"
|
||||
// @Param request body dto.SubmitEnterpriseInfoRequest true "企业信息"
|
||||
// @Success 200 {object} dto.SubmitEnterpriseInfoResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/{id}/submit-info [put]
|
||||
func (h *CertificationHandler) SubmitEnterpriseInfo(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
certificationID := c.Param("id")
|
||||
if certificationID == "" {
|
||||
h.response.BadRequest(c, "认证申请ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.SubmitEnterpriseInfoRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
h.logger.Error("参数绑定失败", zap.Error(err))
|
||||
h.response.BadRequest(c, "请求参数格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 验证企业信息
|
||||
if req.CompanyName == "" {
|
||||
h.response.BadRequest(c, "企业名称不能为空")
|
||||
return
|
||||
}
|
||||
if req.UnifiedSocialCode == "" {
|
||||
h.response.BadRequest(c, "统一社会信用代码不能为空")
|
||||
return
|
||||
}
|
||||
if req.LegalPersonName == "" {
|
||||
h.response.BadRequest(c, "法定代表人姓名不能为空")
|
||||
return
|
||||
}
|
||||
if req.LegalPersonID == "" {
|
||||
h.response.BadRequest(c, "法定代表人身份证号不能为空")
|
||||
return
|
||||
}
|
||||
if req.LicenseUploadRecordID == "" {
|
||||
h.response.BadRequest(c, "营业执照上传记录ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.certificationService.SubmitEnterpriseInfo(c.Request.Context(), certificationID, &req)
|
||||
if err != nil {
|
||||
h.logger.Error("提交企业信息失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
if strings.Contains(err.Error(), "已被使用") || strings.Contains(err.Error(), "不允许") {
|
||||
h.response.BadRequest(c, err.Error())
|
||||
} else {
|
||||
h.response.InternalError(c, "提交失败,请稍后重试")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "企业信息提交成功")
|
||||
}
|
||||
|
||||
// InitiateFaceVerify 初始化人脸识别
|
||||
// @Summary 初始化人脸识别
|
||||
// @Description 开始人脸识别认证流程
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "认证申请ID"
|
||||
// @Param request body dto.FaceVerifyRequest true "人脸识别请求"
|
||||
// @Success 200 {object} dto.FaceVerifyResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/{id}/face-verify [post]
|
||||
func (h *CertificationHandler) InitiateFaceVerify(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
certificationID := c.Param("id")
|
||||
if certificationID == "" {
|
||||
h.response.BadRequest(c, "认证申请ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.FaceVerifyRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
h.logger.Error("参数绑定失败", zap.Error(err))
|
||||
h.response.BadRequest(c, "请求参数格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if req.RealName == "" {
|
||||
h.response.BadRequest(c, "真实姓名不能为空")
|
||||
return
|
||||
}
|
||||
if req.IDCardNumber == "" {
|
||||
h.response.BadRequest(c, "身份证号不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.certificationService.InitiateFaceVerify(c.Request.Context(), certificationID, &req)
|
||||
if err != nil {
|
||||
h.logger.Error("初始化人脸识别失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
if strings.Contains(err.Error(), "不允许") {
|
||||
h.response.BadRequest(c, err.Error())
|
||||
} else {
|
||||
h.response.InternalError(c, "初始化失败,请稍后重试")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "人脸识别初始化成功")
|
||||
}
|
||||
|
||||
// ApplyContract 申请电子合同
|
||||
// @Summary 申请电子合同
|
||||
// @Description 申请生成企业认证电子合同
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "认证申请ID"
|
||||
// @Success 200 {object} dto.ApplyContractResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/{id}/apply-contract [post]
|
||||
func (h *CertificationHandler) ApplyContract(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
certificationID := c.Param("id")
|
||||
if certificationID == "" {
|
||||
h.response.BadRequest(c, "认证申请ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.certificationService.ApplyContract(c.Request.Context(), certificationID)
|
||||
if err != nil {
|
||||
h.logger.Error("申请电子合同失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
if strings.Contains(err.Error(), "不允许") {
|
||||
h.response.BadRequest(c, err.Error())
|
||||
} else {
|
||||
h.response.InternalError(c, "申请失败,请稍后重试")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "合同申请提交成功,请等待管理员审核")
|
||||
}
|
||||
|
||||
// GetCertificationStatus 获取认证状态
|
||||
// @Summary 获取认证状态
|
||||
// @Description 查询当前用户的认证申请状态和进度
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} dto.CertificationStatusResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/status [get]
|
||||
func (h *CertificationHandler) GetCertificationStatus(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.certificationService.GetCertificationStatus(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
h.logger.Error("获取认证状态失败",
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
if strings.Contains(err.Error(), "不存在") {
|
||||
h.response.NotFound(c, "未找到认证申请记录")
|
||||
} else {
|
||||
h.response.InternalError(c, "查询失败,请稍后重试")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "查询成功")
|
||||
}
|
||||
|
||||
// GetCertificationDetails 获取认证详情
|
||||
// @Summary 获取认证详情
|
||||
// @Description 获取指定认证申请的详细信息
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "认证申请ID"
|
||||
// @Success 200 {object} dto.CertificationStatusResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/{id} [get]
|
||||
func (h *CertificationHandler) GetCertificationDetails(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
certificationID := c.Param("id")
|
||||
if certificationID == "" {
|
||||
h.response.BadRequest(c, "认证申请ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
// 通过用户ID获取状态来确保用户只能查看自己的认证记录
|
||||
result, err := h.certificationService.GetCertificationStatus(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
h.logger.Error("获取认证详情失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
if strings.Contains(err.Error(), "不存在") {
|
||||
h.response.NotFound(c, "未找到认证申请记录")
|
||||
} else {
|
||||
h.response.InternalError(c, "查询失败,请稍后重试")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 检查是否是用户自己的认证记录
|
||||
if result.ID != certificationID {
|
||||
h.response.Forbidden(c, "无权访问此认证记录")
|
||||
return
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "查询成功")
|
||||
}
|
||||
|
||||
// RetryStep 重试认证步骤
|
||||
// @Summary 重试认证步骤
|
||||
// @Description 重试失败的认证步骤(如人脸识别失败、签署失败等)
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "认证申请ID"
|
||||
// @Param step query string true "重试步骤(face_verify, sign_contract)"
|
||||
// @Success 200 {object} interfaces.APIResponse
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/{id}/retry [post]
|
||||
func (h *CertificationHandler) RetryStep(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
certificationID := c.Param("id")
|
||||
if certificationID == "" {
|
||||
h.response.BadRequest(c, "认证申请ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
step := c.Query("step")
|
||||
if step == "" {
|
||||
h.response.BadRequest(c, "重试步骤不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: 实现重试逻辑
|
||||
// 这里需要根据不同的步骤调用状态机进行状态重置
|
||||
|
||||
h.logger.Info("重试认证步骤",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("user_id", userID),
|
||||
zap.String("step", step),
|
||||
)
|
||||
|
||||
h.response.Success(c, gin.H{
|
||||
"certification_id": certificationID,
|
||||
"step": step,
|
||||
"message": "重试操作已提交",
|
||||
}, "重试操作成功")
|
||||
}
|
||||
|
||||
// GetProgressStats 获取进度统计
|
||||
// @Summary 获取进度统计
|
||||
// @Description 获取用户认证申请的进度统计信息
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 400 {object} interfaces.APIResponse
|
||||
// @Failure 500 {object} interfaces.APIResponse
|
||||
// @Router /api/v1/certification/progress [get]
|
||||
func (h *CertificationHandler) GetProgressStats(c *gin.Context) {
|
||||
userID := c.GetString("user_id")
|
||||
if userID == "" {
|
||||
h.response.Unauthorized(c, "用户未认证")
|
||||
return
|
||||
}
|
||||
|
||||
// 获取认证状态
|
||||
status, err := h.certificationService.GetCertificationStatus(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "不存在") {
|
||||
h.response.Success(c, gin.H{
|
||||
"has_certification": false,
|
||||
"progress": 0,
|
||||
"status": "",
|
||||
"next_steps": []string{"开始企业认证"},
|
||||
}, "查询成功")
|
||||
return
|
||||
}
|
||||
h.response.InternalError(c, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 构建进度统计
|
||||
nextSteps := []string{}
|
||||
if status.IsUserActionRequired {
|
||||
switch status.Status {
|
||||
case "pending":
|
||||
nextSteps = append(nextSteps, "上传营业执照")
|
||||
case "info_submitted":
|
||||
nextSteps = append(nextSteps, "进行人脸识别")
|
||||
case "face_verified":
|
||||
nextSteps = append(nextSteps, "申请电子合同")
|
||||
case "contract_approved":
|
||||
nextSteps = append(nextSteps, "签署电子合同")
|
||||
case "face_failed":
|
||||
nextSteps = append(nextSteps, "重新进行人脸识别")
|
||||
case "sign_failed":
|
||||
nextSteps = append(nextSteps, "重新签署合同")
|
||||
}
|
||||
} else if status.IsAdminActionRequired {
|
||||
nextSteps = append(nextSteps, "等待管理员审核")
|
||||
} else {
|
||||
nextSteps = append(nextSteps, "认证流程已完成")
|
||||
}
|
||||
|
||||
result := gin.H{
|
||||
"has_certification": true,
|
||||
"certification_id": status.ID,
|
||||
"progress": status.Progress,
|
||||
"status": status.Status,
|
||||
"status_name": status.StatusName,
|
||||
"is_user_action_required": status.IsUserActionRequired,
|
||||
"is_admin_action_required": status.IsAdminActionRequired,
|
||||
"next_steps": nextSteps,
|
||||
"created_at": status.CreatedAt,
|
||||
"updated_at": status.UpdatedAt,
|
||||
}
|
||||
|
||||
h.response.Success(c, result, "查询成功")
|
||||
}
|
||||
|
||||
// parsePageParams 解析分页参数
|
||||
func (h *CertificationHandler) parsePageParams(c *gin.Context) (int, int) {
|
||||
page := 1
|
||||
pageSize := 20
|
||||
|
||||
if pageStr := c.Query("page"); pageStr != "" {
|
||||
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
|
||||
page = p
|
||||
}
|
||||
}
|
||||
|
||||
if sizeStr := c.Query("page_size"); sizeStr != "" {
|
||||
if s, err := strconv.Atoi(sizeStr); err == nil && s > 0 && s <= 100 {
|
||||
pageSize = s
|
||||
}
|
||||
}
|
||||
|
||||
return page, pageSize
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
"tyapi-server/internal/domains/certification/enums"
|
||||
)
|
||||
|
||||
// GormCertificationRepository GORM认证仓储实现
|
||||
type GormCertificationRepository struct {
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewGormCertificationRepository 创建GORM认证仓储
|
||||
func NewGormCertificationRepository(db *gorm.DB, logger *zap.Logger) CertificationRepository {
|
||||
return &GormCertificationRepository{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create 创建认证记录
|
||||
func (r *GormCertificationRepository) Create(ctx context.Context, cert *entities.Certification) error {
|
||||
if err := r.db.WithContext(ctx).Create(cert).Error; err != nil {
|
||||
r.logger.Error("创建认证记录失败",
|
||||
zap.String("user_id", cert.UserID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("创建认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("认证记录创建成功",
|
||||
zap.String("id", cert.ID),
|
||||
zap.String("user_id", cert.UserID),
|
||||
zap.String("status", string(cert.Status)),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID 根据ID获取认证记录
|
||||
func (r *GormCertificationRepository) GetByID(ctx context.Context, id string) (*entities.Certification, error) {
|
||||
var cert entities.Certification
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&cert, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("认证记录不存在")
|
||||
}
|
||||
r.logger.Error("获取认证记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &cert, nil
|
||||
}
|
||||
|
||||
// GetByUserID 根据用户ID获取认证记录
|
||||
func (r *GormCertificationRepository) GetByUserID(ctx context.Context, userID string) (*entities.Certification, error) {
|
||||
var cert entities.Certification
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&cert, "user_id = ?", userID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("用户认证记录不存在")
|
||||
}
|
||||
r.logger.Error("获取用户认证记录失败",
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取用户认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &cert, nil
|
||||
}
|
||||
|
||||
// Update 更新认证记录
|
||||
func (r *GormCertificationRepository) Update(ctx context.Context, cert *entities.Certification) error {
|
||||
if err := r.db.WithContext(ctx).Save(cert).Error; err != nil {
|
||||
r.logger.Error("更新认证记录失败",
|
||||
zap.String("id", cert.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("更新认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("认证记录更新成功",
|
||||
zap.String("id", cert.ID),
|
||||
zap.String("status", string(cert.Status)),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除认证记录(软删除)
|
||||
func (r *GormCertificationRepository) Delete(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Delete(&entities.Certification{}, "id = ?", id).Error; err != nil {
|
||||
r.logger.Error("删除认证记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("删除认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("认证记录删除成功", zap.String("id", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// List 获取认证记录列表
|
||||
func (r *GormCertificationRepository) List(ctx context.Context, page, pageSize int, status enums.CertificationStatus) ([]*entities.Certification, int, error) {
|
||||
var certs []*entities.Certification
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.Certification{})
|
||||
|
||||
// 如果指定了状态,添加状态过滤
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
// 获取总数
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
r.logger.Error("获取认证记录总数失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取认证记录总数失败: %w", err)
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&certs).Error; err != nil {
|
||||
r.logger.Error("获取认证记录列表失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取认证记录列表失败: %w", err)
|
||||
}
|
||||
|
||||
return certs, int(total), nil
|
||||
}
|
||||
|
||||
// GetByStatus 根据状态获取认证记录
|
||||
func (r *GormCertificationRepository) GetByStatus(ctx context.Context, status enums.CertificationStatus, page, pageSize int) ([]*entities.Certification, int, error) {
|
||||
return r.List(ctx, page, pageSize, status)
|
||||
}
|
||||
|
||||
// GetPendingApprovals 获取待审核的认证申请
|
||||
func (r *GormCertificationRepository) GetPendingApprovals(ctx context.Context, page, pageSize int) ([]*entities.Certification, int, error) {
|
||||
return r.GetByStatus(ctx, enums.StatusContractPending, page, pageSize)
|
||||
}
|
||||
|
||||
// GetWithEnterprise 获取包含企业信息的认证记录
|
||||
func (r *GormCertificationRepository) GetWithEnterprise(ctx context.Context, id string) (*entities.Certification, error) {
|
||||
var cert entities.Certification
|
||||
|
||||
if err := r.db.WithContext(ctx).Preload("Enterprise").First(&cert, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("认证记录不存在")
|
||||
}
|
||||
r.logger.Error("获取认证记录(含企业信息)失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &cert, nil
|
||||
}
|
||||
|
||||
// GetWithAllRelations 获取包含所有关联关系的认证记录
|
||||
func (r *GormCertificationRepository) GetWithAllRelations(ctx context.Context, id string) (*entities.Certification, error) {
|
||||
var cert entities.Certification
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Preload("Enterprise").
|
||||
Preload("LicenseUploadRecord").
|
||||
Preload("FaceVerifyRecords").
|
||||
Preload("ContractRecords").
|
||||
Preload("NotificationRecords").
|
||||
First(&cert, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("认证记录不存在")
|
||||
}
|
||||
r.logger.Error("获取认证记录(含所有关联)失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &cert, nil
|
||||
}
|
||||
|
||||
// CountByStatus 根据状态统计认证记录数量
|
||||
func (r *GormCertificationRepository) CountByStatus(ctx context.Context, status enums.CertificationStatus) (int64, error) {
|
||||
var count int64
|
||||
|
||||
if err := r.db.WithContext(ctx).Model(&entities.Certification{}).Where("status = ?", status).Count(&count).Error; err != nil {
|
||||
r.logger.Error("统计认证记录数量失败",
|
||||
zap.String("status", string(status)),
|
||||
zap.Error(err),
|
||||
)
|
||||
return 0, fmt.Errorf("统计认证记录数量失败: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CountByUserID 根据用户ID统计认证记录数量
|
||||
func (r *GormCertificationRepository) CountByUserID(ctx context.Context, userID string) (int64, error) {
|
||||
var count int64
|
||||
|
||||
if err := r.db.WithContext(ctx).Model(&entities.Certification{}).Where("user_id = ?", userID).Count(&count).Error; err != nil {
|
||||
r.logger.Error("统计用户认证记录数量失败",
|
||||
zap.String("user_id", userID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return 0, fmt.Errorf("统计用户认证记录数量失败: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
)
|
||||
|
||||
// GormContractRecordRepository GORM合同记录仓储实现
|
||||
type GormContractRecordRepository struct {
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewGormContractRecordRepository 创建GORM合同记录仓储
|
||||
func NewGormContractRecordRepository(db *gorm.DB, logger *zap.Logger) ContractRecordRepository {
|
||||
return &GormContractRecordRepository{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create 创建合同记录
|
||||
func (r *GormContractRecordRepository) Create(ctx context.Context, record *entities.ContractRecord) error {
|
||||
if err := r.db.WithContext(ctx).Create(record).Error; err != nil {
|
||||
r.logger.Error("创建合同记录失败",
|
||||
zap.String("certification_id", record.CertificationID),
|
||||
zap.String("contract_type", record.ContractType),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("创建合同记录失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("合同记录创建成功",
|
||||
zap.String("id", record.ID),
|
||||
zap.String("contract_type", record.ContractType),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID 根据ID获取合同记录
|
||||
func (r *GormContractRecordRepository) GetByID(ctx context.Context, id string) (*entities.ContractRecord, error) {
|
||||
var record entities.ContractRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&record, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("合同记录不存在")
|
||||
}
|
||||
r.logger.Error("获取合同记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取合同记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// GetByCertificationID 根据认证申请ID获取合同记录列表
|
||||
func (r *GormContractRecordRepository) GetByCertificationID(ctx context.Context, certificationID string) ([]*entities.ContractRecord, error) {
|
||||
var records []*entities.ContractRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).Where("certification_id = ?", certificationID).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
r.logger.Error("根据认证申请ID获取合同记录失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取合同记录失败: %w", err)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// Update 更新合同记录
|
||||
func (r *GormContractRecordRepository) Update(ctx context.Context, record *entities.ContractRecord) error {
|
||||
if err := r.db.WithContext(ctx).Save(record).Error; err != nil {
|
||||
r.logger.Error("更新合同记录失败",
|
||||
zap.String("id", record.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("更新合同记录失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除合同记录
|
||||
func (r *GormContractRecordRepository) Delete(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Delete(&entities.ContractRecord{}, "id = ?", id).Error; err != nil {
|
||||
r.logger.Error("删除合同记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("删除合同记录失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByUserID 根据用户ID获取合同记录列表
|
||||
func (r *GormContractRecordRepository) GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.ContractRecord, int, error) {
|
||||
var records []*entities.ContractRecord
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.ContractRecord{}).Where("user_id = ?", userID)
|
||||
|
||||
// 获取总数
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
r.logger.Error("获取用户合同记录总数失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取合同记录总数失败: %w", err)
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
r.logger.Error("获取用户合同记录列表失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取合同记录列表失败: %w", err)
|
||||
}
|
||||
|
||||
return records, int(total), nil
|
||||
}
|
||||
|
||||
// GetByStatus 根据状态获取合同记录列表
|
||||
func (r *GormContractRecordRepository) GetByStatus(ctx context.Context, status string, page, pageSize int) ([]*entities.ContractRecord, int, error) {
|
||||
var records []*entities.ContractRecord
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.ContractRecord{}).Where("status = ?", status)
|
||||
|
||||
// 获取总数
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
r.logger.Error("根据状态获取合同记录总数失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取合同记录总数失败: %w", err)
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
r.logger.Error("根据状态获取合同记录列表失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取合同记录列表失败: %w", err)
|
||||
}
|
||||
|
||||
return records, int(total), nil
|
||||
}
|
||||
|
||||
// GetPendingContracts 获取待审核的合同记录
|
||||
func (r *GormContractRecordRepository) GetPendingContracts(ctx context.Context, page, pageSize int) ([]*entities.ContractRecord, int, error) {
|
||||
return r.GetByStatus(ctx, "PENDING", page, pageSize)
|
||||
}
|
||||
|
||||
// GetExpiredSigningContracts 获取签署链接已过期的合同记录
|
||||
func (r *GormContractRecordRepository) GetExpiredSigningContracts(ctx context.Context, limit int) ([]*entities.ContractRecord, error) {
|
||||
var records []*entities.ContractRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("expires_at < NOW() AND status = ?", "APPROVED").
|
||||
Limit(limit).
|
||||
Order("expires_at ASC").
|
||||
Find(&records).Error; err != nil {
|
||||
r.logger.Error("获取过期签署合同记录失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("获取过期签署合同记录失败: %w", err)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// GetExpiredContracts 获取已过期的合同记录(通用方法)
|
||||
func (r *GormContractRecordRepository) GetExpiredContracts(ctx context.Context, limit int) ([]*entities.ContractRecord, error) {
|
||||
return r.GetExpiredSigningContracts(ctx, limit)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
)
|
||||
|
||||
// GormEnterpriseRepository GORM企业信息仓储实现
|
||||
type GormEnterpriseRepository struct {
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewGormEnterpriseRepository 创建GORM企业信息仓储
|
||||
func NewGormEnterpriseRepository(db *gorm.DB, logger *zap.Logger) EnterpriseRepository {
|
||||
return &GormEnterpriseRepository{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create 创建企业信息
|
||||
func (r *GormEnterpriseRepository) Create(ctx context.Context, enterprise *entities.Enterprise) error {
|
||||
if err := r.db.WithContext(ctx).Create(enterprise).Error; err != nil {
|
||||
r.logger.Error("创建企业信息失败",
|
||||
zap.String("certification_id", enterprise.CertificationID),
|
||||
zap.String("company_name", enterprise.CompanyName),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("创建企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("企业信息创建成功",
|
||||
zap.String("id", enterprise.ID),
|
||||
zap.String("company_name", enterprise.CompanyName),
|
||||
zap.String("unified_social_code", enterprise.UnifiedSocialCode),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID 根据ID获取企业信息
|
||||
func (r *GormEnterpriseRepository) GetByID(ctx context.Context, id string) (*entities.Enterprise, error) {
|
||||
var enterprise entities.Enterprise
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&enterprise, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("企业信息不存在")
|
||||
}
|
||||
r.logger.Error("获取企业信息失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
return &enterprise, nil
|
||||
}
|
||||
|
||||
// GetByCertificationID 根据认证ID获取企业信息
|
||||
func (r *GormEnterpriseRepository) GetByCertificationID(ctx context.Context, certificationID string) (*entities.Enterprise, error) {
|
||||
var enterprise entities.Enterprise
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&enterprise, "certification_id = ?", certificationID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("企业信息不存在")
|
||||
}
|
||||
r.logger.Error("根据认证ID获取企业信息失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
return &enterprise, nil
|
||||
}
|
||||
|
||||
// Update 更新企业信息
|
||||
func (r *GormEnterpriseRepository) Update(ctx context.Context, enterprise *entities.Enterprise) error {
|
||||
if err := r.db.WithContext(ctx).Save(enterprise).Error; err != nil {
|
||||
r.logger.Error("更新企业信息失败",
|
||||
zap.String("id", enterprise.ID),
|
||||
zap.String("company_name", enterprise.CompanyName),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("更新企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("企业信息更新成功",
|
||||
zap.String("id", enterprise.ID),
|
||||
zap.String("company_name", enterprise.CompanyName),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除企业信息(软删除)
|
||||
func (r *GormEnterpriseRepository) Delete(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Delete(&entities.Enterprise{}, "id = ?", id).Error; err != nil {
|
||||
r.logger.Error("删除企业信息失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("删除企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("企业信息删除成功", zap.String("id", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByUnifiedSocialCode 根据统一社会信用代码获取企业信息
|
||||
func (r *GormEnterpriseRepository) GetByUnifiedSocialCode(ctx context.Context, code string) (*entities.Enterprise, error) {
|
||||
var enterprise entities.Enterprise
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&enterprise, "unified_social_code = ?", code).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("企业信息不存在")
|
||||
}
|
||||
r.logger.Error("根据统一社会信用代码获取企业信息失败",
|
||||
zap.String("unified_social_code", code),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
return &enterprise, nil
|
||||
}
|
||||
|
||||
// ExistsByUnifiedSocialCode 检查统一社会信用代码是否已存在
|
||||
func (r *GormEnterpriseRepository) ExistsByUnifiedSocialCode(ctx context.Context, code string) (bool, error) {
|
||||
var count int64
|
||||
|
||||
if err := r.db.WithContext(ctx).Model(&entities.Enterprise{}).
|
||||
Where("unified_social_code = ?", code).Count(&count).Error; err != nil {
|
||||
r.logger.Error("检查统一社会信用代码是否存在失败",
|
||||
zap.String("unified_social_code", code),
|
||||
zap.Error(err),
|
||||
)
|
||||
return false, fmt.Errorf("检查统一社会信用代码失败: %w", err)
|
||||
}
|
||||
|
||||
return count > 0, nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
)
|
||||
|
||||
// GormFaceVerifyRecordRepository GORM人脸识别记录仓储实现
|
||||
type GormFaceVerifyRecordRepository struct {
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewGormFaceVerifyRecordRepository 创建GORM人脸识别记录仓储
|
||||
func NewGormFaceVerifyRecordRepository(db *gorm.DB, logger *zap.Logger) FaceVerifyRecordRepository {
|
||||
return &GormFaceVerifyRecordRepository{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create 创建人脸识别记录
|
||||
func (r *GormFaceVerifyRecordRepository) Create(ctx context.Context, record *entities.FaceVerifyRecord) error {
|
||||
if err := r.db.WithContext(ctx).Create(record).Error; err != nil {
|
||||
r.logger.Error("创建人脸识别记录失败",
|
||||
zap.String("certification_id", record.CertificationID),
|
||||
zap.String("certify_id", record.CertifyID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("创建人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("人脸识别记录创建成功",
|
||||
zap.String("id", record.ID),
|
||||
zap.String("certify_id", record.CertifyID),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID 根据ID获取人脸识别记录
|
||||
func (r *GormFaceVerifyRecordRepository) GetByID(ctx context.Context, id string) (*entities.FaceVerifyRecord, error) {
|
||||
var record entities.FaceVerifyRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&record, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("人脸识别记录不存在")
|
||||
}
|
||||
r.logger.Error("获取人脸识别记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// GetByCertifyID 根据认证ID获取人脸识别记录
|
||||
func (r *GormFaceVerifyRecordRepository) GetByCertifyID(ctx context.Context, certifyID string) (*entities.FaceVerifyRecord, error) {
|
||||
var record entities.FaceVerifyRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&record, "certify_id = ?", certifyID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("人脸识别记录不存在")
|
||||
}
|
||||
r.logger.Error("根据认证ID获取人脸识别记录失败",
|
||||
zap.String("certify_id", certifyID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// GetByCertificationID 根据认证申请ID获取人脸识别记录列表
|
||||
func (r *GormFaceVerifyRecordRepository) GetByCertificationID(ctx context.Context, certificationID string) ([]*entities.FaceVerifyRecord, error) {
|
||||
var records []*entities.FaceVerifyRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).Where("certification_id = ?", certificationID).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
r.logger.Error("根据认证申请ID获取人脸识别记录失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// Update 更新人脸识别记录
|
||||
func (r *GormFaceVerifyRecordRepository) Update(ctx context.Context, record *entities.FaceVerifyRecord) error {
|
||||
if err := r.db.WithContext(ctx).Save(record).Error; err != nil {
|
||||
r.logger.Error("更新人脸识别记录失败",
|
||||
zap.String("id", record.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("更新人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除人脸识别记录
|
||||
func (r *GormFaceVerifyRecordRepository) Delete(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Delete(&entities.FaceVerifyRecord{}, "id = ?", id).Error; err != nil {
|
||||
r.logger.Error("删除人脸识别记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("删除人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByUserID 根据用户ID获取人脸识别记录列表
|
||||
func (r *GormFaceVerifyRecordRepository) GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.FaceVerifyRecord, int, error) {
|
||||
var records []*entities.FaceVerifyRecord
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.FaceVerifyRecord{}).Where("user_id = ?", userID)
|
||||
|
||||
// 获取总数
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
r.logger.Error("获取用户人脸识别记录总数失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取人脸识别记录总数失败: %w", err)
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
r.logger.Error("获取用户人脸识别记录列表失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取人脸识别记录列表失败: %w", err)
|
||||
}
|
||||
|
||||
return records, int(total), nil
|
||||
}
|
||||
|
||||
// GetExpiredRecords 获取已过期的人脸识别记录
|
||||
func (r *GormFaceVerifyRecordRepository) GetExpiredRecords(ctx context.Context, limit int) ([]*entities.FaceVerifyRecord, error) {
|
||||
var records []*entities.FaceVerifyRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("expires_at < NOW() AND status = ?", "PROCESSING").
|
||||
Limit(limit).
|
||||
Order("expires_at ASC").
|
||||
Find(&records).Error; err != nil {
|
||||
r.logger.Error("获取过期人脸识别记录失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("获取过期人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
)
|
||||
|
||||
// GormLicenseUploadRecordRepository GORM营业执照上传记录仓储实现
|
||||
type GormLicenseUploadRecordRepository struct {
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewGormLicenseUploadRecordRepository 创建GORM营业执照上传记录仓储
|
||||
func NewGormLicenseUploadRecordRepository(db *gorm.DB, logger *zap.Logger) LicenseUploadRecordRepository {
|
||||
return &GormLicenseUploadRecordRepository{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create 创建上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) Create(ctx context.Context, record *entities.LicenseUploadRecord) error {
|
||||
if err := r.db.WithContext(ctx).Create(record).Error; err != nil {
|
||||
r.logger.Error("创建上传记录失败",
|
||||
zap.String("user_id", record.UserID),
|
||||
zap.String("file_name", record.OriginalFileName),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("创建上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("上传记录创建成功",
|
||||
zap.String("id", record.ID),
|
||||
zap.String("file_name", record.OriginalFileName),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID 根据ID获取上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) GetByID(ctx context.Context, id string) (*entities.LicenseUploadRecord, error) {
|
||||
var record entities.LicenseUploadRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&record, "id = ?", id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("上传记录不存在")
|
||||
}
|
||||
r.logger.Error("获取上传记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// GetByUserID 根据用户ID获取上传记录列表
|
||||
func (r *GormLicenseUploadRecordRepository) GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.LicenseUploadRecord, int, error) {
|
||||
var records []*entities.LicenseUploadRecord
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&entities.LicenseUploadRecord{}).Where("user_id = ?", userID)
|
||||
|
||||
// 获取总数
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
r.logger.Error("获取用户上传记录总数失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取上传记录总数失败: %w", err)
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
r.logger.Error("获取用户上传记录列表失败", zap.Error(err))
|
||||
return nil, 0, fmt.Errorf("获取上传记录列表失败: %w", err)
|
||||
}
|
||||
|
||||
return records, int(total), nil
|
||||
}
|
||||
|
||||
// GetByCertificationID 根据认证ID获取上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) GetByCertificationID(ctx context.Context, certificationID string) (*entities.LicenseUploadRecord, error) {
|
||||
var record entities.LicenseUploadRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&record, "certification_id = ?", certificationID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("上传记录不存在")
|
||||
}
|
||||
r.logger.Error("根据认证ID获取上传记录失败",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// Update 更新上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) Update(ctx context.Context, record *entities.LicenseUploadRecord) error {
|
||||
if err := r.db.WithContext(ctx).Save(record).Error; err != nil {
|
||||
r.logger.Error("更新上传记录失败",
|
||||
zap.String("id", record.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("更新上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) Delete(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Delete(&entities.LicenseUploadRecord{}, "id = ?", id).Error; err != nil {
|
||||
r.logger.Error("删除上传记录失败",
|
||||
zap.String("id", id),
|
||||
zap.Error(err),
|
||||
)
|
||||
return fmt.Errorf("删除上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByQiNiuKey 根据七牛云Key获取上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) GetByQiNiuKey(ctx context.Context, key string) (*entities.LicenseUploadRecord, error) {
|
||||
var record entities.LicenseUploadRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).First(&record, "qiniu_key = ?", key).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("上传记录不存在")
|
||||
}
|
||||
r.logger.Error("根据七牛云Key获取上传记录失败",
|
||||
zap.String("qiniu_key", key),
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("获取上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// GetPendingOCR 获取待OCR处理的上传记录
|
||||
func (r *GormLicenseUploadRecordRepository) GetPendingOCR(ctx context.Context, limit int) ([]*entities.LicenseUploadRecord, error) {
|
||||
var records []*entities.LicenseUploadRecord
|
||||
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("ocr_processed = ? OR (ocr_processed = ? AND ocr_success = ?)", false, true, false).
|
||||
Limit(limit).
|
||||
Order("created_at ASC").
|
||||
Find(&records).Error; err != nil {
|
||||
r.logger.Error("获取待OCR处理记录失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("获取待OCR处理记录失败: %w", err)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
105
internal/domains/certification/repositories/impl.go
Normal file
105
internal/domains/certification/repositories/impl.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
"tyapi-server/internal/domains/certification/enums"
|
||||
)
|
||||
|
||||
// CertificationRepository 认证仓储接口
|
||||
type CertificationRepository interface {
|
||||
// 基础CRUD操作
|
||||
Create(ctx context.Context, cert *entities.Certification) error
|
||||
GetByID(ctx context.Context, id string) (*entities.Certification, error)
|
||||
GetByUserID(ctx context.Context, userID string) (*entities.Certification, error)
|
||||
Update(ctx context.Context, cert *entities.Certification) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// 查询操作
|
||||
List(ctx context.Context, page, pageSize int, status enums.CertificationStatus) ([]*entities.Certification, int, error)
|
||||
GetByStatus(ctx context.Context, status enums.CertificationStatus, page, pageSize int) ([]*entities.Certification, int, error)
|
||||
GetPendingApprovals(ctx context.Context, page, pageSize int) ([]*entities.Certification, int, error)
|
||||
|
||||
// 关联查询
|
||||
GetWithEnterprise(ctx context.Context, id string) (*entities.Certification, error)
|
||||
GetWithAllRelations(ctx context.Context, id string) (*entities.Certification, error)
|
||||
|
||||
// 统计操作
|
||||
CountByStatus(ctx context.Context, status enums.CertificationStatus) (int64, error)
|
||||
CountByUserID(ctx context.Context, userID string) (int64, error)
|
||||
}
|
||||
|
||||
// EnterpriseRepository 企业信息仓储接口
|
||||
type EnterpriseRepository interface {
|
||||
// 基础CRUD操作
|
||||
Create(ctx context.Context, enterprise *entities.Enterprise) error
|
||||
GetByID(ctx context.Context, id string) (*entities.Enterprise, error)
|
||||
GetByCertificationID(ctx context.Context, certificationID string) (*entities.Enterprise, error)
|
||||
Update(ctx context.Context, enterprise *entities.Enterprise) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// 查询操作
|
||||
GetByUnifiedSocialCode(ctx context.Context, code string) (*entities.Enterprise, error)
|
||||
ExistsByUnifiedSocialCode(ctx context.Context, code string) (bool, error)
|
||||
}
|
||||
|
||||
// LicenseUploadRecordRepository 营业执照上传记录仓储接口
|
||||
type LicenseUploadRecordRepository interface {
|
||||
// 基础CRUD操作
|
||||
Create(ctx context.Context, record *entities.LicenseUploadRecord) error
|
||||
GetByID(ctx context.Context, id string) (*entities.LicenseUploadRecord, error)
|
||||
GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.LicenseUploadRecord, int, error)
|
||||
GetByCertificationID(ctx context.Context, certificationID string) (*entities.LicenseUploadRecord, error)
|
||||
Update(ctx context.Context, record *entities.LicenseUploadRecord) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// 查询操作
|
||||
GetByQiNiuKey(ctx context.Context, key string) (*entities.LicenseUploadRecord, error)
|
||||
GetPendingOCR(ctx context.Context, limit int) ([]*entities.LicenseUploadRecord, error)
|
||||
}
|
||||
|
||||
// FaceVerifyRecordRepository 人脸识别记录仓储接口
|
||||
type FaceVerifyRecordRepository interface {
|
||||
// 基础CRUD操作
|
||||
Create(ctx context.Context, record *entities.FaceVerifyRecord) error
|
||||
GetByID(ctx context.Context, id string) (*entities.FaceVerifyRecord, error)
|
||||
GetByCertifyID(ctx context.Context, certifyID string) (*entities.FaceVerifyRecord, error)
|
||||
GetByCertificationID(ctx context.Context, certificationID string) ([]*entities.FaceVerifyRecord, error)
|
||||
Update(ctx context.Context, record *entities.FaceVerifyRecord) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// 查询操作
|
||||
GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.FaceVerifyRecord, int, error)
|
||||
GetExpiredRecords(ctx context.Context, limit int) ([]*entities.FaceVerifyRecord, error)
|
||||
}
|
||||
|
||||
// ContractRecordRepository 合同记录仓储接口
|
||||
type ContractRecordRepository interface {
|
||||
// 基础CRUD操作
|
||||
Create(ctx context.Context, record *entities.ContractRecord) error
|
||||
GetByID(ctx context.Context, id string) (*entities.ContractRecord, error)
|
||||
GetByCertificationID(ctx context.Context, certificationID string) ([]*entities.ContractRecord, error)
|
||||
Update(ctx context.Context, record *entities.ContractRecord) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// 查询操作
|
||||
GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.ContractRecord, int, error)
|
||||
GetByStatus(ctx context.Context, status string, page, pageSize int) ([]*entities.ContractRecord, int, error)
|
||||
GetExpiredContracts(ctx context.Context, limit int) ([]*entities.ContractRecord, error)
|
||||
}
|
||||
|
||||
// NotificationRecordRepository 通知记录仓储接口
|
||||
type NotificationRecordRepository interface {
|
||||
// 基础CRUD操作
|
||||
Create(ctx context.Context, record *entities.NotificationRecord) error
|
||||
GetByID(ctx context.Context, id string) (*entities.NotificationRecord, error)
|
||||
GetByCertificationID(ctx context.Context, certificationID string) ([]*entities.NotificationRecord, error)
|
||||
Update(ctx context.Context, record *entities.NotificationRecord) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// 查询操作
|
||||
GetByUserID(ctx context.Context, userID string, page, pageSize int) ([]*entities.NotificationRecord, int, error)
|
||||
GetPendingNotifications(ctx context.Context, limit int) ([]*entities.NotificationRecord, error)
|
||||
GetFailedNotifications(ctx context.Context, limit int) ([]*entities.NotificationRecord, error)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"tyapi-server/internal/domains/certification/handlers"
|
||||
"tyapi-server/internal/shared/middleware"
|
||||
)
|
||||
|
||||
// CertificationRoutes 认证路由组
|
||||
type CertificationRoutes struct {
|
||||
certificationHandler *handlers.CertificationHandler
|
||||
authMiddleware *middleware.JWTAuthMiddleware
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewCertificationRoutes 创建认证路由
|
||||
func NewCertificationRoutes(
|
||||
certificationHandler *handlers.CertificationHandler,
|
||||
authMiddleware *middleware.JWTAuthMiddleware,
|
||||
logger *zap.Logger,
|
||||
) *CertificationRoutes {
|
||||
return &CertificationRoutes{
|
||||
certificationHandler: certificationHandler,
|
||||
authMiddleware: authMiddleware,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterRoutes 注册认证相关路由
|
||||
func (r *CertificationRoutes) RegisterRoutes(router *gin.Engine) {
|
||||
// 认证相关路由组,需要用户认证
|
||||
certificationGroup := router.Group("/api/v1/certification")
|
||||
certificationGroup.Use(r.authMiddleware.Handle())
|
||||
{
|
||||
// 创建认证申请
|
||||
certificationGroup.POST("/create", r.certificationHandler.CreateCertification)
|
||||
|
||||
// 上传营业执照
|
||||
certificationGroup.POST("/upload-license", r.certificationHandler.UploadLicense)
|
||||
|
||||
// 获取认证状态
|
||||
certificationGroup.GET("/status", r.certificationHandler.GetCertificationStatus)
|
||||
|
||||
// 获取进度统计
|
||||
certificationGroup.GET("/progress", r.certificationHandler.GetProgressStats)
|
||||
|
||||
// 提交企业信息
|
||||
certificationGroup.PUT("/:id/submit-info", r.certificationHandler.SubmitEnterpriseInfo)
|
||||
// 发起人脸识别验证
|
||||
certificationGroup.POST("/:id/face-verify", r.certificationHandler.InitiateFaceVerify)
|
||||
// 申请合同签署
|
||||
certificationGroup.POST("/:id/apply-contract", r.certificationHandler.ApplyContract)
|
||||
// 获取认证详情
|
||||
certificationGroup.GET("/:id", r.certificationHandler.GetCertificationDetails)
|
||||
// 重试认证步骤
|
||||
certificationGroup.POST("/:id/retry", r.certificationHandler.RetryStep)
|
||||
}
|
||||
|
||||
r.logger.Info("认证路由注册完成")
|
||||
}
|
||||
404
internal/domains/certification/services/certification_service.go
Normal file
404
internal/domains/certification/services/certification_service.go
Normal file
@@ -0,0 +1,404 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"tyapi-server/internal/domains/certification/dto"
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
"tyapi-server/internal/domains/certification/enums"
|
||||
"tyapi-server/internal/domains/certification/repositories"
|
||||
"tyapi-server/internal/shared/ocr"
|
||||
"tyapi-server/internal/shared/storage"
|
||||
)
|
||||
|
||||
// CertificationService 认证服务
|
||||
type CertificationService struct {
|
||||
certRepo repositories.CertificationRepository
|
||||
enterpriseRepo repositories.EnterpriseRepository
|
||||
licenseRepo repositories.LicenseUploadRecordRepository
|
||||
faceVerifyRepo repositories.FaceVerifyRecordRepository
|
||||
contractRepo repositories.ContractRecordRepository
|
||||
stateMachine *CertificationStateMachine
|
||||
storageService storage.StorageService
|
||||
ocrService ocr.OCRService
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewCertificationService 创建认证服务
|
||||
func NewCertificationService(
|
||||
certRepo repositories.CertificationRepository,
|
||||
enterpriseRepo repositories.EnterpriseRepository,
|
||||
licenseRepo repositories.LicenseUploadRecordRepository,
|
||||
faceVerifyRepo repositories.FaceVerifyRecordRepository,
|
||||
contractRepo repositories.ContractRecordRepository,
|
||||
stateMachine *CertificationStateMachine,
|
||||
storageService storage.StorageService,
|
||||
ocrService ocr.OCRService,
|
||||
logger *zap.Logger,
|
||||
) *CertificationService {
|
||||
return &CertificationService{
|
||||
certRepo: certRepo,
|
||||
enterpriseRepo: enterpriseRepo,
|
||||
licenseRepo: licenseRepo,
|
||||
faceVerifyRepo: faceVerifyRepo,
|
||||
contractRepo: contractRepo,
|
||||
stateMachine: stateMachine,
|
||||
storageService: storageService,
|
||||
ocrService: ocrService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateCertification 创建认证申请
|
||||
func (s *CertificationService) CreateCertification(ctx context.Context, userID string) (*dto.CertificationCreateResponse, error) {
|
||||
s.logger.Info("创建认证申请", zap.String("user_id", userID))
|
||||
|
||||
// 检查用户是否已有认证申请
|
||||
existingCert, err := s.certRepo.GetByUserID(ctx, userID)
|
||||
if err == nil && existingCert != nil {
|
||||
// 如果已存在且不是最终状态,返回现有申请
|
||||
if !enums.IsFinalStatus(existingCert.Status) {
|
||||
return &dto.CertificationCreateResponse{
|
||||
ID: existingCert.ID,
|
||||
UserID: existingCert.UserID,
|
||||
Status: existingCert.Status,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新的认证申请
|
||||
certification := &entities.Certification{
|
||||
ID: uuid.New().String(),
|
||||
UserID: userID,
|
||||
Status: enums.StatusPending,
|
||||
}
|
||||
|
||||
if err := s.certRepo.Create(ctx, certification); err != nil {
|
||||
return nil, fmt.Errorf("创建认证申请失败: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("认证申请创建成功",
|
||||
zap.String("certification_id", certification.ID),
|
||||
zap.String("user_id", userID),
|
||||
)
|
||||
|
||||
return &dto.CertificationCreateResponse{
|
||||
ID: certification.ID,
|
||||
UserID: certification.UserID,
|
||||
Status: certification.Status,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UploadLicense 上传营业执照并进行OCR识别
|
||||
func (s *CertificationService) UploadLicense(ctx context.Context, userID string, fileBytes []byte, fileName string) (*dto.UploadLicenseResponse, error) {
|
||||
s.logger.Info("上传营业执照",
|
||||
zap.String("user_id", userID),
|
||||
zap.String("file_name", fileName),
|
||||
zap.Int("file_size", len(fileBytes)),
|
||||
)
|
||||
|
||||
// 1. 上传文件到存储服务
|
||||
uploadResult, err := s.storageService.UploadFile(ctx, fileBytes, fileName)
|
||||
if err != nil {
|
||||
s.logger.Error("文件上传失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("文件上传失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 创建上传记录
|
||||
uploadRecord := &entities.LicenseUploadRecord{
|
||||
ID: uuid.New().String(),
|
||||
UserID: userID,
|
||||
OriginalFileName: fileName,
|
||||
FileSize: int64(len(fileBytes)),
|
||||
FileType: uploadResult.MimeType,
|
||||
FileURL: uploadResult.URL,
|
||||
QiNiuKey: uploadResult.Key,
|
||||
OCRProcessed: false,
|
||||
OCRSuccess: false,
|
||||
}
|
||||
|
||||
if err := s.licenseRepo.Create(ctx, uploadRecord); err != nil {
|
||||
s.logger.Error("创建上传记录失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("创建上传记录失败: %w", err)
|
||||
}
|
||||
|
||||
// 3. 尝试OCR识别
|
||||
var enterpriseInfo *dto.OCREnterpriseInfo
|
||||
var ocrError string
|
||||
|
||||
ocrResult, err := s.ocrService.RecognizeBusinessLicense(ctx, uploadResult.URL)
|
||||
if err != nil {
|
||||
s.logger.Warn("OCR识别失败", zap.Error(err))
|
||||
ocrError = err.Error()
|
||||
uploadRecord.OCRProcessed = true
|
||||
uploadRecord.OCRSuccess = false
|
||||
uploadRecord.OCRErrorMessage = ocrError
|
||||
} else {
|
||||
s.logger.Info("OCR识别成功",
|
||||
zap.String("company_name", ocrResult.CompanyName),
|
||||
zap.Float64("confidence", ocrResult.Confidence),
|
||||
)
|
||||
enterpriseInfo = ocrResult
|
||||
uploadRecord.OCRProcessed = true
|
||||
uploadRecord.OCRSuccess = true
|
||||
uploadRecord.OCRConfidence = ocrResult.Confidence
|
||||
// 存储OCR原始数据
|
||||
if rawData, err := s.serializeOCRResult(ocrResult); err == nil {
|
||||
uploadRecord.OCRRawData = rawData
|
||||
}
|
||||
}
|
||||
|
||||
// 更新上传记录
|
||||
if err := s.licenseRepo.Update(ctx, uploadRecord); err != nil {
|
||||
s.logger.Warn("更新上传记录失败", zap.Error(err))
|
||||
}
|
||||
|
||||
return &dto.UploadLicenseResponse{
|
||||
UploadRecordID: uploadRecord.ID,
|
||||
FileURL: uploadResult.URL,
|
||||
OCRProcessed: uploadRecord.OCRProcessed,
|
||||
OCRSuccess: uploadRecord.OCRSuccess,
|
||||
EnterpriseInfo: enterpriseInfo,
|
||||
OCRErrorMessage: ocrError,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SubmitEnterpriseInfo 提交企业信息
|
||||
func (s *CertificationService) SubmitEnterpriseInfo(ctx context.Context, certificationID string, req *dto.SubmitEnterpriseInfoRequest) (*dto.SubmitEnterpriseInfoResponse, error) {
|
||||
s.logger.Info("提交企业信息",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("company_name", req.CompanyName),
|
||||
)
|
||||
|
||||
// 1. 获取认证记录
|
||||
cert, err := s.certRepo.GetByID(ctx, certificationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 检查状态是否允许提交企业信息
|
||||
if !cert.CanTransitionTo(enums.StatusInfoSubmitted) {
|
||||
return nil, fmt.Errorf("当前状态不允许提交企业信息,当前状态: %s", enums.GetStatusName(cert.Status))
|
||||
}
|
||||
|
||||
// 3. 检查统一社会信用代码是否已存在
|
||||
exists, err := s.enterpriseRepo.ExistsByUnifiedSocialCode(ctx, req.UnifiedSocialCode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("检查企业信息失败: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil, fmt.Errorf("该统一社会信用代码已被使用")
|
||||
}
|
||||
|
||||
// 4. 创建企业信息
|
||||
enterprise := &entities.Enterprise{
|
||||
ID: uuid.New().String(),
|
||||
CertificationID: certificationID,
|
||||
CompanyName: req.CompanyName,
|
||||
UnifiedSocialCode: req.UnifiedSocialCode,
|
||||
LegalPersonName: req.LegalPersonName,
|
||||
LegalPersonID: req.LegalPersonID,
|
||||
LicenseUploadRecordID: req.LicenseUploadRecordID,
|
||||
IsOCRVerified: false,
|
||||
IsFaceVerified: false,
|
||||
}
|
||||
|
||||
if err := s.enterpriseRepo.Create(ctx, enterprise); err != nil {
|
||||
return nil, fmt.Errorf("创建企业信息失败: %w", err)
|
||||
}
|
||||
|
||||
// 5. 更新认证记录状态
|
||||
cert.EnterpriseID = &enterprise.ID
|
||||
if err := s.stateMachine.TransitionTo(ctx, certificationID, enums.StatusInfoSubmitted, true, false, nil); err != nil {
|
||||
return nil, fmt.Errorf("更新认证状态失败: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("企业信息提交成功",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("enterprise_id", enterprise.ID),
|
||||
)
|
||||
|
||||
return &dto.SubmitEnterpriseInfoResponse{
|
||||
ID: certificationID,
|
||||
Status: enums.StatusInfoSubmitted,
|
||||
Enterprise: &dto.EnterpriseInfoResponse{
|
||||
ID: enterprise.ID,
|
||||
CertificationID: enterprise.CertificationID,
|
||||
CompanyName: enterprise.CompanyName,
|
||||
UnifiedSocialCode: enterprise.UnifiedSocialCode,
|
||||
LegalPersonName: enterprise.LegalPersonName,
|
||||
LegalPersonID: enterprise.LegalPersonID,
|
||||
LicenseUploadRecordID: enterprise.LicenseUploadRecordID,
|
||||
IsOCRVerified: enterprise.IsOCRVerified,
|
||||
IsFaceVerified: enterprise.IsFaceVerified,
|
||||
CreatedAt: enterprise.CreatedAt,
|
||||
UpdatedAt: enterprise.UpdatedAt,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetCertificationStatus 获取认证状态
|
||||
func (s *CertificationService) GetCertificationStatus(ctx context.Context, userID string) (*dto.CertificationStatusResponse, error) {
|
||||
s.logger.Info("获取认证状态", zap.String("user_id", userID))
|
||||
|
||||
// 获取用户的认证记录
|
||||
cert, err := s.certRepo.GetByUserID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
// 获取企业信息
|
||||
var enterprise *dto.EnterpriseInfoResponse
|
||||
if cert.EnterpriseID != nil {
|
||||
ent, err := s.enterpriseRepo.GetByID(ctx, *cert.EnterpriseID)
|
||||
if err == nil {
|
||||
enterprise = &dto.EnterpriseInfoResponse{
|
||||
ID: ent.ID,
|
||||
CertificationID: ent.CertificationID,
|
||||
CompanyName: ent.CompanyName,
|
||||
UnifiedSocialCode: ent.UnifiedSocialCode,
|
||||
LegalPersonName: ent.LegalPersonName,
|
||||
LegalPersonID: ent.LegalPersonID,
|
||||
LicenseUploadRecordID: ent.LicenseUploadRecordID,
|
||||
IsOCRVerified: ent.IsOCRVerified,
|
||||
IsFaceVerified: ent.IsFaceVerified,
|
||||
CreatedAt: ent.CreatedAt,
|
||||
UpdatedAt: ent.UpdatedAt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &dto.CertificationStatusResponse{
|
||||
ID: cert.ID,
|
||||
UserID: cert.UserID,
|
||||
Status: cert.Status,
|
||||
StatusName: enums.GetStatusName(cert.Status),
|
||||
Progress: cert.GetProgressPercentage(),
|
||||
IsUserActionRequired: cert.IsUserActionRequired(),
|
||||
IsAdminActionRequired: cert.IsAdminActionRequired(),
|
||||
InfoSubmittedAt: cert.InfoSubmittedAt,
|
||||
FaceVerifiedAt: cert.FaceVerifiedAt,
|
||||
ContractAppliedAt: cert.ContractAppliedAt,
|
||||
ContractApprovedAt: cert.ContractApprovedAt,
|
||||
ContractSignedAt: cert.ContractSignedAt,
|
||||
CompletedAt: cert.CompletedAt,
|
||||
Enterprise: enterprise,
|
||||
ContractURL: cert.ContractURL,
|
||||
SigningURL: cert.SigningURL,
|
||||
RejectReason: cert.RejectReason,
|
||||
CreatedAt: cert.CreatedAt,
|
||||
UpdatedAt: cert.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// InitiateFaceVerify 初始化人脸识别
|
||||
func (s *CertificationService) InitiateFaceVerify(ctx context.Context, certificationID string, req *dto.FaceVerifyRequest) (*dto.FaceVerifyResponse, error) {
|
||||
s.logger.Info("初始化人脸识别",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("real_name", req.RealName),
|
||||
)
|
||||
|
||||
// 1. 获取认证记录
|
||||
cert, err := s.certRepo.GetByID(ctx, certificationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 检查状态
|
||||
if cert.Status != enums.StatusInfoSubmitted && cert.Status != enums.StatusFaceFailed {
|
||||
return nil, fmt.Errorf("当前状态不允许进行人脸识别,当前状态: %s", enums.GetStatusName(cert.Status))
|
||||
}
|
||||
|
||||
// 3. 创建人脸识别记录
|
||||
verifyRecord := &entities.FaceVerifyRecord{
|
||||
ID: uuid.New().String(),
|
||||
CertificationID: certificationID,
|
||||
UserID: cert.UserID,
|
||||
CertifyID: fmt.Sprintf("cert_%s_%d", certificationID, time.Now().Unix()),
|
||||
RealName: req.RealName,
|
||||
IDCardNumber: req.IDCardNumber,
|
||||
ReturnURL: req.ReturnURL,
|
||||
Status: "PROCESSING",
|
||||
ExpiresAt: time.Now().Add(24 * time.Hour), // 24小时过期
|
||||
}
|
||||
|
||||
// TODO: 实际调用阿里云人脸识别API
|
||||
// 这里是模拟实现
|
||||
verifyRecord.VerifyURL = fmt.Sprintf("https://face-verify.aliyun.com/verify?certifyId=%s", verifyRecord.CertifyID)
|
||||
|
||||
if err := s.faceVerifyRepo.Create(ctx, verifyRecord); err != nil {
|
||||
return nil, fmt.Errorf("创建人脸识别记录失败: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("人脸识别初始化成功",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("certify_id", verifyRecord.CertifyID),
|
||||
)
|
||||
|
||||
return &dto.FaceVerifyResponse{
|
||||
CertifyID: verifyRecord.CertifyID,
|
||||
VerifyURL: verifyRecord.VerifyURL,
|
||||
ExpiresAt: verifyRecord.ExpiresAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ApplyContract 申请电子合同
|
||||
func (s *CertificationService) ApplyContract(ctx context.Context, certificationID string) (*dto.ApplyContractResponse, error) {
|
||||
s.logger.Info("申请电子合同", zap.String("certification_id", certificationID))
|
||||
|
||||
// 1. 获取认证记录
|
||||
cert, err := s.certRepo.GetByID(ctx, certificationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 检查状态
|
||||
if !cert.CanTransitionTo(enums.StatusContractApplied) {
|
||||
return nil, fmt.Errorf("当前状态不允许申请合同,当前状态: %s", enums.GetStatusName(cert.Status))
|
||||
}
|
||||
|
||||
// 3. 转换状态
|
||||
if err := s.stateMachine.TransitionTo(ctx, certificationID, enums.StatusContractApplied, true, false, nil); err != nil {
|
||||
return nil, fmt.Errorf("更新认证状态失败: %w", err)
|
||||
}
|
||||
|
||||
// 4. 自动转换到待审核状态
|
||||
if err := s.stateMachine.TransitionTo(ctx, certificationID, enums.StatusContractPending, false, false, nil); err != nil {
|
||||
s.logger.Warn("自动转换到待审核状态失败", zap.Error(err))
|
||||
}
|
||||
|
||||
// 5. 创建合同记录
|
||||
contractRecord := &entities.ContractRecord{
|
||||
ID: uuid.New().String(),
|
||||
CertificationID: certificationID,
|
||||
UserID: cert.UserID,
|
||||
ContractType: "ENTERPRISE_CERTIFICATION",
|
||||
Status: "PENDING",
|
||||
}
|
||||
|
||||
if err := s.contractRepo.Create(ctx, contractRecord); err != nil {
|
||||
s.logger.Warn("创建合同记录失败", zap.Error(err))
|
||||
}
|
||||
|
||||
// TODO: 发送通知给管理员
|
||||
|
||||
s.logger.Info("合同申请成功", zap.String("certification_id", certificationID))
|
||||
|
||||
return &dto.ApplyContractResponse{
|
||||
ID: certificationID,
|
||||
Status: enums.StatusContractPending,
|
||||
ContractAppliedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// serializeOCRResult 序列化OCR结果
|
||||
func (s *CertificationService) serializeOCRResult(result *dto.OCREnterpriseInfo) (string, error) {
|
||||
// 简单的JSON序列化
|
||||
return fmt.Sprintf(`{"company_name":"%s","unified_social_code":"%s","legal_person_name":"%s","legal_person_id":"%s","confidence":%f}`,
|
||||
result.CompanyName, result.UnifiedSocialCode, result.LegalPersonName, result.LegalPersonID, result.Confidence), nil
|
||||
}
|
||||
287
internal/domains/certification/services/state_machine.go
Normal file
287
internal/domains/certification/services/state_machine.go
Normal file
@@ -0,0 +1,287 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"tyapi-server/internal/domains/certification/entities"
|
||||
"tyapi-server/internal/domains/certification/enums"
|
||||
"tyapi-server/internal/domains/certification/repositories"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// StateTransition 状态转换规则
|
||||
type StateTransition struct {
|
||||
From enums.CertificationStatus
|
||||
To enums.CertificationStatus
|
||||
Action string
|
||||
AllowUser bool // 是否允许用户操作
|
||||
AllowAdmin bool // 是否允许管理员操作
|
||||
RequiresValidation bool // 是否需要额外验证
|
||||
}
|
||||
|
||||
// CertificationStateMachine 认证状态机
|
||||
type CertificationStateMachine struct {
|
||||
transitions map[enums.CertificationStatus][]StateTransition
|
||||
certRepo repositories.CertificationRepository
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewCertificationStateMachine 创建认证状态机
|
||||
func NewCertificationStateMachine(
|
||||
certRepo repositories.CertificationRepository,
|
||||
logger *zap.Logger,
|
||||
) *CertificationStateMachine {
|
||||
sm := &CertificationStateMachine{
|
||||
transitions: make(map[enums.CertificationStatus][]StateTransition),
|
||||
certRepo: certRepo,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
// 初始化状态转换规则
|
||||
sm.initializeTransitions()
|
||||
return sm
|
||||
}
|
||||
|
||||
// initializeTransitions 初始化状态转换规则
|
||||
func (sm *CertificationStateMachine) initializeTransitions() {
|
||||
transitions := []StateTransition{
|
||||
// 正常流程转换
|
||||
{enums.StatusPending, enums.StatusInfoSubmitted, "submit_info", true, false, true},
|
||||
{enums.StatusInfoSubmitted, enums.StatusFaceVerified, "face_verify", true, false, true},
|
||||
{enums.StatusFaceVerified, enums.StatusContractApplied, "apply_contract", true, false, false},
|
||||
{enums.StatusContractApplied, enums.StatusContractPending, "system_process", false, false, false},
|
||||
{enums.StatusContractPending, enums.StatusContractApproved, "admin_approve", false, true, true},
|
||||
{enums.StatusContractApproved, enums.StatusContractSigned, "user_sign", true, false, true},
|
||||
{enums.StatusContractSigned, enums.StatusCompleted, "system_complete", false, false, false},
|
||||
|
||||
// 失败和重试转换
|
||||
{enums.StatusInfoSubmitted, enums.StatusFaceFailed, "face_fail", false, false, false},
|
||||
{enums.StatusFaceFailed, enums.StatusFaceVerified, "retry_face", true, false, true},
|
||||
{enums.StatusContractPending, enums.StatusRejected, "admin_reject", false, true, true},
|
||||
{enums.StatusRejected, enums.StatusInfoSubmitted, "restart_process", true, false, false},
|
||||
{enums.StatusContractApproved, enums.StatusSignFailed, "sign_fail", false, false, false},
|
||||
{enums.StatusSignFailed, enums.StatusContractSigned, "retry_sign", true, false, true},
|
||||
}
|
||||
|
||||
// 构建状态转换映射
|
||||
for _, transition := range transitions {
|
||||
sm.transitions[transition.From] = append(sm.transitions[transition.From], transition)
|
||||
}
|
||||
}
|
||||
|
||||
// CanTransition 检查是否可以转换到指定状态
|
||||
func (sm *CertificationStateMachine) CanTransition(
|
||||
from enums.CertificationStatus,
|
||||
to enums.CertificationStatus,
|
||||
isUser bool,
|
||||
isAdmin bool,
|
||||
) (bool, string) {
|
||||
validTransitions, exists := sm.transitions[from]
|
||||
if !exists {
|
||||
return false, "当前状态不支持任何转换"
|
||||
}
|
||||
|
||||
for _, transition := range validTransitions {
|
||||
if transition.To == to {
|
||||
if isUser && !transition.AllowUser {
|
||||
return false, "用户不允许执行此操作"
|
||||
}
|
||||
if isAdmin && !transition.AllowAdmin {
|
||||
return false, "管理员不允许执行此操作"
|
||||
}
|
||||
if !isUser && !isAdmin && (transition.AllowUser || transition.AllowAdmin) {
|
||||
return false, "此操作需要用户或管理员权限"
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
}
|
||||
|
||||
return false, "不支持的状态转换"
|
||||
}
|
||||
|
||||
// TransitionTo 执行状态转换
|
||||
func (sm *CertificationStateMachine) TransitionTo(
|
||||
ctx context.Context,
|
||||
certificationID string,
|
||||
targetStatus enums.CertificationStatus,
|
||||
isUser bool,
|
||||
isAdmin bool,
|
||||
metadata map[string]interface{},
|
||||
) error {
|
||||
// 获取当前认证记录
|
||||
cert, err := sm.certRepo.GetByID(ctx, certificationID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取认证记录失败: %w", err)
|
||||
}
|
||||
|
||||
// 检查是否可以转换
|
||||
canTransition, reason := sm.CanTransition(cert.Status, targetStatus, isUser, isAdmin)
|
||||
if !canTransition {
|
||||
return fmt.Errorf("状态转换失败: %s", reason)
|
||||
}
|
||||
|
||||
// 执行状态转换前的验证
|
||||
if err := sm.validateTransition(ctx, cert, targetStatus, metadata); err != nil {
|
||||
return fmt.Errorf("状态转换验证失败: %w", err)
|
||||
}
|
||||
|
||||
// 更新状态和时间戳
|
||||
oldStatus := cert.Status
|
||||
cert.Status = targetStatus
|
||||
sm.updateTimestamp(cert, targetStatus)
|
||||
|
||||
// 更新其他字段
|
||||
sm.updateCertificationFields(cert, targetStatus, metadata)
|
||||
|
||||
// 保存到数据库
|
||||
if err := sm.certRepo.Update(ctx, cert); err != nil {
|
||||
return fmt.Errorf("保存状态转换失败: %w", err)
|
||||
}
|
||||
|
||||
sm.logger.Info("认证状态转换成功",
|
||||
zap.String("certification_id", certificationID),
|
||||
zap.String("from_status", string(oldStatus)),
|
||||
zap.String("to_status", string(targetStatus)),
|
||||
zap.Bool("is_user", isUser),
|
||||
zap.Bool("is_admin", isAdmin),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateTimestamp 更新对应的时间戳字段
|
||||
func (sm *CertificationStateMachine) updateTimestamp(cert *entities.Certification, status enums.CertificationStatus) {
|
||||
now := time.Now()
|
||||
|
||||
switch status {
|
||||
case enums.StatusInfoSubmitted:
|
||||
cert.InfoSubmittedAt = &now
|
||||
case enums.StatusFaceVerified:
|
||||
cert.FaceVerifiedAt = &now
|
||||
case enums.StatusContractApplied:
|
||||
cert.ContractAppliedAt = &now
|
||||
case enums.StatusContractApproved:
|
||||
cert.ContractApprovedAt = &now
|
||||
case enums.StatusContractSigned:
|
||||
cert.ContractSignedAt = &now
|
||||
case enums.StatusCompleted:
|
||||
cert.CompletedAt = &now
|
||||
}
|
||||
}
|
||||
|
||||
// updateCertificationFields 根据状态更新认证记录的其他字段
|
||||
func (sm *CertificationStateMachine) updateCertificationFields(
|
||||
cert *entities.Certification,
|
||||
status enums.CertificationStatus,
|
||||
metadata map[string]interface{},
|
||||
) {
|
||||
switch status {
|
||||
case enums.StatusContractApproved:
|
||||
if adminID, ok := metadata["admin_id"].(string); ok {
|
||||
cert.AdminID = &adminID
|
||||
}
|
||||
if approvalNotes, ok := metadata["approval_notes"].(string); ok {
|
||||
cert.ApprovalNotes = approvalNotes
|
||||
}
|
||||
if signingURL, ok := metadata["signing_url"].(string); ok {
|
||||
cert.SigningURL = signingURL
|
||||
}
|
||||
|
||||
case enums.StatusRejected:
|
||||
if adminID, ok := metadata["admin_id"].(string); ok {
|
||||
cert.AdminID = &adminID
|
||||
}
|
||||
if rejectReason, ok := metadata["reject_reason"].(string); ok {
|
||||
cert.RejectReason = rejectReason
|
||||
}
|
||||
|
||||
case enums.StatusContractSigned:
|
||||
if contractURL, ok := metadata["contract_url"].(string); ok {
|
||||
cert.ContractURL = contractURL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// validateTransition 验证状态转换的有效性
|
||||
func (sm *CertificationStateMachine) validateTransition(
|
||||
ctx context.Context,
|
||||
cert *entities.Certification,
|
||||
targetStatus enums.CertificationStatus,
|
||||
metadata map[string]interface{},
|
||||
) error {
|
||||
switch targetStatus {
|
||||
case enums.StatusInfoSubmitted:
|
||||
// 验证企业信息是否完整
|
||||
if cert.EnterpriseID == nil {
|
||||
return fmt.Errorf("企业信息未提交")
|
||||
}
|
||||
|
||||
case enums.StatusFaceVerified:
|
||||
// 验证人脸识别是否成功
|
||||
// 这里可以添加人脸识别结果的验证逻辑
|
||||
|
||||
case enums.StatusContractApproved:
|
||||
// 验证管理员审核信息
|
||||
if metadata["signing_url"] == nil || metadata["signing_url"].(string) == "" {
|
||||
return fmt.Errorf("缺少合同签署链接")
|
||||
}
|
||||
|
||||
case enums.StatusRejected:
|
||||
// 验证拒绝原因
|
||||
if metadata["reject_reason"] == nil || metadata["reject_reason"].(string) == "" {
|
||||
return fmt.Errorf("缺少拒绝原因")
|
||||
}
|
||||
|
||||
case enums.StatusContractSigned:
|
||||
// 验证合同签署信息
|
||||
if cert.SigningURL == "" {
|
||||
return fmt.Errorf("缺少合同签署链接")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetValidNextStatuses 获取当前状态可以转换到的下一个状态列表
|
||||
func (sm *CertificationStateMachine) GetValidNextStatuses(
|
||||
currentStatus enums.CertificationStatus,
|
||||
isUser bool,
|
||||
isAdmin bool,
|
||||
) []enums.CertificationStatus {
|
||||
var validStatuses []enums.CertificationStatus
|
||||
|
||||
transitions, exists := sm.transitions[currentStatus]
|
||||
if !exists {
|
||||
return validStatuses
|
||||
}
|
||||
|
||||
for _, transition := range transitions {
|
||||
if (isUser && transition.AllowUser) || (isAdmin && transition.AllowAdmin) {
|
||||
validStatuses = append(validStatuses, transition.To)
|
||||
}
|
||||
}
|
||||
|
||||
return validStatuses
|
||||
}
|
||||
|
||||
// GetTransitionAction 获取状态转换对应的操作名称
|
||||
func (sm *CertificationStateMachine) GetTransitionAction(
|
||||
from enums.CertificationStatus,
|
||||
to enums.CertificationStatus,
|
||||
) string {
|
||||
transitions, exists := sm.transitions[from]
|
||||
if !exists {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, transition := range transitions {
|
||||
if transition.To == to {
|
||||
return transition.Action
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user