package promo import ( "context" promoModel "github.com/perfect-panel/server/internal/model/promo" "github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/xerr" "github.com/pkg/errors" ) type CreatePromoPriceLogic struct { logger.Logger ctx context.Context svcCtx *svc.ServiceContext } // Batch set promo price func NewCreatePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoPriceLogic { return &CreatePromoPriceLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *CreatePromoPriceLogic) CreatePromoPrice(req *types.CreatePromoPriceRequest) error { if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil { if promoModel.IsNotFound(err) { return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found") } l.Errorw("[CreatePromoPrice] Query Rule Error", logger.Field("error", err.Error())) return wrapQueryError("get promo rule failed", err) } data := make([]*promoModel.SubscribePromo, 0, len(req.Items)) subscribeIds := make([]int64, 0, len(req.Items)) for _, item := range req.Items { sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId) if err != nil { return xerr.NewErrCodeMsg(xerr.InvalidParams, "subscribe not found") } if item.PromoPrice >= sub.UnitPrice { return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo_price must be less than unit_price") } data = append(data, &promoModel.SubscribePromo{ SubscribeId: item.SubscribeId, PromoRuleId: req.PromoRuleId, PromoPrice: item.PromoPrice, }) subscribeIds = append(subscribeIds, item.SubscribeId) } if err := l.svcCtx.PromoModel.UpsertSubscribePromos(l.ctx, data); err != nil { l.Errorw("[CreatePromoPrice] Database Error", logger.Field("error", err.Error())) return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "set promo price failed: %v", err.Error()) } clearSubscribePromoCache(l.ctx, l.svcCtx, subscribeIds...) return nil }