1
0
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:
2026-03-04 18:05:17 +09:00
parent 03e8ed4822
commit c1479a32a7
3 changed files with 94 additions and 29 deletions

View File

@@ -143,6 +143,9 @@ const MemberListDialog: React.FC<{
<Users size={24} className="text-primary" />
{node.name}{" "}
{t("ui.admin.tenants.members.list_title", "구성원 관리")}
<span className="text-sm font-normal text-muted-foreground ml-1">
({isDirectLoading ? "..." : directData?.total ?? 0})
</span>
</DialogTitle>
<DialogDescription>
{t(
@@ -164,7 +167,7 @@ const MemberListDialog: React.FC<{
className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-0 py-2"
>
{t("ui.admin.tenants.members.direct", "소속 멤버")} (
{node.memberCount || 0})
{isDirectLoading ? "..." : directData?.total ?? 0})
</TabsTrigger>
<TabsTrigger
value="descendants"

View File

@@ -374,7 +374,19 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
// [Keto] Sync relations via Outbox
if h.KetoOutboxRepo != nil {
// 1. Role based relations
h.syncKetoRole(ctx, u.ID, role, "", "", tID)
// 2. Direct membership to the Tenant (for accurate counting)
if tID != nil && *tID != "" {
_ = h.KetoOutboxRepo.Create(ctx, &domain.KetoOutbox{
Namespace: "Tenant",
Object: *tID,
Relation: "members",
Subject: "User:" + u.ID,
Action: domain.KetoOutboxActionCreate,
})
}
}
}(localUser, role, localUser.TenantID)
}
@@ -528,7 +540,15 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
identity, _ := h.KratosAdmin.GetIdentity(c.Context(), identityID)
if identity != nil {
localUser := h.mapToLocalUser(*identity)
// [Fix] Override with current loop data to ensure accuracy
localUser.CompanyCode = compCode
if tItem.ID != "" {
localUser.TenantID = &tItem.ID
}
_ = h.UserRepo.Update(context.Background(), localUser)
if h.KetoOutboxRepo != nil {
// 1. Sync Role based relationship
h.syncKetoRole(context.Background(), localUser.ID, role, "", "", localUser.TenantID)
@@ -792,11 +812,28 @@ func (h *UserHandler) BulkUpdateUsers(c *fiber.Ctx) error {
// Sync to local DB
if h.UserRepo != nil {
localUser := h.mapToLocalUser(*identity)
oldRole := extractTraitString(identity.Traits, "grade")
oldTenantID := extractTraitString(identity.Traits, "tenant_id")
if req.Role != nil { localUser.Role = *req.Role }
if req.Status != nil { localUser.Status = *req.Status }
if req.CompanyCode != nil { localUser.CompanyCode = *req.CompanyCode }
if req.Department != nil { localUser.Department = *req.Department }
// Resolve TenantID if changing companyCode
if req.CompanyCode != nil && h.TenantService != nil {
if tenant, err := h.TenantService.GetTenantBySlug(c.Context(), *req.CompanyCode); err == nil && tenant != nil {
localUser.TenantID = &tenant.ID
}
}
_ = h.UserRepo.Update(c.Context(), localUser)
// [Keto Sync]
if h.KetoOutboxRepo != nil {
h.syncKetoRole(c.Context(), localUser.ID,
localUser.Role, oldRole, oldTenantID, localUser.TenantID)
}
}
results = append(results, map[string]any{"id": id, "success": true})
@@ -1170,6 +1207,11 @@ func (h *UserHandler) mapToLocalUser(identity service.KratosIdentity) *domain.Us
}
func (h *UserHandler) syncKetoRole(ctx context.Context, userID, newRole, oldRole, oldTenantID string, newTenantID *string) {
if h.KetoOutboxRepo == nil {
return
}
// 1. Handle Role Changes
// Remove old roles
if oldRole == domain.RoleSuperAdmin {
_ = h.KetoOutboxRepo.Create(ctx, &domain.KetoOutbox{
@@ -1207,6 +1249,35 @@ func (h *UserHandler) syncKetoRole(ctx context.Context, userID, newRole, oldRole
Action: domain.KetoOutboxActionCreate,
})
}
// 2. Handle Tenant Membership (for count)
newTID := ""
if newTenantID != nil {
newTID = *newTenantID
}
if oldTenantID != newTID {
// Remove from old tenant
if oldTenantID != "" {
_ = h.KetoOutboxRepo.Create(ctx, &domain.KetoOutbox{
Namespace: "Tenant",
Object: oldTenantID,
Relation: "members",
Subject: "User:" + userID,
Action: domain.KetoOutboxActionDelete,
})
}
// Add to new tenant
if newTID != "" {
_ = h.KetoOutboxRepo.Create(ctx, &domain.KetoOutbox{
Namespace: "Tenant",
Object: newTID,
Relation: "members",
Subject: "User:" + userID,
Action: domain.KetoOutboxActionCreate,
})
}
}
}
func extractTraitString(traits map[string]interface{}, key string) string {

View File

@@ -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