This commit is contained in:
@@ -37,6 +37,7 @@ type InviteRepository interface {
|
||||
CreateTx(ctx context.Context, tx pgx.Tx, invite *model.InviteCode) error
|
||||
FindByCode(ctx context.Context, code int64) (*model.InviteCode, error)
|
||||
FindActiveByCode(ctx context.Context, code int64) (*model.InviteCode, error)
|
||||
FindActiveByUserID(ctx context.Context, userID int) (*model.InviteCode, error)
|
||||
DecrementCanBeUsedCountTx(ctx context.Context, tx pgx.Tx, code int64) error
|
||||
DeactivateExpired(ctx context.Context) (int, error)
|
||||
GetUserInvites(ctx context.Context, userID int) ([]*model.InviteCode, error)
|
||||
|
||||
@@ -110,6 +110,38 @@ func (r *inviteRepository) FindActiveByCode(ctx context.Context, code int64) (*m
|
||||
return invite, nil
|
||||
}
|
||||
|
||||
func (r *inviteRepository) FindActiveByUserID(ctx context.Context, userID int) (*model.InviteCode, error) {
|
||||
query := r.qb.Select(
|
||||
"id", "user_id", "code", "can_be_used_count",
|
||||
"is_active", "created_at", "expires_at",
|
||||
).From("invite_codes").Where(sq.And{
|
||||
sq.Eq{"user_id": userID},
|
||||
sq.Eq{"is_active": true},
|
||||
sq.Expr("expires_at > now()"),
|
||||
sq.Expr("can_be_used_count > 0"),
|
||||
}).OrderBy("created_at DESC").Limit(1)
|
||||
|
||||
sqlQuery, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, errs.NewInternalError(errs.DatabaseError, "failed to build query", err)
|
||||
}
|
||||
|
||||
invite := &model.InviteCode{}
|
||||
err = r.pool.QueryRow(ctx, sqlQuery, args...).Scan(
|
||||
&invite.ID, &invite.UserID, &invite.Code, &invite.CanBeUsedCount,
|
||||
&invite.IsActive, &invite.CreatedAt, &invite.ExpiresAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, errs.NewBusinessError(errs.InviteInvalidOrExpired, "no active invite code found")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errs.NewInternalError(errs.DatabaseError, "failed to find active invite code by user", err)
|
||||
}
|
||||
|
||||
return invite, nil
|
||||
}
|
||||
|
||||
func (r *inviteRepository) DecrementCanBeUsedCountTx(ctx context.Context, tx pgx.Tx, code int64) error {
|
||||
query := r.qb.Update("invite_codes").
|
||||
Set("can_be_used_count", sq.Expr("can_be_used_count - 1")).
|
||||
|
||||
Reference in New Issue
Block a user