feat(api): enhance organization shared knowledge base and agent functionalities
- Introduced new interfaces for handling shared knowledge bases and agents, including visibility and selection modes for agents. - Added API functions to list shared knowledge bases and agents within an organization, improving data retrieval for UI components. - Updated existing components to utilize the new API endpoints and interfaces, ensuring accurate representation of shared resources. - Enhanced error handling in API calls to provide clearer feedback on failures. This update improves the functionality and user experience by providing better access to shared resources and enhancing the overall data structure within the application.
This commit is contained in:
@@ -108,6 +108,7 @@ func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID str
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Preload("Agent").
|
||||
Preload("Organization").
|
||||
Where("agent_shares.organization_id = ? AND agent_shares.deleted_at IS NULL", orgID).
|
||||
Order("agent_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
@@ -117,6 +118,35 @@ func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID str
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted agents.
|
||||
func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
type row struct {
|
||||
OrgID string `gorm:"column:organization_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
var rows []row
|
||||
err := r.db.WithContext(ctx).Model(&types.AgentShare{}).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Select("agent_shares.organization_id as organization_id, COUNT(*) as count").
|
||||
Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
|
||||
Group("agent_shares.organization_id").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]int64)
|
||||
for _, o := range orgIDs {
|
||||
out[o] = 0
|
||||
}
|
||||
for _, r := range rows {
|
||||
out[r.OrgID] = r.Count
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListSharedAgentsForUser lists all agents shared to organizations that the user belongs to
|
||||
func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) {
|
||||
var shares []*types.AgentShare
|
||||
|
||||
@@ -115,6 +115,7 @@ func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Where("kb_shares.organization_id = ? AND kb_shares.deleted_at IS NULL", orgID).
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
@@ -188,3 +189,32 @@ func (r *kbShareRepository) CountSharesByKnowledgeBaseIDs(ctx context.Context, k
|
||||
}
|
||||
return countMap, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted KBs.
|
||||
func (r *kbShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
type row struct {
|
||||
OrgID string `gorm:"column:organization_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
var rows []row
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Select("kb_shares.organization_id as organization_id, COUNT(*) as count").
|
||||
Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
|
||||
Group("kb_shares.organization_id").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]int64)
|
||||
for _, o := range orgIDs {
|
||||
out[o] = 0
|
||||
}
|
||||
for _, r := range rows {
|
||||
out[r.OrgID] = r.Count
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -224,6 +224,81 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string,
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListSharedAgentsInOrganization returns all agents shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected.
|
||||
func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
shares, err := s.shareRepo.ListByOrganization(ctx, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]*types.OrganizationSharedAgentItem, 0, len(shares))
|
||||
for _, share := range shares {
|
||||
if share.Agent == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
|
||||
orgName := ""
|
||||
if share.Organization != nil {
|
||||
orgName = share.Organization.Name
|
||||
}
|
||||
info := &types.SharedAgentInfo{
|
||||
Agent: share.Agent,
|
||||
ShareID: share.ID,
|
||||
OrganizationID: share.OrganizationID,
|
||||
OrgName: orgName,
|
||||
Permission: effectivePermission,
|
||||
SourceTenantID: share.SourceTenantID,
|
||||
SharedAt: share.CreatedAt,
|
||||
SharedByUserID: share.SharedByUserID,
|
||||
}
|
||||
if share.SharedByUserID != "" {
|
||||
if u, err := s.userRepo.GetUserByID(ctx, share.SharedByUserID); err == nil && u != nil {
|
||||
info.SharedByUsername = u.Username
|
||||
}
|
||||
}
|
||||
|
||||
item := &types.OrganizationSharedAgentItem{
|
||||
SharedAgentInfo: *info,
|
||||
IsMine: share.SourceTenantID == currentTenantID,
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
|
||||
// Set DisabledByMe for entries shared by others (mine entries stay false)
|
||||
disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID)
|
||||
if err == nil {
|
||||
disabledSet := make(map[string]bool)
|
||||
for _, d := range disabledList {
|
||||
disabledSet[fmt.Sprintf("%s_%d", d.AgentID, d.SourceTenantID)] = true
|
||||
}
|
||||
for _, item := range result {
|
||||
if item.Agent != nil && !item.IsMine {
|
||||
key := fmt.Sprintf("%s_%d", item.Agent.ID, item.SourceTenantID)
|
||||
item.DisabledByMe = disabledSet[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (for list sidebar); excludes deleted agents
|
||||
func (s *agentShareService) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
return s.shareRepo.CountByOrganizations(ctx, orgIDs)
|
||||
}
|
||||
|
||||
// SetSharedAgentDisabledByMe adds or removes (tenantID, agentID, sourceTenantID) from tenant_disabled_shared_agents.
|
||||
func (s *agentShareService) SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error {
|
||||
if disabled {
|
||||
@@ -254,6 +329,41 @@ func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID st
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
// UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (used when opening KB detail from space list without agent_id).
|
||||
func (s *agentShareService) UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error) {
|
||||
if kb == nil || kb.ID == "" {
|
||||
return false, nil
|
||||
}
|
||||
list, err := s.ListSharedAgents(ctx, userID, currentTenantID)
|
||||
if err != nil || len(list) == 0 {
|
||||
return false, err
|
||||
}
|
||||
for _, info := range list {
|
||||
if info.Agent == nil {
|
||||
continue
|
||||
}
|
||||
agent := info.Agent
|
||||
if agent.TenantID != kb.TenantID {
|
||||
continue
|
||||
}
|
||||
mode := agent.Config.KBSelectionMode
|
||||
if mode == "none" {
|
||||
continue
|
||||
}
|
||||
if mode == "all" {
|
||||
return true, nil
|
||||
}
|
||||
if mode == "selected" {
|
||||
for _, id := range agent.Config.KnowledgeBases {
|
||||
if id == kb.ID {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// GetShare gets an agent share by ID
|
||||
func (s *agentShareService) GetShare(ctx context.Context, shareID string) (*types.AgentShare, error) {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
|
||||
@@ -289,6 +289,65 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListSharedKnowledgeBasesInOrganization returns all knowledge bases shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected.
|
||||
func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
shares, err := s.shareRepo.ListByOrganization(ctx, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]*types.OrganizationSharedKnowledgeBaseItem, 0, len(shares))
|
||||
for _, share := range shares {
|
||||
if share.KnowledgeBase == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
|
||||
kb := share.KnowledgeBase
|
||||
switch kb.Type {
|
||||
case types.KnowledgeBaseTypeDocument:
|
||||
if count, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID); err == nil {
|
||||
kb.KnowledgeCount = count
|
||||
}
|
||||
case types.KnowledgeBaseTypeFAQ:
|
||||
if count, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID); err == nil {
|
||||
kb.ChunkCount = count
|
||||
}
|
||||
}
|
||||
|
||||
orgName := ""
|
||||
if share.Organization != nil {
|
||||
orgName = share.Organization.Name
|
||||
}
|
||||
item := &types.OrganizationSharedKnowledgeBaseItem{
|
||||
SharedKnowledgeBaseInfo: types.SharedKnowledgeBaseInfo{
|
||||
KnowledgeBase: kb,
|
||||
ShareID: share.ID,
|
||||
OrganizationID: share.OrganizationID,
|
||||
OrgName: orgName,
|
||||
Permission: effectivePermission,
|
||||
SourceTenantID: share.SourceTenantID,
|
||||
SharedAt: share.CreatedAt,
|
||||
},
|
||||
IsMine: share.SourceTenantID == currentTenantID,
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetShare gets a share by ID
|
||||
func (s *kbShareService) GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error) {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
@@ -388,3 +447,8 @@ func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (ui
|
||||
func (s *kbShareService) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
|
||||
return s.shareRepo.CountSharesByKnowledgeBaseIDs(ctx, kbIDs)
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (for list sidebar); excludes deleted KBs
|
||||
func (s *kbShareService) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
return s.shareRepo.CountByOrganizations(ctx, orgIDs)
|
||||
}
|
||||
|
||||
+22
-12
@@ -15,14 +15,15 @@ import (
|
||||
|
||||
// ChunkHandler defines HTTP handlers for chunk operations
|
||||
type ChunkHandler struct {
|
||||
service interfaces.ChunkService
|
||||
kgService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
service interfaces.ChunkService
|
||||
kgService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
agentShareService interfaces.AgentShareService
|
||||
}
|
||||
|
||||
// NewChunkHandler creates a new chunk handler
|
||||
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService) *ChunkHandler {
|
||||
return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService}
|
||||
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService, agentShareService interfaces.AgentShareService) *ChunkHandler {
|
||||
return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService, agentShareService: agentShareService}
|
||||
}
|
||||
|
||||
// effectiveCtxForKnowledge resolves knowledge by ID, validates KB access (owner or shared with required role), and returns context with effectiveTenantID for downstream service calls.
|
||||
@@ -41,17 +42,26 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri
|
||||
if knowledge.TenantID == tenantID {
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
if !userExists || h.kbShareService == nil {
|
||||
if !userExists {
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
|
||||
if permErr != nil || !isShared {
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
if h.kbShareService != nil {
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
if !permission.HasPermission(requiredPermission) {
|
||||
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||
}
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||
}
|
||||
}
|
||||
if !permission.HasPermission(requiredPermission) {
|
||||
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||
if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil {
|
||||
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef)
|
||||
if err == nil && can {
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||
}
|
||||
}
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly godoc
|
||||
|
||||
+143
-21
@@ -1,6 +1,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@@ -15,12 +16,67 @@ import (
|
||||
|
||||
// FAQHandler handles FAQ knowledge base operations.
|
||||
type FAQHandler struct {
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
agentShareService interfaces.AgentShareService
|
||||
}
|
||||
|
||||
// NewFAQHandler creates a new FAQ handler
|
||||
func NewFAQHandler(knowledgeService interfaces.KnowledgeService) *FAQHandler {
|
||||
return &FAQHandler{knowledgeService: knowledgeService}
|
||||
func NewFAQHandler(
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
agentShareService interfaces.AgentShareService,
|
||||
) *FAQHandler {
|
||||
return &FAQHandler{
|
||||
knowledgeService: knowledgeService,
|
||||
kbService: kbService,
|
||||
kbShareService: kbShareService,
|
||||
agentShareService: agentShareService,
|
||||
}
|
||||
}
|
||||
|
||||
// effectiveCtxForKB validates KB access (owner, shared, or via shared agent when requiredPermission is Viewer) and returns context with effectiveTenantID.
|
||||
func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPermission types.OrgMemberRole) (context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
return nil, errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
kbID = secutils.SanitizeForLog(kbID)
|
||||
if kbID == "" {
|
||||
return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
if kb.TenantID == tenantID {
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
if userExists && h.kbShareService != nil {
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
||||
if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
|
||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||
if srcErr == nil {
|
||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
||||
userID.(string), kbID, permission, sourceTenantID)
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if requiredPermission == types.OrgRoleViewer && userExists && h.agentShareService != nil {
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
||||
if err == nil && can {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
// ListEntries godoc
|
||||
@@ -43,6 +99,12 @@ func NewFAQHandler(knowledgeService interfaces.KnowledgeService) *FAQHandler {
|
||||
// @Router /knowledge-bases/{id}/faq/entries [get]
|
||||
func (h *FAQHandler) ListEntries(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var page types.Pagination
|
||||
if err := c.ShouldBindQuery(&page); err != nil {
|
||||
logger.Error(ctx, "Failed to bind pagination query", err)
|
||||
@@ -64,7 +126,7 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
|
||||
searchField := secutils.SanitizeForLog(c.Query("search_field"))
|
||||
sortOrder := secutils.SanitizeForLog(c.Query("sort_order"))
|
||||
|
||||
result, err := h.knowledgeService.ListFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &page, tagSeqID, keyword, searchField, sortOrder)
|
||||
result, err := h.knowledgeService.ListFAQEntries(effCtx, kbID, &page, tagSeqID, keyword, searchField, sortOrder)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -94,6 +156,12 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/faq/entries [post]
|
||||
func (h *FAQHandler) UpsertEntries(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req types.FAQBatchUpsertPayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind FAQ upsert payload", err)
|
||||
@@ -101,10 +169,8 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
// 统一使用 UpsertFAQEntries,通过 DryRun 字段区分模式
|
||||
taskID, err := h.knowledgeService.UpsertFAQEntries(ctx, kbID, &req)
|
||||
taskID, err := h.knowledgeService.UpsertFAQEntries(effCtx, kbID, &req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -134,6 +200,12 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/faq/entry [post]
|
||||
func (h *FAQHandler) CreateEntry(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req types.FAQEntryPayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
|
||||
@@ -141,7 +213,7 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.CreateFAQEntry(ctx, secutils.SanitizeForLog(c.Param("id")), &req)
|
||||
entry, err := h.knowledgeService.CreateFAQEntry(effCtx, kbID, &req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -170,6 +242,12 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/faq/entries/{entry_id} [put]
|
||||
func (h *FAQHandler) UpdateEntry(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req types.FAQEntryPayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
|
||||
@@ -183,8 +261,8 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.UpdateFAQEntry(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")), entrySeqID, &req)
|
||||
entry, err := h.knowledgeService.UpdateFAQEntry(effCtx,
|
||||
kbID, entrySeqID, &req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -212,14 +290,20 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/faq/entries/tags [put]
|
||||
func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req faqEntryTagBatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind FAQ entry tag batch payload", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := h.knowledgeService.UpdateFAQEntryTagBatch(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")), req.Updates); err != nil {
|
||||
if err := h.knowledgeService.UpdateFAQEntryTagBatch(effCtx,
|
||||
kbID, req.Updates); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -244,14 +328,20 @@ func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/faq/entries/fields [put]
|
||||
func (h *FAQHandler) UpdateEntryFieldsBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req types.FAQEntryFieldsBatchUpdate
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind FAQ entry fields batch payload", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")), &req); err != nil {
|
||||
if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(effCtx,
|
||||
kbID, &req); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -292,6 +382,12 @@ type addSimilarQuestionsRequest struct {
|
||||
// @Router /knowledge-bases/{id}/faq/entries [delete]
|
||||
func (h *FAQHandler) DeleteEntries(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req faqDeleteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Errorf(ctx, "Failed to bind FAQ delete payload: %s", secutils.SanitizeForLog(err.Error()))
|
||||
@@ -299,8 +395,8 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.knowledgeService.DeleteFAQEntries(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")),
|
||||
if err := h.knowledgeService.DeleteFAQEntries(effCtx,
|
||||
kbID,
|
||||
req.IDs); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -327,6 +423,12 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/faq/search [post]
|
||||
func (h *FAQHandler) SearchFAQ(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var req types.FAQSearchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind FAQ search payload", err)
|
||||
@@ -340,7 +442,7 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) {
|
||||
if req.MatchCount > 200 {
|
||||
req.MatchCount = 200
|
||||
}
|
||||
entries, err := h.knowledgeService.SearchFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &req)
|
||||
entries, err := h.knowledgeService.SearchFAQEntries(effCtx, kbID, &req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -368,8 +470,13 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) {
|
||||
func (h *FAQHandler) ExportEntries(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
csvData, err := h.knowledgeService.ExportFAQEntries(ctx, kbID)
|
||||
csvData, err := h.knowledgeService.ExportFAQEntries(effCtx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -401,13 +508,18 @@ func (h *FAQHandler) ExportEntries(c *gin.Context) {
|
||||
func (h *FAQHandler) GetEntry(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entrySeqID)
|
||||
entry, err := h.knowledgeService.GetFAQEntry(effCtx, kbID, entrySeqID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -471,6 +583,11 @@ type updateLastFAQImportResultDisplayStatusRequest struct {
|
||||
func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req updateLastFAQImportResultDisplayStatusRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -479,7 +596,7 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(ctx, kbID, req.DisplayStatus); err != nil {
|
||||
if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(effCtx, kbID, req.DisplayStatus); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -508,6 +625,11 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
|
||||
func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -522,7 +644,7 @@ func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.AddSimilarQuestions(ctx, kbID, entrySeqID, req.SimilarQuestions)
|
||||
entry, err := h.knowledgeService.AddSimilarQuestions(effCtx, kbID, entrySeqID, req.SimilarQuestions)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
|
||||
@@ -93,6 +93,15 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.K
|
||||
}
|
||||
}
|
||||
|
||||
// Check 3: If not owner and no direct share, allow if user has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list)
|
||||
if userExists && h.agentShareService != nil {
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
||||
if err == nil && can {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
||||
return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil
|
||||
}
|
||||
}
|
||||
|
||||
// No permission: not owner and no shared access
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
@@ -137,6 +146,13 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, k
|
||||
}
|
||||
}
|
||||
}
|
||||
if userExists && h.agentShareService != nil {
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
||||
if err == nil && can {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
||||
return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "Permission denied to access KB %s, tenant ID: %d, KB tenant: %d", kbID, tenantID, kb.TenantID)
|
||||
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
@@ -169,7 +185,7 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
|
||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
|
||||
}
|
||||
}
|
||||
// Shared agent: request passes agent_id, verify user has that shared agent and the agent has access to this knowledge/KB
|
||||
// Shared agent: request passes agent_id, or user has any shared agent that can access this KB
|
||||
if userExists && h.agentShareService != nil && requiredPermission == types.OrgRoleViewer {
|
||||
agentID := c.Query("agent_id")
|
||||
if agentID != "" {
|
||||
@@ -194,6 +210,12 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
|
||||
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef)
|
||||
if err == nil && can {
|
||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
|
||||
@@ -197,34 +197,39 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
||||
}
|
||||
}
|
||||
|
||||
// Check 3: Shared agent — request has agent_id, verify user has that shared agent and the agent has access to this KB
|
||||
// Check 3: Shared agent — allow if request has agent_id (and agent can access this KB) OR user has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list without agent_id)
|
||||
if userExists && h.agentShareService != nil {
|
||||
currentTenantID := tenantID.(uint64)
|
||||
agentID := c.Query("agent_id")
|
||||
if agentID != "" {
|
||||
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if currentTenantID != 0 {
|
||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID)
|
||||
if err == nil && agent != nil {
|
||||
if kb.TenantID != agent.TenantID {
|
||||
logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
|
||||
} else {
|
||||
mode := agent.Config.KBSelectionMode
|
||||
if mode == "none" {
|
||||
// no-op, fall through to forbid
|
||||
} else if mode == "all" {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID)
|
||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||
} else if mode == "selected" {
|
||||
for _, allowedID := range agent.Config.KnowledgeBases {
|
||||
if allowedID == id {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID)
|
||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||
}
|
||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID)
|
||||
if err == nil && agent != nil {
|
||||
if kb.TenantID != agent.TenantID {
|
||||
logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
|
||||
} else {
|
||||
mode := agent.Config.KBSelectionMode
|
||||
if mode == "none" {
|
||||
// no-op, fall through
|
||||
} else if mode == "all" {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID)
|
||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||
} else if mode == "selected" {
|
||||
for _, allowedID := range agent.Config.KnowledgeBases {
|
||||
if allowedID == id {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID)
|
||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No agent_id in query: allow if user has any shared agent that can access this KB (e.g. from space list "通过智能体可见")
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), currentTenantID, kb)
|
||||
if err == nil && can {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent (no agent_id in query)", userID.(string), id)
|
||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,7 +259,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
||||
// @Router /knowledge-bases/{id} [get]
|
||||
func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
|
||||
// Validate and get the knowledge base
|
||||
kb, _, _, _, err := h.validateAndGetKnowledgeBase(c)
|
||||
kb, _, _, permission, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -263,10 +268,19 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
|
||||
if fillErr := h.service.FillKnowledgeBaseCounts(c.Request.Context(), kb); fillErr != nil {
|
||||
logger.Warnf(c.Request.Context(), "Failed to fill KB counts for %s: %v", kb.ID, fillErr)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": kb,
|
||||
})
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
data := interface{}(kb)
|
||||
if kb.TenantID != tenantID && permission != "" {
|
||||
// Include my_permission in data so frontend can show role (e.g. "只读") instead of "--" for agent-visible KBs
|
||||
var dataMap map[string]interface{}
|
||||
b, _ := json.Marshal(kb)
|
||||
_ = json.Unmarshal(b, &dataMap)
|
||||
if dataMap != nil {
|
||||
dataMap["my_permission"] = permission
|
||||
data = dataMap
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": data})
|
||||
}
|
||||
|
||||
// ListKnowledgeBases godoc
|
||||
|
||||
@@ -23,6 +23,7 @@ type OrganizationHandler struct {
|
||||
agentShareService interfaces.AgentShareService
|
||||
customAgentService interfaces.CustomAgentService
|
||||
userService interfaces.UserService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
}
|
||||
@@ -34,6 +35,7 @@ func NewOrganizationHandler(
|
||||
agentShareService interfaces.AgentShareService,
|
||||
customAgentService interfaces.CustomAgentService,
|
||||
userService interfaces.UserService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
) *OrganizationHandler {
|
||||
@@ -43,6 +45,7 @@ func NewOrganizationHandler(
|
||||
agentShareService: agentShareService,
|
||||
customAgentService: customAgentService,
|
||||
userService: userService,
|
||||
kbService: kbService,
|
||||
knowledgeRepo: knowledgeRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
}
|
||||
@@ -1254,6 +1257,73 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"shares": response, "total": len(response)}})
|
||||
}
|
||||
|
||||
// GetMeResourceCounts returns per-organization resource counts for the list sidebar (one request instead of N).
|
||||
// 全部 total is not returned here; frontend keeps 全部 = 我的 + 他人共享给我(与「全部」Tab 一致).
|
||||
// @Summary 获取各空间资源数量(侧栏用)
|
||||
// @Description 一次请求返回各空间内知识库/智能体数量(含我共享的),用于列表页侧栏展示
|
||||
// @Tags 组织管理
|
||||
// @Produce json
|
||||
// @Success 200 {object} types.ResourceCountsByOrgResponse
|
||||
// @Security Bearer
|
||||
// @Router /me/resource-counts [get]
|
||||
func (h *OrganizationHandler) GetMeResourceCounts(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID := c.GetString(types.UserIDContextKey.String())
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
|
||||
orgs, err := h.orgService.ListUserOrganizations(ctx, userID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to list user organizations: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to list organizations"))
|
||||
return
|
||||
}
|
||||
orgIDs := make([]string, 0, len(orgs))
|
||||
for _, o := range orgs {
|
||||
orgIDs = append(orgIDs, o.ID)
|
||||
}
|
||||
|
||||
agentCounts, err := h.agentShareService.CountByOrganizations(ctx, orgIDs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to count agent shares by org: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to get counts"))
|
||||
return
|
||||
}
|
||||
|
||||
byOrgKB := make(map[string]int)
|
||||
for _, o := range orgs {
|
||||
list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, o.ID, userID, tenantID)
|
||||
if err != nil {
|
||||
if !errors.Is(err, service.ErrUserNotInOrg) {
|
||||
logger.Warnf(ctx, "listSpaceKnowledgeBasesInOrganization org %s: %v", o.ID, err)
|
||||
}
|
||||
byOrgKB[o.ID] = 0
|
||||
continue
|
||||
}
|
||||
byOrgKB[o.ID] = len(list)
|
||||
}
|
||||
byOrgAgent := make(map[string]int)
|
||||
for id, n := range agentCounts {
|
||||
byOrgAgent[id] = int(n)
|
||||
}
|
||||
for _, o := range orgs {
|
||||
if _, ok := byOrgAgent[o.ID]; !ok {
|
||||
byOrgAgent[o.ID] = 0
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": types.ResourceCountsByOrgResponse{
|
||||
KnowledgeBases: struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
}{ByOrganization: byOrgKB},
|
||||
Agents: struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
}{ByOrganization: byOrgAgent},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ListSharedAgents lists agents shared to the current user
|
||||
func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
@@ -1268,6 +1338,182 @@ func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
|
||||
}
|
||||
|
||||
// listSpaceKnowledgeBasesInOrganization returns merged list of direct shared KBs and agent-carried KBs in the org (for list and count).
|
||||
func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, tenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
||||
directList, err := h.shareService.ListSharedKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
directKbIDs := make(map[string]bool)
|
||||
for _, item := range directList {
|
||||
if item.KnowledgeBase != nil && item.KnowledgeBase.ID != "" {
|
||||
directKbIDs[item.KnowledgeBase.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
agentList, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID)
|
||||
if err != nil {
|
||||
return directList, nil
|
||||
}
|
||||
|
||||
orgName := ""
|
||||
if len(agentList) > 0 && agentList[0].OrganizationID == orgID {
|
||||
orgName = agentList[0].OrgName
|
||||
}
|
||||
if orgName == "" {
|
||||
if org, err := h.orgService.GetOrganization(ctx, orgID); err == nil && org != nil {
|
||||
orgName = org.Name
|
||||
}
|
||||
}
|
||||
|
||||
merged := make([]*types.OrganizationSharedKnowledgeBaseItem, 0, len(directList)+64)
|
||||
merged = append(merged, directList...)
|
||||
|
||||
for _, agentItem := range agentList {
|
||||
if agentItem.Agent == nil {
|
||||
continue
|
||||
}
|
||||
agent := agentItem.Agent
|
||||
mode := agent.Config.KBSelectionMode
|
||||
if mode == "none" {
|
||||
continue
|
||||
}
|
||||
|
||||
var kbIDs []string
|
||||
switch mode {
|
||||
case "selected":
|
||||
if len(agent.Config.KnowledgeBases) == 0 {
|
||||
continue
|
||||
}
|
||||
kbIDs = agent.Config.KnowledgeBases
|
||||
case "all":
|
||||
kbs, err := h.kbService.ListKnowledgeBasesByTenantID(ctx, agent.TenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "ListKnowledgeBasesByTenantID for agent %s: %v", agent.ID, err)
|
||||
continue
|
||||
}
|
||||
kbIDs = make([]string, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
if kb != nil && kb.ID != "" {
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if len(agent.Config.KnowledgeBases) > 0 {
|
||||
kbIDs = agent.Config.KnowledgeBases
|
||||
}
|
||||
}
|
||||
|
||||
agentName := agent.Name
|
||||
if agentName == "" {
|
||||
agentName = agent.ID
|
||||
}
|
||||
sourceTenantID := agent.TenantID
|
||||
|
||||
for _, kbID := range kbIDs {
|
||||
if kbID == "" || directKbIDs[kbID] {
|
||||
continue
|
||||
}
|
||||
kb, err := h.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
|
||||
if err != nil || kb == nil {
|
||||
continue
|
||||
}
|
||||
if kb.TenantID != sourceTenantID {
|
||||
continue
|
||||
}
|
||||
directKbIDs[kbID] = true
|
||||
|
||||
switch kb.Type {
|
||||
case types.KnowledgeBaseTypeDocument:
|
||||
if count, err := h.knowledgeRepo.CountKnowledgeByKnowledgeBaseID(ctx, sourceTenantID, kb.ID); err == nil {
|
||||
kb.KnowledgeCount = count
|
||||
}
|
||||
case types.KnowledgeBaseTypeFAQ:
|
||||
if count, err := h.chunkRepo.CountChunksByKnowledgeBaseID(ctx, sourceTenantID, kb.ID); err == nil {
|
||||
kb.ChunkCount = count
|
||||
}
|
||||
}
|
||||
|
||||
merged = append(merged, &types.OrganizationSharedKnowledgeBaseItem{
|
||||
SharedKnowledgeBaseInfo: types.SharedKnowledgeBaseInfo{
|
||||
KnowledgeBase: kb,
|
||||
ShareID: "",
|
||||
OrganizationID: orgID,
|
||||
OrgName: orgName,
|
||||
Permission: types.OrgRoleViewer,
|
||||
SourceTenantID: sourceTenantID,
|
||||
SharedAt: agentItem.SharedAt,
|
||||
},
|
||||
IsMine: false,
|
||||
SourceFromAgent: &types.SourceFromAgentInfo{
|
||||
AgentID: agent.ID,
|
||||
AgentName: agentName,
|
||||
KBSelectionMode: agent.Config.KBSelectionMode,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return merged, nil
|
||||
}
|
||||
|
||||
// ListOrganizationSharedKnowledgeBases lists all knowledge bases in the given organization (including those shared by the current tenant and those from shared agents), for the list page when a space is selected.
|
||||
// @Summary 获取空间内全部知识库(含我共享的、含智能体携带的)
|
||||
// @Description 获取指定空间下所有共享知识库,包含直接共享的与通过共享智能体可见的,用于列表页空间视角
|
||||
// @Tags 组织管理
|
||||
// @Produce json
|
||||
// @Param id path string true "组织ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /organizations/{id}/shared-knowledge-bases [get]
|
||||
func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
orgID := c.Param("id")
|
||||
userID := c.GetString(types.UserIDContextKey.String())
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
|
||||
list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUserNotInOrg) {
|
||||
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
|
||||
return
|
||||
}
|
||||
logger.Errorf(ctx, "Failed to list organization shared knowledge bases: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to list shared knowledge bases"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
|
||||
}
|
||||
|
||||
// ListOrganizationSharedAgents lists all agents in the given organization (including those shared by the current tenant), for the list page when a space is selected.
|
||||
// @Summary 获取空间内全部智能体(含我共享的)
|
||||
// @Description 获取指定空间下所有共享智能体,包含他人共享的与我共享的,用于列表页空间视角
|
||||
// @Tags 组织管理
|
||||
// @Produce json
|
||||
// @Param id path string true "组织ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /organizations/{id}/shared-agents [get]
|
||||
func (h *OrganizationHandler) ListOrganizationSharedAgents(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
orgID := c.Param("id")
|
||||
userID := c.GetString(types.UserIDContextKey.String())
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
|
||||
list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUserNotInOrg) {
|
||||
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
|
||||
return
|
||||
}
|
||||
logger.Errorf(ctx, "Failed to list organization shared agents: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to list shared agents"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
|
||||
}
|
||||
|
||||
// SetSharedAgentDisabledByMeRequest is the body for POST /shared-agents/disabled
|
||||
type SetSharedAgentDisabledByMeRequest struct {
|
||||
AgentID string `json:"agent_id" binding:"required"`
|
||||
|
||||
+15
-6
@@ -16,11 +16,12 @@ import (
|
||||
|
||||
// TagHandler handles knowledge base tag operations.
|
||||
type TagHandler struct {
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
agentShareService interfaces.AgentShareService
|
||||
}
|
||||
|
||||
// DeleteTagRequest represents the request body for deleting a tag
|
||||
@@ -35,8 +36,9 @@ func NewTagHandler(
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
agentShareService interfaces.AgentShareService,
|
||||
) *TagHandler {
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService}
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService, agentShareService: agentShareService}
|
||||
}
|
||||
|
||||
// effectiveCtxForKB validates KB access (owner or shared) and returns context with effectiveTenantID for downstream service calls.
|
||||
@@ -70,6 +72,13 @@ func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Con
|
||||
}
|
||||
}
|
||||
}
|
||||
if userExists && h.agentShareService != nil {
|
||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
||||
if err == nil && can {
|
||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
@@ -502,6 +502,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
||||
orgs.GET("/:id/shares", orgHandler.ListOrgShares)
|
||||
// List agents shared to this organization
|
||||
orgs.GET("/:id/agent-shares", orgHandler.ListOrgAgentShares)
|
||||
// List all knowledge bases in this organization (including mine) for list-page space view
|
||||
orgs.GET("/:id/shared-knowledge-bases", orgHandler.ListOrganizationSharedKnowledgeBases)
|
||||
// List all agents in this organization (including mine) for list-page space view
|
||||
orgs.GET("/:id/shared-agents", orgHandler.ListOrganizationSharedAgents)
|
||||
}
|
||||
|
||||
// Knowledge base sharing routes (add to existing kb routes)
|
||||
@@ -530,4 +534,6 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
||||
// Shared agents route
|
||||
r.GET("/shared-agents", orgHandler.ListSharedAgents)
|
||||
r.POST("/shared-agents/disabled", orgHandler.SetSharedAgentDisabledByMe)
|
||||
// Per-org resource counts for list sidebar (one request)
|
||||
r.GET("/me/resource-counts", orgHandler.GetMeResourceCounts)
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ type KBShareService interface {
|
||||
ListSharesByKnowledgeBase(ctx context.Context, kbID string, tenantID uint64) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error)
|
||||
ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error)
|
||||
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
|
||||
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||
|
||||
@@ -102,6 +103,8 @@ type KBShareService interface {
|
||||
|
||||
// Count shares for knowledge bases
|
||||
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
||||
// CountByOrganizations returns share counts per organization (for sidebar); excludes deleted KBs
|
||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||
}
|
||||
|
||||
// KBShareRepository defines the knowledge base sharing repository interface
|
||||
@@ -120,6 +123,7 @@ type KBShareRepository interface {
|
||||
// List
|
||||
ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||
|
||||
// Query for user's accessible shared knowledge bases
|
||||
ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error)
|
||||
@@ -136,14 +140,19 @@ type AgentShareService interface {
|
||||
ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
||||
ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error)
|
||||
ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error)
|
||||
// SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-user preference).
|
||||
SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error
|
||||
// GetSharedAgentForUser returns the shared agent by agentID if the user has access (source tenant is resolved from share); used to resolve KB scope for @ mention.
|
||||
GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error)
|
||||
// UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (for opening KB detail from "通过智能体可见" list without passing agent_id).
|
||||
UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error)
|
||||
GetShare(ctx context.Context, shareID string) (*types.AgentShare, error)
|
||||
GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error)
|
||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access, excluding source_tenant_id == excludeTenantID (e.g. current tenant to get shared-from-other only).
|
||||
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
|
||||
// CountByOrganizations returns share counts per organization (for sidebar); excludes deleted agents
|
||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||
}
|
||||
|
||||
// AgentShareRepository defines the agent sharing repository interface
|
||||
@@ -158,6 +167,7 @@ type AgentShareRepository interface {
|
||||
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
||||
ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error)
|
||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID.
|
||||
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
|
||||
}
|
||||
|
||||
@@ -245,6 +245,27 @@ type SharedAgentInfo struct {
|
||||
DisabledByMe bool `json:"disabled_by_me"`
|
||||
}
|
||||
|
||||
// SourceFromAgentInfo indicates the KB is visible in the space via a shared agent (read-only, no KB share record).
|
||||
type SourceFromAgentInfo struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
AgentName string `json:"agent_name"`
|
||||
KBSelectionMode string `json:"kb_selection_mode"` // "all" | "selected" | "none"; for drawer copy "该智能体对知识库的策略"
|
||||
}
|
||||
|
||||
// OrganizationSharedKnowledgeBaseItem is used by GET /organizations/:id/shared-knowledge-bases (space-scoped list including mine).
|
||||
// When SourceFromAgent is set, the KB is from a shared agent's config (no direct KB share); show as read-only and "来自智能体 XXX".
|
||||
type OrganizationSharedKnowledgeBaseItem struct {
|
||||
SharedKnowledgeBaseInfo
|
||||
IsMine bool `json:"is_mine"`
|
||||
SourceFromAgent *SourceFromAgentInfo `json:"source_from_agent,omitempty"`
|
||||
}
|
||||
|
||||
// OrganizationSharedAgentItem is used by GET /organizations/:id/shared-agents (space-scoped list including mine).
|
||||
type OrganizationSharedAgentItem struct {
|
||||
SharedAgentInfo
|
||||
IsMine bool `json:"is_mine"`
|
||||
}
|
||||
|
||||
// TenantDisabledSharedAgent records that a tenant has "disabled" a shared agent for their own dropdown
|
||||
type TenantDisabledSharedAgent struct {
|
||||
TenantID uint64 `json:"tenant_id" gorm:"primaryKey"`
|
||||
@@ -421,6 +442,16 @@ type ListOrganizationsResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// ResourceCountsByOrgResponse is the response for GET /me/resource-counts (sidebar counts per space)
|
||||
type ResourceCountsByOrgResponse struct {
|
||||
KnowledgeBases struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
} `json:"knowledge_bases"`
|
||||
Agents struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
} `json:"agents"`
|
||||
}
|
||||
|
||||
// SearchableOrganizationItem is a searchable org item for discovery (no invite code)
|
||||
type SearchableOrganizationItem struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
Reference in New Issue
Block a user