2026-05-21 10:50:18 +08:00

99 lines
3.0 KiB
Go

package luckygift
import (
"chatapp3-golang/internal/utils"
"context"
"net/http"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
// LuckyGiftRewardDispatchEvent 是发送给 Java 房间侧统计消费者的中奖事件。
type LuckyGiftRewardDispatchEvent struct {
EventID string `json:"eventId"`
BusinessID string `json:"businessId"`
SysOrigin string `json:"sysOrigin"`
RoomID int64 `json:"roomId"`
SendUserID int64 `json:"sendUserId"`
GiftID int64 `json:"giftId"`
GiftPrice int64 `json:"giftPrice"`
GiftNum int64 `json:"giftNum"`
RewardTotal int64 `json:"rewardTotal"`
Results []LuckyGiftRewardDispatchResult `json:"results"`
PublishedAt int64 `json:"publishedAt"`
}
// LuckyGiftRewardDispatchResult 是单个中奖子单的房间侧结算载体。
type LuckyGiftRewardDispatchResult struct {
OrderSeed string `json:"orderSeed"`
AcceptUserID int64 `json:"acceptUserId"`
RewardNum int64 `json:"rewardNum"`
}
func (s *LuckyGiftService) publishRewardEvent(
ctx context.Context,
req LuckyGiftDrawRequest,
results []LuckyGiftDrawResult,
rewardTotal int64,
) error {
if rewardTotal <= 0 {
return nil
}
streamKey := strings.TrimSpace(s.cfg.LuckyGift.RewardStreamKey)
if streamKey == "" {
return NewAppError(http.StatusInternalServerError, "lucky_gift_reward_stream_not_configured", "lucky gift reward stream is not configured")
}
winResults := make([]LuckyGiftRewardDispatchResult, 0, len(results))
for _, item := range results {
if item.RewardNum <= 0 {
continue
}
winResults = append(winResults, LuckyGiftRewardDispatchResult{
OrderSeed: item.ID,
AcceptUserID: item.AcceptUserID,
RewardNum: item.RewardNum,
})
}
if len(winResults) == 0 {
return nil
}
event := LuckyGiftRewardDispatchEvent{
EventID: luckyGiftRewardEventID(req.BusinessID),
BusinessID: req.BusinessID,
SysOrigin: req.SysOrigin,
RoomID: req.RoomID,
SendUserID: req.SendUserID,
GiftID: req.GiftID,
GiftPrice: req.GiftPrice,
GiftNum: req.GiftNum,
RewardTotal: rewardTotal,
Results: winResults,
PublishedAt: time.Now().UnixMilli(),
}
_, err := s.repo.Redis.XAdd(ctx, &redis.XAddArgs{
Stream: streamKey,
MaxLen: s.cfg.LuckyGift.RewardStreamMaxLen,
Approx: s.cfg.LuckyGift.RewardStreamMaxLen > 0,
Values: map[string]any{
"eventId": event.EventID,
"businessId": event.BusinessID,
"payload": utils.MustJSONString(event, "{}"),
"publishedAt": event.PublishedAt,
},
}).Result()
if err != nil {
return NewAppError(http.StatusBadGateway, "lucky_gift_reward_stream_publish_failed", err.Error())
}
return nil
}
func luckyGiftRewardEventID(businessID string) string {
return "LUCKY_GIFT_REWARD:" + strings.TrimSpace(businessID)
}