package videocoupon import ( "errors" "sort" "time" "91porn-server/common/db" "91porn-server/common/stderr" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/options" ) // InsertOne ... func InsertOne(coupon UserGoldVideoCoupon) error { _, err := coll(nil).InsertOne(coupon) return err } // InsertMany batch insert func InsertMany(coupons []UserGoldVideoCoupon) error { _, err := coll(nil).InsertMany(coupons) return err } func InsertManyTrans(t *db.MongoTool, coupons []UserGoldVideoCoupon) error { _, err := coll(t).InsertMany(coupons) return err } // GetUserUnusedCouponCount 获取用户未使用的观影券总数 func GetUserUnusedCouponCount(uid uint64) (int64, error) { filter := bson.M{"uid": uid, "used": false} return coll(nil).Count(filter) } // GetCouponsByUID 根据uid获取观影券 func GetCouponsByUID(uid uint64) (list []UserGoldVideoCoupon, err error) { filter := bson.M{"uid": uid} err = coll(nil).Find(&list, filter) return } // GetByUIDAndCouponNum 根据uid和观影券面值查询观影券 func GetByUIDAndCouponNum(uid uint64, num int) (list []UserGoldVideoCoupon, err error) { filter := bson.M{"uid": uid, "num": num, "used": false} opts := options.FindOptions{} opts.SetSort(bson.D{{Key: "createdAt", Value: -1}}) err = coll(nil).Find(&list, filter) return } // UpdateCoupon 更新用户观影券 func UpdateCoupon(edit EditSelector) error { res, err := coll(nil).UpdateOne(bson.M{"_id": edit.ID}, bson.M{"$set": edit}) if err != nil { return err } if res.ModifiedCount+res.UpsertedCount < 1 { return errors.New("update failed") } return nil } // UseOneCoupon 使用一张观影券 func UseOneCoupon(coupons []UserGoldVideoCoupon) error { if len(coupons) == 0 { return stderr.GoldVideoCoupleNotExist } sort.Slice(coupons, func(i, j int) bool { // 优先使用最早创建的观影券 return coupons[i].CreatedAt.After(coupons[j].CreatedAt) }) edit := EditSelector{ ID: coupons[0].ID, Used: true, UpdatedAt: time.Now(), } return UpdateCoupon(edit) }