voucher/internal/biz/wechat_query.go

111 lines
2.4 KiB
Go

package biz
import (
"context"
"encoding/json"
"fmt"
"github.com/go-kratos/kratos/v2/log"
"time"
"voucher/internal/biz/bo"
"voucher/internal/biz/do"
)
func (v *VoucherBiz) PushWechatQuery(ctx context.Context, req *do.WechatQuery) error {
if v.Get(req.ProductNo) {
return fmt.Errorf("正在处理中")
}
_, err := v.ProductRepo.GetByProductNo(ctx, req.ProductNo)
if err != nil {
return err
}
queue := v.bc.RdsMQ.GetWechatQuery()
if queue == nil {
return fmt.Errorf("队列不存在")
}
msg, err := json.Marshal(req)
if err != nil {
return err
}
_, err = v.rdb.Rdb.RPush(ctx, queue.Name, msg).Result()
if err != nil {
return fmt.Errorf("添加到队列失败:%v", err)
}
v.Add(req.ProductNo)
return nil
}
func (v *VoucherBiz) WechatQuery(ctx context.Context, msg string) error {
var req *do.WechatQuery
if err := json.Unmarshal([]byte(msg), &req); err != nil {
return err
}
defer v.Remove(req.ProductNo)
start := time.Now()
log.Warnf("微信券查询处理开始:%s,msg:%s", start.String(), msg)
fmt.Printf("微信券查询处理开始:%s,msg:%s", start.String(), msg)
num := 0
err := v.OrderRepo.FinSucByStockIdInBatches(ctx, req, func(ctx context.Context, rows []*bo.OrderBo) error {
for _, order := range rows {
num += 1
if err := v.wechatQuery(ctx, order); err != nil {
log.Errorf("微信查询券订单状态发生错误,msg:%s,orderNo:%s,couponId:%s,appId:%s,openId:%s,err:%v",
msg, order.OrderNo, order.VoucherNo, order.AppID, order.Account, err)
}
}
time.Sleep(1 * time.Second)
return nil
})
log.Warnf("微信券查询处理耗时:%s,msg:%s,处理%d单", time.Now().Sub(start).String(), msg, num)
fmt.Printf("微信券查询处理耗时:%s,msg:%s,处理%d单", time.Now().Sub(start).String(), msg, num)
return err
}
func (v *VoucherBiz) wechatQuery(ctx context.Context, order *bo.OrderBo) error {
status, err := v.WechatCpnRepo.Query(ctx, order)
if err != nil {
return err
}
if status.IsUse() {
return v.queryUsed(ctx, order)
} else if status.IsExpired() {
return v.expired(ctx, order)
}
return nil
}
func (v *VoucherBiz) queryUsed(ctx context.Context, order *bo.OrderBo) error {
if order.Status.IsUse() {
log.Warnf("券状态已是已使用,忽略不处理,orderNo:%s", order.OrderNo)
return nil
}
if err := v.OrderRepo.Used(ctx, order.ID); err != nil {
return err
}
return v.notify(ctx, order)
}