This commit is contained in:
2026-04-21 22:36:48 +08:00
commit 488c695fdf
748 changed files with 266838 additions and 0 deletions

View File

@@ -0,0 +1,229 @@
package events
import (
"encoding/json"
"time"
"hyapi-server/internal/domains/certification/entities"
"github.com/google/uuid"
)
// 事件类型常量
const (
EventTypeCertificationCreated = "certification.created"
EventTypeEnterpriseInfoSubmitted = "enterprise.info.submitted"
EventTypeEnterpriseVerified = "enterprise.verified"
EventTypeContractApplied = "contract.applied"
EventTypeContractSigned = "contract.signed"
EventTypeCertificationCompleted = "certification.completed"
)
// 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"`
}
// 实现 DomainEvent 接口
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-service",
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
}
// EnterpriseInfoSubmittedEvent 企业信息提交事件
type EnterpriseInfoSubmittedEvent struct {
*BaseCertificationEvent
Data struct {
CertificationID string `json:"certification_id"`
UserID string `json:"user_id"`
Status string `json:"status"`
} `json:"data"`
}
// NewEnterpriseInfoSubmittedEvent 创建企业信息提交事件
func NewEnterpriseInfoSubmittedEvent(certification *entities.Certification) *EnterpriseInfoSubmittedEvent {
event := &EnterpriseInfoSubmittedEvent{
BaseCertificationEvent: NewBaseCertificationEvent(
EventTypeEnterpriseInfoSubmitted,
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
}
// EnterpriseVerifiedEvent 企业认证完成事件
type EnterpriseVerifiedEvent struct {
*BaseCertificationEvent
Data struct {
CertificationID string `json:"certification_id"`
UserID string `json:"user_id"`
Status string `json:"status"`
} `json:"data"`
}
// NewEnterpriseVerifiedEvent 创建企业认证完成事件
func NewEnterpriseVerifiedEvent(certification *entities.Certification) *EnterpriseVerifiedEvent {
event := &EnterpriseVerifiedEvent{
BaseCertificationEvent: NewBaseCertificationEvent(
EventTypeEnterpriseVerified,
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
}
// ContractAppliedEvent 合同申请事件
type ContractAppliedEvent struct {
*BaseCertificationEvent
Data struct {
CertificationID string `json:"certification_id"`
UserID string `json:"user_id"`
Status string `json:"status"`
} `json:"data"`
}
// NewContractAppliedEvent 创建合同申请事件
func NewContractAppliedEvent(certification *entities.Certification) *ContractAppliedEvent {
event := &ContractAppliedEvent{
BaseCertificationEvent: NewBaseCertificationEvent(
EventTypeContractApplied,
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
}
// ContractSignedEvent 合同签署事件
type ContractSignedEvent struct {
*BaseCertificationEvent
Data struct {
CertificationID string `json:"certification_id"`
UserID string `json:"user_id"`
ContractURL string `json:"contract_url"`
Status string `json:"status"`
} `json:"data"`
}
// NewContractSignedEvent 创建合同签署事件
func NewContractSignedEvent(certification *entities.Certification, contractURL string) *ContractSignedEvent {
event := &ContractSignedEvent{
BaseCertificationEvent: NewBaseCertificationEvent(
EventTypeContractSigned,
certification.ID,
nil,
),
}
event.Data.CertificationID = certification.ID
event.Data.UserID = certification.UserID
event.Data.ContractURL = contractURL
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"`
CompletedAt string `json:"completed_at"`
Status string `json:"status"`
} `json:"data"`
}
// NewCertificationCompletedEvent 创建认证完成事件
func NewCertificationCompletedEvent(certification *entities.Certification) *CertificationCompletedEvent {
event := &CertificationCompletedEvent{
BaseCertificationEvent: NewBaseCertificationEvent(
EventTypeCertificationCompleted,
certification.ID,
nil,
),
}
event.Data.CertificationID = certification.ID
event.Data.UserID = certification.UserID
event.Data.CompletedAt = time.Now().Format(time.RFC3339)
event.Data.Status = string(certification.Status)
event.Payload = event.Data
return event
}
// 工具函数
func generateEventID() string {
return uuid.New().String()
}

View File

@@ -0,0 +1,326 @@
package events
import (
"context"
"encoding/json"
"fmt"
"time"
"go.uber.org/zap"
"hyapi-server/internal/infrastructure/external/notification"
"hyapi-server/internal/shared/interfaces"
)
// 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,
EventTypeEnterpriseInfoSubmitted,
EventTypeEnterpriseVerified,
EventTypeContractApplied,
EventTypeContractSigned,
EventTypeCertificationCompleted,
},
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 EventTypeEnterpriseInfoSubmitted:
return h.handleEnterpriseInfoSubmitted(ctx, event)
case EventTypeEnterpriseVerified:
return h.handleEnterpriseVerified(ctx, event)
case EventTypeContractApplied:
return h.handleContractApplied(ctx, event)
case EventTypeContractSigned:
return h.handleContractSigned(ctx, event)
case EventTypeCertificationCompleted:
return h.handleCertificationCompleted(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)
}
// handleEnterpriseInfoSubmitted 处理企业信息提交事件
func (h *CertificationEventHandler) handleEnterpriseInfoSubmitted(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)
}
// handleEnterpriseVerified 处理企业认证完成事件
func (h *CertificationEventHandler) handleEnterpriseVerified(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)
}
// handleContractApplied 处理合同申请事件
func (h *CertificationEventHandler) handleContractApplied(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)
}
// 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)
}
// sendUserNotification 发送用户通知
func (h *CertificationEventHandler) sendUserNotification(ctx context.Context, event interfaces.Event, title, message string) error {
userID := h.extractUserID(event)
if userID == "" {
h.logger.Warn("无法提取用户ID跳过通知发送")
return nil
}
// 这里可以调用通知服务发送消息
h.logger.Info("发送用户通知",
zap.String("user_id", userID),
zap.String("title", title),
zap.String("message", message),
)
h.logger.Info("发送用户通知", zap.String("user_id", userID), zap.String("title", title), zap.String("message", message))
return nil
}
// sendAdminNotification 发送管理员通知
func (h *CertificationEventHandler) sendAdminNotification(ctx context.Context, event interfaces.Event, title, message string) error {
// 这里可以调用通知服务发送管理员消息
h.logger.Info("发送管理员通知",
zap.String("title", title),
zap.String("message", message),
)
return nil
}
// extractUserID 从事件中提取用户ID
func (h *CertificationEventHandler) extractUserID(event interfaces.Event) string {
payload := event.GetPayload()
if payload == nil {
return ""
}
// 尝试从payload中提取user_id
if data, ok := payload.(map[string]interface{}); ok {
if userID, exists := data["user_id"]; exists {
if str, ok := userID.(string); ok {
return str
}
}
}
// 尝试从JSON中解析
if data, ok := payload.(map[string]interface{}); ok {
if dataField, exists := data["data"]; exists {
if dataMap, ok := dataField.(map[string]interface{}); ok {
if userID, exists := dataMap["user_id"]; exists {
if str, ok := userID.(string); ok {
return str
}
}
}
}
}
// 尝试从JSON字符串解析
if jsonData, err := json.Marshal(payload); err == nil {
var data map[string]interface{}
if err := json.Unmarshal(jsonData, &data); err == nil {
if userID, exists := data["user_id"]; exists {
if str, ok := userID.(string); ok {
return str
}
}
if dataField, exists := data["data"]; exists {
if dataMap, ok := dataField.(map[string]interface{}); ok {
if userID, exists := dataMap["user_id"]; exists {
if str, ok := userID.(string); ok {
return str
}
}
}
}
}
}
return ""
}
// 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,
EventTypeEnterpriseInfoSubmitted,
EventTypeEnterpriseVerified,
EventTypeContractApplied,
EventTypeContractSigned,
EventTypeCertificationCompleted,
},
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: 0,
RetryDelay: 0,
BackoffFactor: 1.0,
MaxDelay: 0,
}
}
// Handle 处理事件
func (l *LoggingEventHandler) Handle(ctx context.Context, event interfaces.Event) error {
l.logger.Info("认证事件日志",
zap.String("event_type", event.GetType()),
zap.String("event_id", event.GetID()),
zap.String("aggregate_id", event.GetAggregateID()),
zap.Time("timestamp", event.GetTimestamp()),
zap.Any("payload", event.GetPayload()),
)
return nil
}