-
-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Manage User Badges in the UI #31262
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
HenriquerPimentel
wants to merge
19
commits into
go-gitea:main
Choose a base branch
from
HenriquerPimentel:Badge
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Manage User Badges in the UI #31262
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
8b86c31
Implemented Badge Management in administration panel (#29798)
HenriquerPimentel f68e44d
Implemented User Badge Management Interface (#29798)
HenriquerPimentel d681313
Fix linting recommendations
HenriquerPimentel 10463ec
Merge branch 'main' into Badge
techknowlogick 52bc49d
fix lints
techknowlogick 401d257
Merge branch 'main' into Badge
techknowlogick d55e25f
update join
techknowlogick d9efbf3
close session immediately
techknowlogick ae9c0a6
Merge branch 'main' into Badge
techknowlogick 9234ef5
Merge branch 'main' into Badge
techknowlogick f601501
Update per feedback
techknowlogick 789b73b
update per feedback
techknowlogick f5c6a31
fix lint
techknowlogick 4890a15
Merge branch 'main' into Badge
techknowlogick 52957f4
Merge branch 'main' into Badge
techknowlogick 6e7fc93
Merge remote-tracking branch 'upstream/main' into Badge
techknowlogick 50f7ce1
update per feedback
techknowlogick ebc487b
User badge model fixes for RemoveUserBadges and AddUserBadges
2a69304
use the link-action approach for deletion
techknowlogick File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
- | ||
id: 1 | ||
slug: badge1 | ||
description: just a test badge | ||
image_url: badge1.png |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
// Copyright 2025 The Gitea Authors. All rights reserved. | ||
// SPDX-License-Identifier: MIT | ||
|
||
package v1_25 | ||
|
||
import ( | ||
"fmt" | ||
|
||
"xorm.io/xorm" | ||
"xorm.io/xorm/schemas" | ||
) | ||
|
||
type UserBadge struct { //revive:disable-line:exported | ||
ID int64 `xorm:"pk autoincr"` | ||
BadgeID int64 | ||
UserID int64 | ||
} | ||
|
||
// TableIndices implements xorm's TableIndices interface | ||
func (n *UserBadge) TableIndices() []*schemas.Index { | ||
indices := make([]*schemas.Index, 0, 1) | ||
ubUnique := schemas.NewIndex("unique_user_badge", schemas.UniqueType) | ||
ubUnique.AddColumn("user_id", "badge_id") | ||
indices = append(indices, ubUnique) | ||
return indices | ||
} | ||
|
||
// AddUniqueIndexForUserBadge adds a compound unique indexes for user badge table | ||
// and it replaces an old index on user_id | ||
func AddUniqueIndexForUserBadge(x *xorm.Engine) error { | ||
// remove possible duplicated records in table user_badge | ||
type result struct { | ||
UserID int64 | ||
BadgeID int64 | ||
Cnt int | ||
} | ||
var results []result | ||
if err := x.Select("user_id, badge_id, count(*) as cnt"). | ||
Table("user_badge"). | ||
GroupBy("user_id, badge_id"). | ||
Having("count(*) > 1"). | ||
Find(&results); err != nil { | ||
return err | ||
} | ||
for _, r := range results { | ||
if x.Dialect().URI().DBType == schemas.MSSQL { | ||
if _, err := x.Exec(fmt.Sprintf("delete from user_badge where id in (SELECT top %d id FROM user_badge WHERE user_id = ? and badge_id = ?)", r.Cnt-1), r.UserID, r.BadgeID); err != nil { | ||
return err | ||
} | ||
} else { | ||
var ids []int64 | ||
if err := x.SQL("SELECT id FROM user_badge WHERE user_id = ? and badge_id = ? limit ?", r.UserID, r.BadgeID, r.Cnt-1).Find(&ids); err != nil { | ||
return err | ||
} | ||
if _, err := x.Table("user_badge").In("id", ids).Delete(); err != nil { | ||
return err | ||
} | ||
} | ||
} | ||
|
||
return x.Sync(new(UserBadge)) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,8 +6,13 @@ package user | |
import ( | ||
"context" | ||
"fmt" | ||
"strings" | ||
|
||
"code.gitea.io/gitea/models/db" | ||
"code.gitea.io/gitea/modules/util" | ||
|
||
"xorm.io/builder" | ||
"xorm.io/xorm/schemas" | ||
) | ||
|
||
// Badge represents a user badge | ||
|
@@ -25,6 +30,59 @@ type UserBadge struct { //nolint:revive // export stutter | |
UserID int64 `xorm:"INDEX"` | ||
} | ||
|
||
// TableIndices implements xorm's TableIndices interface | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So that please remove the index tags in the struct |
||
func (n *UserBadge) TableIndices() []*schemas.Index { | ||
indices := make([]*schemas.Index, 0, 1) | ||
ubUnique := schemas.NewIndex("unique_user_badge", schemas.UniqueType) | ||
ubUnique.AddColumn("user_id", "badge_id") | ||
indices = append(indices, ubUnique) | ||
return indices | ||
} | ||
|
||
// ErrBadgeAlreadyExist represents a "badge already exists" error. | ||
type ErrBadgeAlreadyExist struct { | ||
Slug string | ||
} | ||
|
||
// IsErrBadgeAlreadyExist checks if an error is a ErrBadgeAlreadyExist. | ||
func IsErrBadgeAlreadyExist(err error) bool { | ||
_, ok := err.(ErrBadgeAlreadyExist) | ||
return ok | ||
} | ||
|
||
func (err ErrBadgeAlreadyExist) Error() string { | ||
return fmt.Sprintf("badge already exists [slug: %s]", err.Slug) | ||
} | ||
|
||
// Unwrap unwraps this error as a ErrExist error | ||
func (err ErrBadgeAlreadyExist) Unwrap() error { | ||
return util.ErrAlreadyExist | ||
} | ||
|
||
// ErrBadgeNotExist represents a "BadgeNotExist" kind of error. | ||
type ErrBadgeNotExist struct { | ||
Slug string | ||
ID int64 | ||
} | ||
|
||
func (err ErrBadgeNotExist) Error() string { | ||
if err.ID > 0 { | ||
return fmt.Sprintf("badge does not exist [id: %d]", err.ID) | ||
} | ||
return fmt.Sprintf("badge does not exist [slug: %s]", err.Slug) | ||
} | ||
|
||
// IsErrBadgeNotExist checks if an error is a ErrBadgeNotExist. | ||
func IsErrBadgeNotExist(err error) bool { | ||
_, ok := err.(ErrBadgeNotExist) | ||
return ok | ||
} | ||
|
||
// Unwrap unwraps this error as a ErrNotExist error | ||
func (err ErrBadgeNotExist) Unwrap() error { | ||
return util.ErrNotExist | ||
} | ||
|
||
func init() { | ||
db.RegisterModel(new(Badge)) | ||
db.RegisterModel(new(UserBadge)) | ||
|
@@ -42,13 +100,37 @@ func GetUserBadges(ctx context.Context, u *User) ([]*Badge, int64, error) { | |
return badges, count, err | ||
} | ||
|
||
// GetBadgeUsersOptions contains options for getting users with a specific badge | ||
type GetBadgeUsersOptions struct { | ||
db.ListOptions | ||
BadgeSlug string | ||
} | ||
|
||
// GetBadgeUsers returns the users that have a specific badge with pagination support. | ||
func GetBadgeUsers(ctx context.Context, opts *GetBadgeUsersOptions) ([]*User, int64, error) { | ||
techknowlogick marked this conversation as resolved.
Show resolved
Hide resolved
|
||
sess := db.GetEngine(ctx). | ||
Select("`user`.*"). | ||
Join("INNER", "user_badge", "`user_badge`.user_id=user.id"). | ||
Join("INNER", "badge", "`user_badge`.badge_id=badge.id"). | ||
Where("badge.slug=?", opts.BadgeSlug) | ||
|
||
if opts.Page > 0 { | ||
sess = db.SetSessionPagination(sess, opts) | ||
} | ||
|
||
users := make([]*User, 0, opts.PageSize) | ||
count, err := sess.FindAndCount(&users) | ||
return users, count, err | ||
} | ||
|
||
// CreateBadge creates a new badge. | ||
func CreateBadge(ctx context.Context, badge *Badge) error { | ||
// this will fail if the badge already exists due to the UNIQUE constraint | ||
_, err := db.GetEngine(ctx).Insert(badge) | ||
return err | ||
} | ||
|
||
// GetBadge returns a badge | ||
// GetBadge returns a specific badge | ||
func GetBadge(ctx context.Context, slug string) (*Badge, error) { | ||
badge := new(Badge) | ||
has, err := db.GetEngine(ctx).Where("slug=?", slug).Get(badge) | ||
|
@@ -60,14 +142,26 @@ func GetBadge(ctx context.Context, slug string) (*Badge, error) { | |
|
||
// UpdateBadge updates a badge based on its slug. | ||
func UpdateBadge(ctx context.Context, badge *Badge) error { | ||
_, err := db.GetEngine(ctx).Where("slug=?", badge.Slug).Update(badge) | ||
_, err := db.GetEngine(ctx).Where("slug=?", badge.Slug).Cols("description", "image_url").Update(badge) | ||
return err | ||
} | ||
|
||
// DeleteBadge deletes a badge. | ||
// DeleteBadge deletes a badge and all associated user_badge entries. | ||
func DeleteBadge(ctx context.Context, badge *Badge) error { | ||
_, err := db.GetEngine(ctx).Where("slug=?", badge.Slug).Delete(badge) | ||
return err | ||
return db.WithTx(ctx, func(ctx context.Context) error { | ||
// First delete all user_badge entries for this badge | ||
if _, err := db.GetEngine(ctx). | ||
Where("badge_id = (SELECT id FROM badge WHERE slug = ?)", badge.Slug). | ||
techknowlogick marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Delete(&UserBadge{}); err != nil { | ||
return err | ||
} | ||
|
||
// Then delete the badge itself | ||
if _, err := db.GetEngine(ctx).Where("slug=?", badge.Slug).Delete(badge); err != nil { | ||
return err | ||
} | ||
return nil | ||
}) | ||
} | ||
|
||
// AddUserBadge adds a badge to a user. | ||
|
@@ -84,7 +178,7 @@ func AddUserBadges(ctx context.Context, u *User, badges []*Badge) error { | |
if err != nil { | ||
return err | ||
} else if !has { | ||
return fmt.Errorf("badge with slug %s doesn't exist", badge.Slug) | ||
return ErrBadgeNotExist{Slug: badge.Slug} | ||
} | ||
if err := db.Insert(ctx, &UserBadge{ | ||
BadgeID: badge.ID, | ||
|
@@ -102,16 +196,26 @@ func RemoveUserBadge(ctx context.Context, u *User, badge *Badge) error { | |
return RemoveUserBadges(ctx, u, []*Badge{badge}) | ||
} | ||
|
||
// RemoveUserBadges removes badges from a user. | ||
// RemoveUserBadges removes specific badges from a user. | ||
func RemoveUserBadges(ctx context.Context, u *User, badges []*Badge) error { | ||
return db.WithTx(ctx, func(ctx context.Context) error { | ||
badgeSlugs := make([]string, 0, len(badges)) | ||
for _, badge := range badges { | ||
if _, err := db.GetEngine(ctx). | ||
Join("INNER", "badge", "badge.id = `user_badge`.badge_id"). | ||
Where("`user_badge`.user_id=? AND `badge`.slug=?", u.ID, badge.Slug). | ||
Delete(&UserBadge{}); err != nil { | ||
return err | ||
} | ||
badgeSlugs = append(badgeSlugs, badge.Slug) | ||
} | ||
var userBadges []UserBadge | ||
if err := db.GetEngine(ctx).Table("user_badge"). | ||
Join("INNER", "badge", "badge.id = `user_badge`.badge_id"). | ||
Where("`user_badge`.user_id = ?", u.ID).In("`badge`.slug", badgeSlugs). | ||
Find(&userBadges); err != nil { | ||
return err | ||
} | ||
userBadgeIDs := make([]int64, 0, len(userBadges)) | ||
for _, ub := range userBadges { | ||
userBadgeIDs = append(userBadgeIDs, ub.ID) | ||
} | ||
if _, err := db.GetEngine(ctx).Table("user_badge").In("id", userBadgeIDs).Delete(); err != nil { | ||
return err | ||
} | ||
return nil | ||
}) | ||
|
@@ -122,3 +226,56 @@ func RemoveAllUserBadges(ctx context.Context, u *User) error { | |
_, err := db.GetEngine(ctx).Where("user_id=?", u.ID).Delete(&UserBadge{}) | ||
return err | ||
} | ||
|
||
// SearchBadgeOptions represents the options when fdin badges | ||
type SearchBadgeOptions struct { | ||
db.ListOptions | ||
|
||
Keyword string | ||
Slug string | ||
ID int64 | ||
OrderBy db.SearchOrderBy | ||
Actor *User // The user doing the search | ||
} | ||
|
||
func (opts *SearchBadgeOptions) ToConds() builder.Cond { | ||
cond := builder.NewCond() | ||
|
||
if opts.Keyword != "" { | ||
lowerKeyword := strings.ToLower(opts.Keyword) | ||
keywordCond := builder.Or( | ||
builder.Like{"badge.slug", lowerKeyword}, | ||
builder.Like{"badge.description", lowerKeyword}, | ||
builder.Like{"badge.id", lowerKeyword}, | ||
) | ||
cond = cond.And(keywordCond) | ||
} | ||
|
||
if opts.ID > 0 { | ||
cond = cond.And(builder.Eq{"badge.id": opts.ID}) | ||
} | ||
|
||
if len(opts.Slug) > 0 { | ||
cond = cond.And(builder.Eq{"badge.slug": opts.Slug}) | ||
} | ||
|
||
return cond | ||
} | ||
|
||
// SearchBadges returns badges based on the provided SearchBadgeOptions options | ||
func SearchBadges(ctx context.Context, opts *SearchBadgeOptions) ([]*Badge, int64, error) { | ||
return db.FindAndCount[Badge](ctx, opts) | ||
} | ||
|
||
// GetBadgeByID returns a specific badge by ID | ||
func GetBadgeByID(ctx context.Context, id int64) (*Badge, error) { | ||
badge := new(Badge) | ||
has, err := db.GetEngine(ctx).ID(id).Get(badge) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if !has { | ||
return nil, ErrBadgeNotExist{ID: id} | ||
} | ||
return badge, nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's better to add a test for the function.