forked from baron/baron-sso
fix: ensure member counts are accurate by syncing membership relations in all user management actions
This commit is contained in:
@@ -116,32 +116,17 @@ func (r *userRepository) CountByCompanyCodes(ctx context.Context, codes []string
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
|
||||
// 1. Resolve IDs for these codes to support dual counting (slug or ID)
|
||||
var tenants []domain.Tenant
|
||||
_ = r.db.WithContext(ctx).Where("slug IN ?", codes).Find(&tenants).Error
|
||||
|
||||
idToSlug := make(map[string]string)
|
||||
slugToNormalized := make(map[string]string)
|
||||
|
||||
for _, code := range codes {
|
||||
slugToNormalized[strings.ToLower(strings.TrimSpace(code))] = code
|
||||
}
|
||||
for _, t := range tenants {
|
||||
idToSlug[t.ID] = t.Slug
|
||||
}
|
||||
|
||||
type result struct {
|
||||
CompanyCode string
|
||||
TenantID string
|
||||
Count int64
|
||||
}
|
||||
var results []result
|
||||
|
||||
// Use a more comprehensive aggregation
|
||||
// Search by company_code directly. Normalize inputs.
|
||||
err := r.db.WithContext(ctx).Model(&domain.User{}).
|
||||
Select("company_code, tenant_id, count(*) as count").
|
||||
Where("company_code IN ? OR tenant_id IN (SELECT id FROM tenants WHERE slug IN ?)", codes, codes).
|
||||
Group("company_code, tenant_id").
|
||||
Select("LOWER(company_code) as company_code, count(*) as count").
|
||||
Where("LOWER(company_code) IN ?", lowerStrings(codes)).
|
||||
Group("LOWER(company_code)").
|
||||
Scan(&results).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -149,22 +134,28 @@ func (r *userRepository) CountByCompanyCodes(ctx context.Context, codes []string
|
||||
|
||||
counts := make(map[string]int64)
|
||||
for _, res := range results {
|
||||
var slug string
|
||||
if res.CompanyCode != "" {
|
||||
slug = res.CompanyCode
|
||||
} else if res.TenantID != "" {
|
||||
slug = idToSlug[res.TenantID]
|
||||
}
|
||||
counts[res.CompanyCode] = res.Count
|
||||
}
|
||||
|
||||
if slug != "" {
|
||||
normalizedSlug := strings.ToLower(strings.TrimSpace(slug))
|
||||
counts[normalizedSlug] += res.Count
|
||||
// Ensure all requested codes are present in results
|
||||
for _, code := range codes {
|
||||
lower := strings.ToLower(strings.TrimSpace(code))
|
||||
if _, ok := counts[lower]; !ok {
|
||||
counts[lower] = 0
|
||||
}
|
||||
}
|
||||
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func lowerStrings(arr []string) []string {
|
||||
res := make([]string, len(arr))
|
||||
for i, s := range arr {
|
||||
res[i] = strings.ToLower(strings.TrimSpace(s))
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (r *userRepository) List(ctx context.Context, offset, limit int, search string, companyCode string) ([]domain.User, int64, error) {
|
||||
var users []domain.User
|
||||
var total int64
|
||||
|
||||
Reference in New Issue
Block a user