feat(distribution): 分站发布群只使用自己的二维码池
主站单独维护分站码池,池空时不再借用主站或其他分站,并去掉已停用的固定二维码入口。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -29,6 +29,7 @@ const (
|
||||
var (
|
||||
ErrQrCodeNotFound = errors.New("二维码不存在")
|
||||
ErrQrCodeCannotReenable = errors.New("已发放的二维码不能改回待用")
|
||||
ErrQrCodeSiteNotFound = errors.New("分销站点不存在")
|
||||
)
|
||||
|
||||
// CreateQrCodeRequest 创建二维码请求
|
||||
@@ -180,7 +181,8 @@ func (r *Repository) ListQrCodes(ctx context.Context, req QrCodeListRequest) ([]
|
||||
return applyQrCodeListFilters(
|
||||
r.db.WithContext(ctx).
|
||||
Table("chat_qrcode_pool AS q").
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id"),
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id").
|
||||
Where("q.distribution_site_id IS NULL"),
|
||||
req,
|
||||
now,
|
||||
)
|
||||
@@ -294,23 +296,24 @@ func (r *Repository) GetQrCodeStats(ctx context.Context) (*QrCodeStats, error) {
|
||||
stats := &QrCodeStats{}
|
||||
now := time.Now()
|
||||
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).Count(&stats.TotalCount).Error; err != nil {
|
||||
mainPool := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).Where("distribution_site_id IS NULL")
|
||||
if err := mainPool.Count(&stats.TotalCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&model.ChatQrCode{}).
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL").
|
||||
Where("status = ?", QrCodeStatusUsed).
|
||||
Count(&stats.UsedCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&model.ChatQrCode{}).
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL").
|
||||
Where("status = ?", QrCodeStatusDisabled).
|
||||
Count(&stats.DisabledCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&model.ChatQrCode{}).
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL").
|
||||
Where("status = ?", QrCodeStatusUnused).
|
||||
Where("expires_at IS NULL OR expires_at > ?", now).
|
||||
Count(&stats.UnusedCount).Error; err != nil {
|
||||
@@ -351,7 +354,7 @@ func (r *Repository) GetQrCodeOCRConfig(ctx context.Context) (*QrCodeOCRConfig,
|
||||
// UpdateQrCode 更新二维码
|
||||
func (r *Repository) UpdateQrCode(ctx context.Context, id uint64, req UpdateQrCodeRequest) error {
|
||||
var qrcode model.ChatQrCode
|
||||
if err := r.db.WithContext(ctx).First(&qrcode, id).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id IS NULL").First(&qrcode, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
@@ -406,7 +409,7 @@ func qrcodeWasIssued(qrcode model.ChatQrCode) bool {
|
||||
// DeleteQrCode 删除二维码
|
||||
func (r *Repository) DeleteQrCode(ctx context.Context, id uint64) error {
|
||||
var qrcode model.ChatQrCode
|
||||
if err := r.db.WithContext(ctx).First(&qrcode, id).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id IS NULL").First(&qrcode, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
@@ -422,7 +425,7 @@ func (r *Repository) BatchDeleteQrCodes(ctx context.Context, ids []uint64) (int6
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
result := r.db.WithContext(ctx).Where("id IN ?", ids).Delete(&model.ChatQrCode{})
|
||||
result := r.db.WithContext(ctx).Where("id IN ? AND distribution_site_id IS NULL", ids).Delete(&model.ChatQrCode{})
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
@@ -465,24 +468,28 @@ func (r *Repository) markQrCodeAsUsed(tx *gorm.DB, qrcodeID uint64, conversation
|
||||
|
||||
func deliverPendingQrCodes(tx *gorm.DB) ([]model.ChatMessage, error) {
|
||||
deliveredMessages := make([]model.ChatMessage, 0)
|
||||
skipped := make([]uint64, 0)
|
||||
for {
|
||||
var task model.ChatQrCodeDeliveryTask
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("status = ?", "pending").
|
||||
Order("created_at ASC, id ASC").
|
||||
First(&task).Error; err != nil {
|
||||
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("status = ?", "pending")
|
||||
if len(skipped) > 0 {
|
||||
query = query.Where("id NOT IN ?", skipped)
|
||||
}
|
||||
if err := query.Order("created_at ASC, id ASC").First(&task).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return deliveredMessages, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
qrcode, err := fetchUnusedQrCode(tx)
|
||||
qrcode, err := fetchUnusedQrCodeForConversation(tx, task.ConversationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if qrcode == nil {
|
||||
return deliveredMessages, nil
|
||||
skipped = append(skipped, task.ID)
|
||||
continue
|
||||
}
|
||||
|
||||
if err := markQrCodeAsUsed(tx, qrcode.ID, task.ConversationID); err != nil {
|
||||
@@ -516,6 +523,198 @@ func deliverPendingQrCodes(tx *gorm.DB) ([]model.ChatMessage, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Repository) ensureDistributionSite(ctx context.Context, siteID uint64) error {
|
||||
if siteID == 0 {
|
||||
return ErrQrCodeSiteNotFound
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.DistributionSite{}).Where("id = ?", siteID).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return ErrQrCodeSiteNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListSiteQrCodes(ctx context.Context, siteID uint64, req QrCodeListRequest) ([]QrCodeListItem, int64, error) {
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if req.Page < 1 {
|
||||
req.Page = 1
|
||||
}
|
||||
if req.Limit < 1 || req.Limit > 100 {
|
||||
req.Limit = 20
|
||||
}
|
||||
now := time.Now()
|
||||
baseQuery := func() *gorm.DB {
|
||||
return applyQrCodeListFilters(
|
||||
r.db.WithContext(ctx).
|
||||
Table("chat_qrcode_pool AS q").
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id").
|
||||
Where("q.distribution_site_id = ?", siteID),
|
||||
req,
|
||||
now,
|
||||
)
|
||||
}
|
||||
var total int64
|
||||
if err := baseQuery().Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var qrcodes []QrCodeListItem
|
||||
if err := baseQuery().
|
||||
Select("q.*, COALESCE(c.title, '') AS bound_conversation_title").
|
||||
Order("q.id DESC").
|
||||
Offset((req.Page - 1) * req.Limit).
|
||||
Limit(req.Limit).
|
||||
Scan(&qrcodes).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return qrcodes, total, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetSiteQrCodeStats(ctx context.Context, siteID uint64) (*QrCodeStats, error) {
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stats := &QrCodeStats{}
|
||||
now := time.Now()
|
||||
base := func() *gorm.DB {
|
||||
return r.db.WithContext(ctx).Model(&model.ChatQrCode{}).Where("distribution_site_id = ?", siteID)
|
||||
}
|
||||
if err := base().Count(&stats.TotalCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := base().Where("status = ?", QrCodeStatusUsed).Count(&stats.UsedCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := base().Where("status = ?", QrCodeStatusDisabled).Count(&stats.DisabledCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := base().
|
||||
Where("status = ?", QrCodeStatusUnused).
|
||||
Where("expires_at IS NULL OR expires_at > ?", now).
|
||||
Count(&stats.UnusedCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (r *Repository) BatchCreateSiteQrCode(ctx context.Context, adminID, siteID uint64, req BatchCreateQrCodeRequest) ([]model.ChatQrCode, error) {
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var qrcodes []model.ChatQrCode
|
||||
var deliveredMessages []model.ChatMessage
|
||||
defaultExpires := time.Now().Add(7 * 24 * time.Hour)
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, item := range req.Items {
|
||||
qr := model.ChatQrCode{
|
||||
ImageURL: item.ImageURL,
|
||||
GroupName: item.GroupName,
|
||||
DistributionSiteID: &siteID,
|
||||
Status: QrCodeStatusUnused,
|
||||
CreatedBy: adminID,
|
||||
Note: item.Note,
|
||||
ExpiresAt: item.ExpiresAt,
|
||||
}
|
||||
if qr.ExpiresAt == nil {
|
||||
expires := defaultExpires
|
||||
qr.ExpiresAt = &expires
|
||||
}
|
||||
qrcodes = append(qrcodes, qr)
|
||||
}
|
||||
if err := tx.Create(&qrcodes).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.notifyDeliveredQrCodeMessages(deliveredMessages)
|
||||
return qrcodes, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateSiteQrCode(ctx context.Context, siteID, id uint64, req UpdateQrCodeRequest) error {
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return err
|
||||
}
|
||||
var qrcode model.ChatQrCode
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID).First(&qrcode, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
return r.applyQrCodeUpdates(ctx, &qrcode, req)
|
||||
}
|
||||
|
||||
func (r *Repository) applyQrCodeUpdates(ctx context.Context, qrcode *model.ChatQrCode, req UpdateQrCodeRequest) error {
|
||||
updates := make(map[string]interface{})
|
||||
if req.ImageURL != nil {
|
||||
updates["image_url"] = *req.ImageURL
|
||||
}
|
||||
if req.GroupName != nil {
|
||||
updates["group_name"] = *req.GroupName
|
||||
}
|
||||
if req.Note != nil {
|
||||
updates["note"] = *req.Note
|
||||
}
|
||||
if req.WecomRenamed != nil {
|
||||
updates["wecom_renamed"] = *req.WecomRenamed
|
||||
}
|
||||
if req.Status != nil {
|
||||
if *req.Status != QrCodeStatusUnused && *req.Status != QrCodeStatusUsed && *req.Status != QrCodeStatusDisabled {
|
||||
return errors.New("无效的状态值")
|
||||
}
|
||||
if *req.Status == QrCodeStatusUnused && qrcodeWasIssued(*qrcode) {
|
||||
return ErrQrCodeCannotReenable
|
||||
}
|
||||
updates["status"] = *req.Status
|
||||
}
|
||||
if req.ExpiresAt != nil {
|
||||
updates["expires_at"] = req.ExpiresAt
|
||||
} else if req.ClearExpiresAt {
|
||||
updates["expires_at"] = nil
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Model(qrcode).Updates(updates).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteSiteQrCode(ctx context.Context, siteID, id uint64) error {
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return err
|
||||
}
|
||||
result := r.db.WithContext(ctx).Where("id = ? AND distribution_site_id = ?", id, siteID).Delete(&model.ChatQrCode{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) BatchDeleteSiteQrCodes(ctx context.Context, siteID uint64, ids []uint64) (int64, error) {
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
result := r.db.WithContext(ctx).Where("id IN ? AND distribution_site_id = ?", ids, siteID).Delete(&model.ChatQrCode{})
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
return result.RowsAffected, nil
|
||||
}
|
||||
|
||||
func (r *Repository) notifyDeliveredQrCodeMessages(messages []model.ChatMessage) {
|
||||
if r.hub == nil {
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user