feat: add organization management features
- Introduced a new API for organization management, including creation, updating, and deletion of organizations. - Implemented organization sharing functionality for knowledge bases, allowing users to share knowledge bases with specific organizations and set permissions. - Added UI components for organization selection and sharing dialogs. - Enhanced existing components to support organization-related features, including shared knowledge base handling and organization role management. This update enhances collaboration capabilities within the application by allowing users to manage and share knowledge bases across different organizations.
This commit is contained in:
@@ -369,7 +369,8 @@ func (t *DataAnalysisTool) LoadFromKnowledge(ctx context.Context, knowledge *typ
|
||||
// - *TableSchema: schema information of the created table
|
||||
// - error: any error that occurred during the operation
|
||||
func (t *DataAnalysisTool) LoadFromKnowledgeID(ctx context.Context, knowledgeID string) (*TableSchema, error) {
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
|
||||
// Use GetKnowledgeByIDOnly to support cross-tenant shared KB
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get knowledge by ID '%s': %v", knowledgeID, err)
|
||||
return nil, fmt.Errorf("failed to get knowledge by ID: %w", err)
|
||||
|
||||
@@ -49,8 +49,8 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty
|
||||
}, err
|
||||
}
|
||||
|
||||
// Get knowledge to get TenantID
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, input.KnowledgeID)
|
||||
// Get knowledge to get TenantID (use IDOnly to support cross-tenant shared KB)
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, input.KnowledgeID)
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
|
||||
@@ -54,27 +54,25 @@ type GetDocumentInfoTool struct {
|
||||
BaseTool
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
|
||||
}
|
||||
|
||||
// NewGetDocumentInfoTool creates a new get document info tool
|
||||
func NewGetDocumentInfoTool(
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
searchTargets types.SearchTargets,
|
||||
) *GetDocumentInfoTool {
|
||||
return &GetDocumentInfoTool{
|
||||
BaseTool: getDocumentInfoTool,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
searchTargets: searchTargets,
|
||||
}
|
||||
}
|
||||
|
||||
// Execute retrieves document information with concurrent processing
|
||||
func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
|
||||
// Parse args from json.RawMessage
|
||||
var input GetDocumentInfoInput
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
@@ -118,8 +116,8 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
|
||||
go func(id string) {
|
||||
defer wg.Done()
|
||||
|
||||
// Get knowledge metadata
|
||||
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, tenantID, id)
|
||||
// Get knowledge metadata without tenant filter to support shared KB
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
@@ -129,9 +127,19 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// Get chunk count
|
||||
// Verify the knowledge's KB is in searchTargets (permission check)
|
||||
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
err: fmt.Errorf("知识库 %s 不可访问", knowledge.KnowledgeBaseID),
|
||||
}
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Use knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
|
||||
_, total, err := t.chunkService.GetRepository().
|
||||
ListPagedChunksByKnowledgeID(ctx, tenantID, id, &types.Pagination{
|
||||
ListPagedChunksByKnowledgeID(ctx, knowledge.TenantID, id, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1000,
|
||||
}, []types.ChunkType{"text"}, "", "", "", "", "")
|
||||
|
||||
@@ -94,18 +94,16 @@ type GrepChunksInput struct {
|
||||
// Similar to grep command in Unix-like systems, but operates on knowledge base content
|
||||
type GrepChunksTool struct {
|
||||
BaseTool
|
||||
db *gorm.DB
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string // Specific knowledge/document IDs to search within
|
||||
db *gorm.DB
|
||||
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
|
||||
}
|
||||
|
||||
// NewGrepChunksTool creates a new grep chunks tool
|
||||
func NewGrepChunksTool(db *gorm.DB, knowledgeBaseIDs []string, knowledgeIDs []string) *GrepChunksTool {
|
||||
func NewGrepChunksTool(db *gorm.DB, searchTargets types.SearchTargets) *GrepChunksTool {
|
||||
return &GrepChunksTool{
|
||||
BaseTool: grepChunksTool,
|
||||
db: db,
|
||||
knowledgeBaseIDs: knowledgeBaseIDs,
|
||||
knowledgeIDs: knowledgeIDs,
|
||||
BaseTool: grepChunksTool,
|
||||
db: db,
|
||||
searchTargets: searchTargets,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,27 +146,38 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args json.RawMessage) (*ty
|
||||
}
|
||||
}
|
||||
|
||||
// Parse knowledge_base_ids filter
|
||||
kbIDs := input.KnowledgeBaseIDs
|
||||
if len(kbIDs) == 0 {
|
||||
kbIDs = t.knowledgeBaseIDs
|
||||
// Get allowed KBs from searchTargets
|
||||
allowedKBIDs := t.searchTargets.GetAllKnowledgeBaseIDs()
|
||||
kbTenantMap := t.searchTargets.GetKBTenantMap()
|
||||
|
||||
// Collect all specific knowledge IDs from searchTargets
|
||||
var allowedKnowledgeIDs []string
|
||||
for _, target := range t.searchTargets {
|
||||
if target.Type == types.SearchTargetTypeKnowledge && len(target.KnowledgeIDs) > 0 {
|
||||
allowedKnowledgeIDs = append(allowedKnowledgeIDs, target.KnowledgeIDs...)
|
||||
}
|
||||
}
|
||||
|
||||
// // Parse knowledge_ids filter
|
||||
// var knowledgeIDs []string
|
||||
// if knowledgeIDsRaw, ok := args["knowledge_ids"].([]interface{}); ok {
|
||||
// for _, id := range knowledgeIDsRaw {
|
||||
// if idStr, ok := id.(string); ok && idStr != "" {
|
||||
// knowledgeIDs = append(knowledgeIDs, idStr)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// Parse knowledge_base_ids filter from input
|
||||
kbIDs := input.KnowledgeBaseIDs
|
||||
if len(kbIDs) == 0 {
|
||||
kbIDs = allowedKBIDs
|
||||
} else {
|
||||
// Validate input KBs against allowed KBs
|
||||
validKBs := make([]string, 0)
|
||||
for _, kbID := range kbIDs {
|
||||
if t.searchTargets.ContainsKB(kbID) {
|
||||
validKBs = append(validKBs, kbID)
|
||||
}
|
||||
}
|
||||
kbIDs = validKBs
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Patterns: %v, MaxResults: %d, KnowledgeIDs: %v",
|
||||
patterns, maxResults, t.knowledgeIDs)
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Patterns: %v, MaxResults: %d, KBs: %v, KnowledgeIDs: %v, KBTenantMap: %v",
|
||||
patterns, maxResults, kbIDs, allowedKnowledgeIDs, kbTenantMap)
|
||||
|
||||
// Build and execute query
|
||||
results, totalCount, err := t.searchChunks(ctx, patterns, kbIDs, t.knowledgeIDs)
|
||||
// Build and execute query with tenant info
|
||||
results, totalCount, err := t.searchChunks(ctx, patterns, kbIDs, allowedKnowledgeIDs, kbTenantMap)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][GrepChunks] Search failed: %v", err)
|
||||
return &types.ToolResult{
|
||||
@@ -256,32 +265,53 @@ type chunkWithTitle struct {
|
||||
}
|
||||
|
||||
// searchChunks performs the database search with pattern matching
|
||||
// kbTenantMap provides KB-to-tenant mapping for cross-tenant queries
|
||||
func (t *GrepChunksTool) searchChunks(
|
||||
ctx context.Context,
|
||||
patterns []string,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
kbTenantMap map[string]uint64,
|
||||
) ([]chunkWithTitle, int64, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
// Safety check: must have either kbIDs or knowledgeIDs
|
||||
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
logger.Warnf(ctx, "[Tool][GrepChunks] No kbIDs or knowledgeIDs specified, returning empty results")
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
// Build base query
|
||||
// Use knowledge_base_id filter combined with tenant_id to ensure data isolation
|
||||
query := t.db.Debug().WithContext(ctx).Table("chunks").
|
||||
Select("chunks.id, chunks.content, chunks.chunk_index, chunks.knowledge_id, chunks.knowledge_base_id, chunks.chunk_type, chunks.created_at, knowledges.title as knowledge_title, COUNT(*) OVER (PARTITION BY chunks.knowledge_id) AS total_chunk_count").
|
||||
Joins("LEFT JOIN knowledges ON chunks.knowledge_id = knowledges.id").
|
||||
Where("chunks.tenant_id = ?", tenantID).
|
||||
Where("chunks.is_enabled = ?", true).
|
||||
Where("chunks.deleted_at IS NULL").
|
||||
Where("knowledges.deleted_at IS NULL")
|
||||
|
||||
// Apply knowledge IDs filter (specific documents) - takes priority over KB filter
|
||||
// Build tenant-aware KB filter: (kb_id = X AND tenant_id = Y) OR (kb_id = Z AND tenant_id = W) ...
|
||||
// This ensures we only access chunks from KBs we have permission for, with correct tenant scope
|
||||
if len(knowledgeIDs) > 0 {
|
||||
// For specific knowledge IDs, filter directly by knowledge_id
|
||||
// Permission already checked when building searchTargets
|
||||
query = query.Where("chunks.knowledge_id IN ?", knowledgeIDs)
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Filtering by %d specific knowledge IDs", len(knowledgeIDs))
|
||||
} else if len(kbIDs) > 0 {
|
||||
// Apply knowledge base filter only if no specific knowledge IDs
|
||||
query = query.Where("chunks.knowledge_base_id IN ?", kbIDs)
|
||||
// Build OR conditions for each KB with its tenant
|
||||
var conditions []string
|
||||
var args []interface{}
|
||||
for _, kbID := range kbIDs {
|
||||
tenantID := kbTenantMap[kbID]
|
||||
if tenantID > 0 {
|
||||
conditions = append(conditions, "(chunks.knowledge_base_id = ? AND chunks.tenant_id = ?)")
|
||||
args = append(args, kbID, tenantID)
|
||||
}
|
||||
}
|
||||
if len(conditions) > 0 {
|
||||
query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
|
||||
} else {
|
||||
logger.Warnf(ctx, "[Tool][GrepChunks] No valid KB-tenant pairs found")
|
||||
return nil, 0, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Apply pattern matching (case-insensitive fixed string matching, OR logic for multiple patterns)
|
||||
|
||||
@@ -965,10 +965,6 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
kbsToSearch []string,
|
||||
queries []string,
|
||||
) (*types.ToolResult, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
if len(results) == 0 {
|
||||
data := map[string]interface{}{
|
||||
"knowledge_base_ids": kbsToSearch,
|
||||
@@ -1052,22 +1048,30 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle)
|
||||
|
||||
// Get total chunk count for this knowledge (cache it)
|
||||
// Use KB's tenant_id from searchTargets to support cross-tenant shared KB
|
||||
if _, exists := knowledgeTotalMap[result.KnowledgeID]; !exists {
|
||||
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
tenantID, result.KnowledgeID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
|
||||
result.KnowledgeID,
|
||||
err,
|
||||
)
|
||||
// Get tenant_id from searchTargets using the KB ID from the result
|
||||
effectiveTenantID := t.searchTargets.GetTenantIDForKB(result.KnowledgeBaseID)
|
||||
if effectiveTenantID == 0 {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count", result.KnowledgeBaseID)
|
||||
knowledgeTotalMap[result.KnowledgeID] = 0
|
||||
} else {
|
||||
knowledgeTotalMap[result.KnowledgeID] = total
|
||||
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
effectiveTenantID, result.KnowledgeID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
|
||||
result.KnowledgeID,
|
||||
err,
|
||||
)
|
||||
knowledgeTotalMap[result.KnowledgeID] = 0
|
||||
} else {
|
||||
knowledgeTotalMap[result.KnowledgeID] = total
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,27 +67,25 @@ type ListKnowledgeChunksTool struct {
|
||||
BaseTool
|
||||
chunkService interfaces.ChunkService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
|
||||
}
|
||||
|
||||
// NewListKnowledgeChunksTool creates a new tool instance.
|
||||
func NewListKnowledgeChunksTool(
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
searchTargets types.SearchTargets,
|
||||
) *ListKnowledgeChunksTool {
|
||||
return &ListKnowledgeChunksTool{
|
||||
BaseTool: listKnowledgeChunksTool,
|
||||
chunkService: chunkService,
|
||||
knowledgeService: knowledgeService,
|
||||
searchTargets: searchTargets,
|
||||
}
|
||||
}
|
||||
|
||||
// Execute performs the chunk fetch against the chunk service.
|
||||
func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
|
||||
// Parse args from json.RawMessage
|
||||
var input ListKnowledgeChunksInput
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
@@ -107,6 +105,26 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
||||
}
|
||||
knowledgeID = strings.TrimSpace(knowledgeID)
|
||||
|
||||
// Get knowledge info without tenant filter to support shared KB
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Knowledge not found: %v", err),
|
||||
}, err
|
||||
}
|
||||
|
||||
// Verify the knowledge's KB is in searchTargets (permission check)
|
||||
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Knowledge base %s is not accessible", knowledge.KnowledgeBaseID),
|
||||
}, fmt.Errorf("knowledge base not in search targets")
|
||||
}
|
||||
|
||||
// Use the knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
|
||||
effectiveTenantID := knowledge.TenantID
|
||||
|
||||
chunkLimit := 20
|
||||
if input.Limit > 0 {
|
||||
chunkLimit = input.Limit
|
||||
@@ -125,7 +143,7 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
||||
}
|
||||
|
||||
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
|
||||
effectiveTenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
@@ -206,11 +224,12 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
||||
}
|
||||
|
||||
// lookupKnowledgeTitle looks up the title of a knowledge document
|
||||
// Uses GetKnowledgeByIDOnly to support cross-tenant shared KB
|
||||
func (t *ListKnowledgeChunksTool) lookupKnowledgeTitle(ctx context.Context, knowledgeID string) string {
|
||||
if t.knowledgeService == nil {
|
||||
return ""
|
||||
}
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil || knowledge == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -44,6 +44,18 @@ func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint64, id
|
||||
return &chunk, nil
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly retrieves a chunk by ID without tenant filter (for permission resolution).
|
||||
func (r *chunkRepository) GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error) {
|
||||
var chunk types.Chunk
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&chunk).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("chunk not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &chunk, nil
|
||||
}
|
||||
|
||||
// GetChunkBySeqID retrieves a chunk by its seq_id and tenant ID
|
||||
func (r *chunkRepository) GetChunkBySeqID(ctx context.Context, tenantID uint64, seqID int64) (*types.Chunk, error) {
|
||||
var chunk types.Chunk
|
||||
@@ -69,6 +81,18 @@ func (r *chunkRepository) ListChunksByID(
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// ListChunksByIDOnly retrieves multiple chunks by their IDs without tenant filter (for shared KB resolution).
|
||||
func (r *chunkRepository) ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var chunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// ListChunksBySeqID retrieves multiple chunks by their seq_ids
|
||||
func (r *chunkRepository) ListChunksBySeqID(
|
||||
ctx context.Context, tenantID uint64, seqIDs []int64,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrKBShareNotFound = errors.New("knowledge base share not found")
|
||||
ErrKBShareAlreadyExists = errors.New("knowledge base already shared to this organization")
|
||||
)
|
||||
|
||||
// kbShareRepository implements KBShareRepository interface
|
||||
type kbShareRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewKBShareRepository creates a new knowledge base share repository
|
||||
func NewKBShareRepository(db *gorm.DB) interfaces.KBShareRepository {
|
||||
return &kbShareRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new share record
|
||||
func (r *kbShareRepository) Create(ctx context.Context, share *types.KnowledgeBaseShare) error {
|
||||
// Check if share already exists
|
||||
var count int64
|
||||
r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("knowledge_base_id = ? AND organization_id = ? AND deleted_at IS NULL", share.KnowledgeBaseID, share.OrganizationID).
|
||||
Count(&count)
|
||||
|
||||
if count > 0 {
|
||||
return ErrKBShareAlreadyExists
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Create(share).Error
|
||||
}
|
||||
|
||||
// GetByID gets a share record by ID
|
||||
func (r *kbShareRepository) GetByID(ctx context.Context, id string) (*types.KnowledgeBaseShare, error) {
|
||||
var share types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
First(&share).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKBShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// GetByKBAndOrg gets a share record by knowledge base ID and organization ID
|
||||
func (r *kbShareRepository) GetByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error) {
|
||||
var share types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND organization_id = ?", kbID, orgID).
|
||||
First(&share).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKBShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// Update updates a share record
|
||||
func (r *kbShareRepository) Update(ctx context.Context, share *types.KnowledgeBaseShare) error {
|
||||
return r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("id = ?", share.ID).
|
||||
Updates(share).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes a share record
|
||||
func (r *kbShareRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeBaseID soft deletes all share records for a knowledge base (e.g. when the KB is deleted)
|
||||
func (r *kbShareRepository) DeleteByKnowledgeBaseID(ctx context.Context, kbID string) error {
|
||||
return r.db.WithContext(ctx).Where("knowledge_base_id = ?", kbID).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByOrganizationID soft deletes all share records for an organization (e.g. when the org is deleted)
|
||||
func (r *kbShareRepository) DeleteByOrganizationID(ctx context.Context, orgID string) error {
|
||||
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// ListByKnowledgeBase lists all share records for a knowledge base
|
||||
func (r *kbShareRepository) ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Organization").
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Order("created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganization lists all share records for an organization
|
||||
func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("KnowledgeBase").
|
||||
Where("organization_id = ?", orgID).
|
||||
Order("created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListSharedKBsForUser lists all knowledge bases shared to organizations that the user belongs to.
|
||||
// Excludes shares for soft-deleted organizations so users no longer see KBs after the space is deleted.
|
||||
func (r *kbShareRepository) ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
|
||||
// Get shares for organizations that the user is a member of; exclude deleted organizations
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Joins("JOIN organization_members ON organization_members.organization_id = kb_shares.organization_id").
|
||||
Joins("JOIN organizations ON organizations.id = kb_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||
Where("organization_members.user_id = ?", userID).
|
||||
Where("kb_shares.deleted_at IS NULL").
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseID counts the number of organizations a knowledge base is shared with
|
||||
func (r *kbShareRepository) CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("knowledge_base_id = ? AND deleted_at IS NULL", kbID).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseIDs counts the number of shares for multiple knowledge bases at once
|
||||
func (r *kbShareRepository) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
|
||||
if len(kbIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
|
||||
type result struct {
|
||||
KnowledgeBaseID string `gorm:"column:knowledge_base_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
|
||||
var results []result
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Select("knowledge_base_id, COUNT(*) as count").
|
||||
Where("knowledge_base_id IN ? AND deleted_at IS NULL", kbIDs).
|
||||
Group("knowledge_base_id").
|
||||
Find(&results).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
countMap := make(map[string]int64)
|
||||
for _, r := range results {
|
||||
countMap[r.KnowledgeBaseID] = r.Count
|
||||
}
|
||||
return countMap, nil
|
||||
}
|
||||
@@ -47,6 +47,18 @@ func (r *knowledgeRepository) GetKnowledgeByID(
|
||||
return &knowledge, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution).
|
||||
func (r *knowledgeRepository) GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error) {
|
||||
var knowledge types.Knowledge
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&knowledge).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKnowledgeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &knowledge, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base
|
||||
func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context, tenantID uint64, kbID string,
|
||||
@@ -402,6 +414,111 @@ func (r *knowledgeRepository) SearchKnowledge(
|
||||
return knowledges, hasMore, nil
|
||||
}
|
||||
|
||||
// SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (e.g. own + shared KBs).
|
||||
func (r *knowledgeRepository) SearchKnowledgeInScopes(
|
||||
ctx context.Context,
|
||||
scopes []types.KnowledgeSearchScope,
|
||||
keyword string,
|
||||
offset, limit int,
|
||||
fileTypes []string,
|
||||
) ([]*types.Knowledge, bool, error) {
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
type KnowledgeWithKBName struct {
|
||||
types.Knowledge
|
||||
KnowledgeBaseName string `gorm:"column:knowledge_base_name"`
|
||||
}
|
||||
|
||||
placeholders := make([]string, len(scopes))
|
||||
args := make([]interface{}, 0, len(scopes)*2)
|
||||
for i, s := range scopes {
|
||||
placeholders[i] = "(?,?)"
|
||||
args = append(args, s.TenantID, s.KBID)
|
||||
}
|
||||
scopeCondition := "(knowledges.tenant_id, knowledges.knowledge_base_id) IN (" + strings.Join(placeholders, ",") + ")"
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("knowledges").
|
||||
Select("knowledges.*, knowledge_bases.name as knowledge_base_name").
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = knowledges.knowledge_base_id AND knowledge_bases.tenant_id = knowledges.tenant_id").
|
||||
Where(scopeCondition, args...).
|
||||
Where("knowledge_bases.type = ?", types.KnowledgeBaseTypeDocument).
|
||||
Where("knowledges.deleted_at IS NULL")
|
||||
|
||||
if keyword != "" {
|
||||
query = query.Where("knowledges.file_name LIKE ?", "%"+keyword+"%")
|
||||
}
|
||||
|
||||
if len(fileTypes) > 0 {
|
||||
seen := make(map[string]bool)
|
||||
var uniquePatterns []string
|
||||
for _, ft := range fileTypes {
|
||||
ft = strings.ToLower(strings.TrimPrefix(ft, "."))
|
||||
pattern := "%." + ft
|
||||
if !seen[pattern] {
|
||||
seen[pattern] = true
|
||||
uniquePatterns = append(uniquePatterns, pattern)
|
||||
}
|
||||
var aliases []string
|
||||
switch ft {
|
||||
case "xlsx":
|
||||
aliases = []string{"%.xls"}
|
||||
case "xls":
|
||||
aliases = []string{"%.xlsx"}
|
||||
case "docx":
|
||||
aliases = []string{"%.doc"}
|
||||
case "doc":
|
||||
aliases = []string{"%.docx"}
|
||||
case "jpg":
|
||||
aliases = []string{"%.jpeg", "%.png"}
|
||||
case "jpeg":
|
||||
aliases = []string{"%.jpg", "%.png"}
|
||||
case "png":
|
||||
aliases = []string{"%.jpg", "%.jpeg"}
|
||||
}
|
||||
for _, alias := range aliases {
|
||||
if !seen[alias] {
|
||||
seen[alias] = true
|
||||
uniquePatterns = append(uniquePatterns, alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(uniquePatterns) > 0 {
|
||||
orConditions := make([]string, len(uniquePatterns))
|
||||
ftArgs := make([]interface{}, len(uniquePatterns))
|
||||
for i, p := range uniquePatterns {
|
||||
orConditions[i] = "LOWER(knowledges.file_name) LIKE ?"
|
||||
ftArgs[i] = p
|
||||
}
|
||||
query = query.Where("("+strings.Join(orConditions, " OR ")+")", ftArgs...)
|
||||
}
|
||||
}
|
||||
|
||||
var results []KnowledgeWithKBName
|
||||
err := query.Order("knowledges.created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit + 1).
|
||||
Scan(&results).Error
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
hasMore := len(results) > limit
|
||||
if hasMore {
|
||||
results = results[:limit]
|
||||
}
|
||||
|
||||
knowledges := make([]*types.Knowledge, len(results))
|
||||
for i, r := range results {
|
||||
k := r.Knowledge
|
||||
k.KnowledgeBaseName = r.KnowledgeBaseName
|
||||
knowledges[i] = &k
|
||||
}
|
||||
return knowledges, hasMore, nil
|
||||
}
|
||||
|
||||
// ListIDsByTagID returns all knowledge IDs that have the specified tag ID
|
||||
func (r *knowledgeRepository) ListIDsByTagID(
|
||||
ctx context.Context,
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrOrganizationNotFound = errors.New("organization not found")
|
||||
ErrOrgMemberNotFound = errors.New("organization member not found")
|
||||
ErrOrgMemberAlreadyExists = errors.New("member already exists in organization")
|
||||
ErrInviteCodeNotFound = errors.New("invite code not found")
|
||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||
)
|
||||
|
||||
// organizationRepository implements OrganizationRepository interface
|
||||
type organizationRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewOrganizationRepository creates a new organization repository
|
||||
func NewOrganizationRepository(db *gorm.DB) interfaces.OrganizationRepository {
|
||||
return &organizationRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new organization
|
||||
func (r *organizationRepository) Create(ctx context.Context, org *types.Organization) error {
|
||||
return r.db.WithContext(ctx).Create(org).Error
|
||||
}
|
||||
|
||||
// GetByID gets an organization by ID
|
||||
func (r *organizationRepository) GetByID(ctx context.Context, id string) (*types.Organization, error) {
|
||||
var org types.Organization
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOrganizationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
// GetByInviteCode gets an organization by invite code (returns ErrInviteCodeExpired if code has expired)
|
||||
func (r *organizationRepository) GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) {
|
||||
var org types.Organization
|
||||
if err := r.db.WithContext(ctx).Where("invite_code = ?", inviteCode).First(&org).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrInviteCodeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if org.InviteCodeExpiresAt != nil && org.InviteCodeExpiresAt.Before(time.Now()) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
// ListByUserID lists organizations that a user belongs to
|
||||
func (r *organizationRepository) ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error) {
|
||||
var orgs []*types.Organization
|
||||
|
||||
// Get organizations where user is a member
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN organization_members ON organization_members.organization_id = organizations.id").
|
||||
Where("organization_members.user_id = ?", userID).
|
||||
Order("organizations.created_at DESC").
|
||||
Find(&orgs).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return orgs, nil
|
||||
}
|
||||
|
||||
// Update updates an organization (Select ensures zero values like invite_code_validity_days=0 are persisted)
|
||||
func (r *organizationRepository) Update(ctx context.Context, org *types.Organization) error {
|
||||
return r.db.WithContext(ctx).Model(&types.Organization{}).Where("id = ?", org.ID).
|
||||
Select("name", "description", "require_approval", "invite_code_validity_days", "updated_at").
|
||||
Updates(org).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes an organization
|
||||
func (r *organizationRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Organization{}).Error
|
||||
}
|
||||
|
||||
// AddMember adds a member to an organization
|
||||
func (r *organizationRepository) AddMember(ctx context.Context, member *types.OrganizationMember) error {
|
||||
// Check if member already exists
|
||||
var count int64
|
||||
r.db.WithContext(ctx).Model(&types.OrganizationMember{}).
|
||||
Where("organization_id = ? AND user_id = ?", member.OrganizationID, member.UserID).
|
||||
Count(&count)
|
||||
|
||||
if count > 0 {
|
||||
return ErrOrgMemberAlreadyExists
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Create(member).Error
|
||||
}
|
||||
|
||||
// RemoveMember removes a member from an organization
|
||||
func (r *organizationRepository) RemoveMember(ctx context.Context, orgID string, userID string) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
||||
Delete(&types.OrganizationMember{})
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrOrgMemberNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateMemberRole updates a member's role in an organization
|
||||
func (r *organizationRepository) UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationMember{}).
|
||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
||||
Update("role", role)
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrOrgMemberNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListMembers lists all members of an organization
|
||||
func (r *organizationRepository) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) {
|
||||
var members []*types.OrganizationMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("organization_id = ?", orgID).
|
||||
Order("created_at ASC").
|
||||
Find(&members).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// GetMember gets a specific member of an organization
|
||||
func (r *organizationRepository) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) {
|
||||
var member types.OrganizationMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
||||
First(&member).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOrgMemberNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &member, nil
|
||||
}
|
||||
|
||||
// CountMembers counts the number of members in an organization
|
||||
func (r *organizationRepository) CountMembers(ctx context.Context, orgID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationMember{}).
|
||||
Where("organization_id = ?", orgID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpdateInviteCode updates the invite code and optional expiry for an organization (expiresAt nil = never expire)
|
||||
func (r *organizationRepository) UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error {
|
||||
updates := map[string]interface{}{"invite_code": inviteCode, "invite_code_expires_at": expiresAt}
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.Organization{}).
|
||||
Where("id = ?", orgID).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
// ----------------
|
||||
// Join Requests
|
||||
// ----------------
|
||||
|
||||
var ErrJoinRequestNotFound = errors.New("join request not found")
|
||||
|
||||
// CreateJoinRequest creates a new join request
|
||||
func (r *organizationRepository) CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error {
|
||||
return r.db.WithContext(ctx).Create(request).Error
|
||||
}
|
||||
|
||||
// GetJoinRequestByID gets a join request by ID
|
||||
func (r *organizationRepository) GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("id = ?", id).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// GetPendingJoinRequest gets a pending join request for a user in an organization (any type)
|
||||
func (r *organizationRepository) GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ? AND status = ?", orgID, userID, types.JoinRequestStatusPending).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// GetPendingRequestByType gets a pending request for a user filtered by request type
|
||||
func (r *organizationRepository) GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ? AND status = ? AND request_type = ?", orgID, userID, types.JoinRequestStatusPending, requestType).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// ListJoinRequests lists join requests for an organization
|
||||
func (r *organizationRepository) ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error) {
|
||||
var requests []*types.OrganizationJoinRequest
|
||||
query := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("organization_id = ?", orgID)
|
||||
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
err := query.Order("created_at DESC").Find(&requests).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return requests, nil
|
||||
}
|
||||
|
||||
// CountJoinRequests counts join requests for an organization by status
|
||||
func (r *organizationRepository) CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&types.OrganizationJoinRequest{}).Where("organization_id = ?", orgID)
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpdateJoinRequestStatus updates the status of a join request
|
||||
func (r *organizationRepository) UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationJoinRequest{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": status,
|
||||
"reviewed_by": reviewedBy,
|
||||
"reviewed_at": gorm.Expr("NOW()"),
|
||||
"review_message": reviewMessage,
|
||||
}).Error
|
||||
}
|
||||
@@ -95,6 +95,28 @@ func (r *userRepository) ListUsers(ctx context.Context, offset, limit int) ([]*t
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// SearchUsers searches users by username or email
|
||||
func (r *userRepository) SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error) {
|
||||
var users []*types.User
|
||||
searchPattern := "%" + query + "%"
|
||||
|
||||
dbQuery := r.db.WithContext(ctx).
|
||||
Where("username ILIKE ? OR email ILIKE ?", searchPattern, searchPattern).
|
||||
Where("is_active = ?", true).
|
||||
Order("username ASC")
|
||||
|
||||
if limit > 0 {
|
||||
dbQuery = dbQuery.Limit(limit)
|
||||
} else {
|
||||
dbQuery = dbQuery.Limit(20) // default limit
|
||||
}
|
||||
|
||||
if err := dbQuery.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// authTokenRepository implements auth token repository interface
|
||||
type authTokenRepository struct {
|
||||
db *gorm.DB
|
||||
|
||||
@@ -366,14 +366,14 @@ func (s *agentService) registerTools(
|
||||
s.cfg,
|
||||
)
|
||||
case tools.ToolGrepChunks:
|
||||
toolToRegister = tools.NewGrepChunksTool(s.db, config.KnowledgeBases, config.KnowledgeIDs)
|
||||
logger.Infof(ctx, "Registered grep_chunks tool, KBs: %d, KnowledgeIDs: %d", len(config.KnowledgeBases), len(config.KnowledgeIDs))
|
||||
toolToRegister = tools.NewGrepChunksTool(s.db, config.SearchTargets)
|
||||
logger.Infof(ctx, "Registered grep_chunks tool with searchTargets: %d targets", len(config.SearchTargets))
|
||||
case tools.ToolListKnowledgeChunks:
|
||||
toolToRegister = tools.NewListKnowledgeChunksTool(s.knowledgeService, s.chunkService)
|
||||
toolToRegister = tools.NewListKnowledgeChunksTool(s.knowledgeService, s.chunkService, config.SearchTargets)
|
||||
case tools.ToolQueryKnowledgeGraph:
|
||||
toolToRegister = tools.NewQueryKnowledgeGraphTool(s.knowledgeBaseService)
|
||||
case tools.ToolGetDocumentInfo:
|
||||
toolToRegister = tools.NewGetDocumentInfoTool(s.knowledgeService, s.chunkService)
|
||||
toolToRegister = tools.NewGetDocumentInfoTool(s.knowledgeService, s.chunkService, config.SearchTargets)
|
||||
case tools.ToolDatabaseQuery:
|
||||
toolToRegister = tools.NewDatabaseQueryTool(s.db)
|
||||
case tools.ToolWebSearch:
|
||||
|
||||
@@ -100,6 +100,19 @@ func (s *chunkService) GetChunkByID(ctx context.Context, id string) (*types.Chun
|
||||
return chunk, nil
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly retrieves a chunk by ID without tenant filter (for permission resolution).
|
||||
func (s *chunkService) GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error) {
|
||||
chunk, err := s.chunkRepository.GetChunkByIDOnly(ctx, id)
|
||||
if err != nil {
|
||||
if err != nil && err.Error() == "chunk not found" {
|
||||
return nil, ErrChunkNotFound
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"chunk_id": id})
|
||||
return nil, err
|
||||
}
|
||||
return chunk, nil
|
||||
}
|
||||
|
||||
// ListChunksByKnowledgeID lists all chunks for a knowledge ID
|
||||
// This method retrieves all chunks belonging to a specific knowledge document
|
||||
// Parameters:
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrShareNotFound = errors.New("share not found")
|
||||
ErrSharePermissionDenied = errors.New("permission denied for this share operation")
|
||||
ErrKBNotFound = errors.New("knowledge base not found")
|
||||
ErrNotKBOwner = errors.New("only knowledge base owner can share")
|
||||
// ErrOrgRoleCannotShare: only editors and admins in the org can share KBs to that org; viewers cannot
|
||||
ErrOrgRoleCannotShare = errors.New("only editors and admins can share knowledge bases to this organization")
|
||||
)
|
||||
|
||||
// kbShareService implements KBShareService interface
|
||||
type kbShareService struct {
|
||||
shareRepo interfaces.KBShareRepository
|
||||
orgRepo interfaces.OrganizationRepository
|
||||
kbRepo interfaces.KnowledgeBaseRepository
|
||||
kgRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
}
|
||||
|
||||
// NewKBShareService creates a new knowledge base share service
|
||||
func NewKBShareService(
|
||||
shareRepo interfaces.KBShareRepository,
|
||||
orgRepo interfaces.OrganizationRepository,
|
||||
kbRepo interfaces.KnowledgeBaseRepository,
|
||||
kgRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
) interfaces.KBShareService {
|
||||
return &kbShareService{
|
||||
shareRepo: shareRepo,
|
||||
orgRepo: orgRepo,
|
||||
kbRepo: kbRepo,
|
||||
kgRepo: kgRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// ShareKnowledgeBase shares a knowledge base to an organization
|
||||
func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error) {
|
||||
logger.Infof(ctx, "Sharing knowledge base %s to organization %s", kbID, orgID)
|
||||
|
||||
// Verify knowledge base exists and user is the owner (same tenant)
|
||||
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, ErrKBNotFound
|
||||
}
|
||||
|
||||
// Check if user's tenant owns the knowledge base
|
||||
if kb.TenantID != tenantID {
|
||||
return nil, ErrNotKBOwner
|
||||
}
|
||||
|
||||
// Verify organization exists
|
||||
_, err = s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if user is a member of the organization and has at least editor role (viewers cannot share KBs to the org)
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !member.Role.HasPermission(types.OrgRoleEditor) {
|
||||
return nil, ErrOrgRoleCannotShare
|
||||
}
|
||||
|
||||
if !permission.IsValid() {
|
||||
return nil, ErrInvalidRole
|
||||
}
|
||||
|
||||
share := &types.KnowledgeBaseShare{
|
||||
ID: uuid.New().String(),
|
||||
KnowledgeBaseID: kbID,
|
||||
OrganizationID: orgID,
|
||||
SharedByUserID: userID,
|
||||
SourceTenantID: tenantID,
|
||||
Permission: permission,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.shareRepo.Create(ctx, share); err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareAlreadyExists) {
|
||||
// Update existing share
|
||||
existingShare, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existingShare.Permission = permission
|
||||
existingShare.UpdatedAt = time.Now()
|
||||
if err := s.shareRepo.Update(ctx, existingShare); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return existingShare, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge base %s shared successfully to organization %s", kbID, orgID)
|
||||
return share, nil
|
||||
}
|
||||
|
||||
// UpdateSharePermission updates the permission of a share
|
||||
func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return ErrShareNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Only the user who shared can update
|
||||
if share.SharedByUserID != userID {
|
||||
return ErrSharePermissionDenied
|
||||
}
|
||||
|
||||
if !permission.IsValid() {
|
||||
return ErrInvalidRole
|
||||
}
|
||||
|
||||
share.Permission = permission
|
||||
share.UpdatedAt = time.Now()
|
||||
|
||||
return s.shareRepo.Update(ctx, share)
|
||||
}
|
||||
|
||||
// RemoveShare removes a share.
|
||||
// Allowed if: (1) current user is the sharer, or (2) current user is admin of the target organization.
|
||||
// Org admins can unlink any KB shared to their org (e.g. content governance, sharer left).
|
||||
func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string) error {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return ErrShareNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Sharer can always remove their own share
|
||||
if share.SharedByUserID == userID {
|
||||
return s.shareRepo.Delete(ctx, shareID)
|
||||
}
|
||||
|
||||
// Org admin can remove any share targeting their organization
|
||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
||||
if err == nil && member.Role == types.OrgRoleAdmin {
|
||||
return s.shareRepo.Delete(ctx, shareID)
|
||||
}
|
||||
|
||||
return ErrSharePermissionDenied
|
||||
}
|
||||
|
||||
// ListSharesByKnowledgeBase lists all shares for a knowledge base
|
||||
func (s *kbShareService) ListSharesByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
return s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||
}
|
||||
|
||||
// ListSharesByOrganization lists all shares for an organization
|
||||
func (s *kbShareService) ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
return s.shareRepo.ListByOrganization(ctx, orgID)
|
||||
}
|
||||
|
||||
// ListSharedKnowledgeBases lists all knowledge bases shared to the user through organizations
|
||||
// It filters out knowledge bases that belong to the user's own tenant
|
||||
// It deduplicates knowledge bases that are shared to multiple organizations the user belongs to
|
||||
func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error) {
|
||||
shares, err := s.shareRepo.ListSharedKBsForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use a map to deduplicate by knowledge base ID, keeping the one with highest permission
|
||||
kbInfoMap := make(map[string]*types.SharedKnowledgeBaseInfo)
|
||||
|
||||
for _, share := range shares {
|
||||
// Skip knowledge bases that belong to the user's own tenant
|
||||
// (user already has full ownership of these)
|
||||
if share.SourceTenantID == currentTenantID {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip if knowledge base is nil
|
||||
if share.KnowledgeBase == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
kbID := share.KnowledgeBase.ID
|
||||
|
||||
// Get user's role in the organization
|
||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
||||
if err != nil {
|
||||
continue // Skip if user is not a member anymore
|
||||
}
|
||||
|
||||
// Effective permission is the lower of share permission and user's org role
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
|
||||
kb := share.KnowledgeBase
|
||||
// Calculate knowledge/chunk count based on type
|
||||
switch kb.Type {
|
||||
case types.KnowledgeBaseTypeDocument:
|
||||
knowledgeCount, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge count for shared KB %s: %v", kb.ID, err)
|
||||
} else {
|
||||
kb.KnowledgeCount = knowledgeCount
|
||||
}
|
||||
case types.KnowledgeBaseTypeFAQ:
|
||||
chunkCount, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get chunk count for shared KB %s: %v", kb.ID, err)
|
||||
} else {
|
||||
kb.ChunkCount = chunkCount
|
||||
}
|
||||
}
|
||||
|
||||
info := &types.SharedKnowledgeBaseInfo{
|
||||
KnowledgeBase: kb,
|
||||
ShareID: share.ID,
|
||||
OrganizationID: share.OrganizationID,
|
||||
OrgName: "",
|
||||
Permission: effectivePermission,
|
||||
SourceTenantID: share.SourceTenantID,
|
||||
SharedAt: share.CreatedAt,
|
||||
}
|
||||
|
||||
if share.Organization != nil {
|
||||
info.OrgName = share.Organization.Name
|
||||
}
|
||||
|
||||
// Check if we already have this knowledge base
|
||||
existing, exists := kbInfoMap[kbID]
|
||||
if !exists {
|
||||
// First time seeing this KB, add it
|
||||
kbInfoMap[kbID] = info
|
||||
} else {
|
||||
// KB already exists, keep the one with higher permission
|
||||
// Permission hierarchy: admin(3) > editor(2) > viewer(1)
|
||||
// If current permission is higher than existing, replace
|
||||
// This handles the case where a user belongs to multiple orgs with different permissions
|
||||
if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission {
|
||||
// Current permission is higher, replace with higher permission
|
||||
kbInfoMap[kbID] = info
|
||||
}
|
||||
// If existing permission is higher or equal, keep existing (no change needed)
|
||||
}
|
||||
}
|
||||
|
||||
// Convert map to slice
|
||||
result := make([]*types.SharedKnowledgeBaseInfo, 0, len(kbInfoMap))
|
||||
for _, info := range kbInfoMap {
|
||||
result = append(result, info)
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return nil, ErrShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return share, nil
|
||||
}
|
||||
|
||||
// GetShareByKBAndOrg gets a share by knowledge base and organization
|
||||
func (s *kbShareService) GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error) {
|
||||
share, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return nil, ErrShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return share, nil
|
||||
}
|
||||
|
||||
// CheckUserKBPermission checks a user's permission for a knowledge base
|
||||
// Returns: permission level, isShared, error
|
||||
func (s *kbShareService) CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error) {
|
||||
// Get all shares for this knowledge base
|
||||
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
var highestPermission types.OrgMemberRole
|
||||
isShared := false
|
||||
|
||||
for _, share := range shares {
|
||||
// Check if user is a member of the organization
|
||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
||||
if err != nil {
|
||||
continue // User is not a member of this org
|
||||
}
|
||||
|
||||
isShared = true
|
||||
|
||||
// Effective permission is the lower of share permission and user's org role
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
|
||||
// Keep the highest permission
|
||||
if highestPermission == "" || effectivePermission.HasPermission(highestPermission) {
|
||||
highestPermission = effectivePermission
|
||||
}
|
||||
}
|
||||
|
||||
return highestPermission, isShared, nil
|
||||
}
|
||||
|
||||
// HasKBPermission checks if a user has at least the required permission level for a knowledge base
|
||||
func (s *kbShareService) HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) {
|
||||
permission, isShared, err := s.CheckUserKBPermission(ctx, kbID, userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if !isShared {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return permission.HasPermission(requiredRole), nil
|
||||
}
|
||||
|
||||
// GetKBSourceTenant gets the source tenant ID for a shared knowledge base
|
||||
func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error) {
|
||||
// First check if there are any shares for this KB
|
||||
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if len(shares) > 0 {
|
||||
return shares[0].SourceTenantID, nil
|
||||
}
|
||||
|
||||
// If not shared, get the tenant from the knowledge base itself
|
||||
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return 0, ErrKBNotFound
|
||||
}
|
||||
|
||||
return kb.TenantID, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseIDs counts the number of shares for multiple knowledge bases
|
||||
func (s *kbShareService) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
|
||||
return s.shareRepo.CountSharesByKnowledgeBaseIDs(ctx, kbIDs)
|
||||
}
|
||||
@@ -70,6 +70,7 @@ type knowledgeService struct {
|
||||
task *asynq.Client
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -95,6 +96,7 @@ func NewKnowledgeService(
|
||||
graphEngine interfaces.RetrieveGraphRepository,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
redisClient *redis.Client,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) (interfaces.KnowledgeService, error) {
|
||||
return &knowledgeService{
|
||||
config: config,
|
||||
@@ -112,6 +114,7 @@ func NewKnowledgeService(
|
||||
graphEngine: graphEngine,
|
||||
retrieveEngine: retrieveEngine,
|
||||
redisClient: redisClient,
|
||||
kbShareService: kbShareService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -713,6 +716,11 @@ func (s *knowledgeService) GetKnowledgeByID(ctx context.Context, id string) (*ty
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeByIDOnly retrieves knowledge by ID without tenant filter (for permission resolution).
|
||||
func (s *knowledgeService) GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error) {
|
||||
return s.repo.GetKnowledgeByIDOnly(ctx, id)
|
||||
}
|
||||
|
||||
// ListKnowledgeByKnowledgeBaseID returns all knowledge entries in a knowledge base
|
||||
func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
kbID string,
|
||||
@@ -2229,6 +2237,50 @@ func (s *knowledgeService) GetKnowledgeBatch(ctx context.Context,
|
||||
return s.repo.GetKnowledgeBatch(ctx, tenantID, ids)
|
||||
}
|
||||
|
||||
// GetKnowledgeBatchWithSharedAccess retrieves knowledge by IDs, including items from shared KBs the user has access to.
|
||||
// Used when building search targets so that @mentioned files from shared KBs are included.
|
||||
func (s *knowledgeService) GetKnowledgeBatchWithSharedAccess(ctx context.Context,
|
||||
tenantID uint64, ids []string,
|
||||
) ([]*types.Knowledge, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
ownList, err := s.repo.GetKnowledgeBatch(ctx, tenantID, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
foundSet := make(map[string]bool)
|
||||
for _, k := range ownList {
|
||||
if k != nil {
|
||||
foundSet[k.ID] = true
|
||||
}
|
||||
}
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return ownList, nil
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
return ownList, nil
|
||||
}
|
||||
for _, id := range ids {
|
||||
if foundSet[id] {
|
||||
continue
|
||||
}
|
||||
k, err := s.repo.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil || !hasPermission {
|
||||
continue
|
||||
}
|
||||
foundSet[k.ID] = true
|
||||
ownList = append(ownList, k)
|
||||
}
|
||||
return ownList, nil
|
||||
}
|
||||
|
||||
// calculateFileHash calculates MD5 hash of a file
|
||||
func calculateFileHash(file *multipart.FileHeader) (string, error) {
|
||||
f, err := file.Open()
|
||||
@@ -2677,8 +2729,35 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if this is a shared knowledge base access
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
|
||||
effectiveTenantID := tenantID
|
||||
|
||||
// If the kb belongs to a different tenant, check for shared access
|
||||
if kb.TenantID != tenantID {
|
||||
// Get user ID from context
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
userID := userIDVal.(string)
|
||||
|
||||
// Check if user has at least viewer permission through organization sharing
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if err != nil || !hasPermission {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
|
||||
// Use the source tenant ID for data access
|
||||
sourceTenantID, err := s.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
effectiveTenantID = sourceTenantID
|
||||
}
|
||||
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, effectiveTenantID, kb.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2689,7 +2768,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
// Convert tagSeqID to tagID (UUID)
|
||||
var tagID string
|
||||
if tagSeqID > 0 {
|
||||
tag, err := s.tagRepo.GetBySeqID(ctx, tenantID, tagSeqID)
|
||||
tag, err := s.tagRepo.GetBySeqID(ctx, effectiveTenantID, tagSeqID)
|
||||
if err != nil {
|
||||
return nil, werrors.NewNotFoundError("标签不存在")
|
||||
}
|
||||
@@ -2698,7 +2777,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
|
||||
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
|
||||
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
|
||||
ctx, tenantID, faqKnowledge.ID, page, chunkType, tagID, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
|
||||
ctx, effectiveTenantID, faqKnowledge.ID, page, chunkType, tagID, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -2718,7 +2797,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
}
|
||||
}
|
||||
if len(tagIDs) > 0 {
|
||||
tags, err := s.tagRepo.GetByIDs(ctx, tenantID, tagIDs)
|
||||
tags, err := s.tagRepo.GetByIDs(ctx, effectiveTenantID, tagIDs)
|
||||
if err == nil {
|
||||
for _, tag := range tags {
|
||||
tagNameMap[tag.ID] = tag.Name
|
||||
@@ -4562,7 +4641,14 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
tenantIDVal := ctx.Value(types.TenantIDContextKey)
|
||||
if tenantIDVal == nil {
|
||||
return werrors.NewUnauthorizedError("tenant ID not found in context")
|
||||
}
|
||||
tenantID, ok := tenantIDVal.(uint64)
|
||||
if !ok {
|
||||
return werrors.NewUnauthorizedError("invalid tenant ID in context")
|
||||
}
|
||||
|
||||
// Get all knowledge items in batch
|
||||
knowledgeIDs := make([]string, 0, len(updates))
|
||||
@@ -7456,14 +7542,47 @@ func (s *knowledgeService) getOrCreateTagInTarget(
|
||||
return newTag.ID
|
||||
}
|
||||
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant and shared knowledge bases.
|
||||
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
|
||||
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, false, werrors.NewUnauthorizedError("Tenant ID not found in context")
|
||||
}
|
||||
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit, fileTypes)
|
||||
|
||||
scopes := make([]types.KnowledgeSearchScope, 0)
|
||||
|
||||
// Own tenant: document-type knowledge bases
|
||||
ownKBs, err := s.kbService.ListKnowledgeBases(ctx)
|
||||
if err == nil {
|
||||
for _, kb := range ownKBs {
|
||||
if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument {
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: tenantID, KBID: kb.ID})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared knowledge bases (document type only)
|
||||
if userIDVal := ctx.Value(types.UserIDContextKey); userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err == nil {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && info.KnowledgeBase.Type == types.KnowledgeBaseTypeDocument {
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{
|
||||
TenantID: info.SourceTenantID,
|
||||
KBID: info.KnowledgeBase.ID,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
}
|
||||
|
||||
// ProcessKnowledgeListDelete handles Asynq knowledge list delete tasks
|
||||
|
||||
@@ -25,6 +25,8 @@ type knowledgeBaseService struct {
|
||||
repo interfaces.KnowledgeBaseRepository
|
||||
kgRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
shareRepo interfaces.KBShareRepository
|
||||
kbShareService interfaces.KBShareService
|
||||
modelService interfaces.ModelService
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
tenantRepo interfaces.TenantRepository
|
||||
@@ -37,6 +39,8 @@ type knowledgeBaseService struct {
|
||||
func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
kgRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
shareRepo interfaces.KBShareRepository,
|
||||
kbShareService interfaces.KBShareService,
|
||||
modelService interfaces.ModelService,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
@@ -48,6 +52,8 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
repo: repo,
|
||||
kgRepo: kgRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
shareRepo: shareRepo,
|
||||
kbShareService: kbShareService,
|
||||
modelService: modelService,
|
||||
retrieveEngine: retrieveEngine,
|
||||
tenantRepo: tenantRepo,
|
||||
@@ -113,6 +119,26 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id stri
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBaseByIDOnly retrieves knowledge base by ID without tenant filter
|
||||
// Used for cross-tenant shared KB access where permission is checked elsewhere
|
||||
func (s *knowledgeBaseService) GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
return nil, errors.New("knowledge base ID cannot be empty")
|
||||
}
|
||||
|
||||
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
kb.EnsureDefaults()
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBases returns all knowledge bases for a tenant
|
||||
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
@@ -241,6 +267,11 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
|
||||
return err
|
||||
}
|
||||
|
||||
// Step 1b: Remove all organization shares for this KB so org settings no longer show them
|
||||
if delErr := s.shareRepo.DeleteByKnowledgeBaseID(ctx, id); delErr != nil {
|
||||
logger.Warnf(ctx, "Failed to delete KB shares for knowledge base %s: %v", id, delErr)
|
||||
}
|
||||
|
||||
// Step 2: Enqueue async task for heavy cleanup operations
|
||||
payload := types.KBDeletePayload{
|
||||
TenantID: tenantID,
|
||||
@@ -493,6 +524,7 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
logger.Infof(ctx, "Hybrid search parameters, knowledge base ID: %s, query text: %s", id, params.QueryText)
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
currentTenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
// Create a composite retrieval engine with tenant's configured retrievers
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
@@ -520,7 +552,16 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
|
||||
|
||||
logger.Infof(ctx, "Getting embedding model, model ID: %s", kb.EmbeddingModelID)
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
|
||||
// Check if this is a cross-tenant shared knowledge base
|
||||
// For shared KB, we must use the source tenant's embedding model to ensure vector compatibility
|
||||
if kb.TenantID != currentTenantID {
|
||||
logger.Infof(ctx, "Cross-tenant knowledge base detected, using source tenant's embedding model. KB tenant: %d, current tenant: %d", kb.TenantID, currentTenantID)
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModelForTenant(ctx, kb.EmbeddingModelID, kb.TenantID)
|
||||
} else {
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get embedding model, model ID: %s, error: %v", kb.EmbeddingModelID, err)
|
||||
return nil, err
|
||||
@@ -1016,16 +1057,16 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
||||
chunkMatchedContents[chunk.ChunkID] = chunk.Content
|
||||
}
|
||||
|
||||
// Batch fetch knowledge data
|
||||
// Batch fetch knowledge data (include shared KB so cross-tenant retrieval works)
|
||||
logger.Infof(ctx, "Fetching knowledge data for %d IDs", len(knowledgeIDs))
|
||||
knowledgeMap, err := s.fetchKnowledgeData(ctx, tenantID, knowledgeIDs)
|
||||
knowledgeMap, err := s.fetchKnowledgeDataWithShared(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Batch fetch all chunks in one go
|
||||
// Batch fetch chunks (include shared KB chunks: first by tenant, then by ID-only for missing with permission check)
|
||||
logger.Infof(ctx, "Fetching chunk data for %d IDs", len(chunkIDs))
|
||||
allChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
allChunks, err := s.listChunksByIDWithShared(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
@@ -1077,10 +1118,10 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch all additional chunks in one go if needed
|
||||
// Fetch all additional chunks in one go if needed (include shared KB)
|
||||
if len(additionalChunkIDs) > 0 {
|
||||
logger.Infof(ctx, "Fetching %d additional chunks", len(additionalChunkIDs))
|
||||
additionalChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, additionalChunkIDs)
|
||||
additionalChunks, err := s.listChunksByIDWithShared(ctx, tenantID, additionalChunkIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch some additional chunks: %v", err)
|
||||
// Continue with what we have
|
||||
@@ -1226,3 +1267,136 @@ func (s *knowledgeBaseService) fetchKnowledgeData(ctx context.Context,
|
||||
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
// fetchKnowledgeDataWithShared gets knowledge data in batch, including knowledge from shared KBs the user has access to.
|
||||
func (s *knowledgeBaseService) fetchKnowledgeDataWithShared(ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeIDs []string,
|
||||
) (map[string]*types.Knowledge, error) {
|
||||
knowledges, err := s.kgRepo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"knowledge_ids": knowledgeIDs,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
knowledgeMap := make(map[string]*types.Knowledge, len(knowledges))
|
||||
for _, k := range knowledges {
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
|
||||
// Count how many IDs are missing (not found in current tenant)
|
||||
var missingIDs []string
|
||||
for _, id := range knowledgeIDs {
|
||||
if knowledgeMap[id] == nil {
|
||||
missingIDs = append(missingIDs, id)
|
||||
}
|
||||
}
|
||||
if len(missingIDs) == 0 {
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] %d knowledge IDs not found in current tenant, attempting shared KB lookup", len(missingIDs))
|
||||
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
logger.Warnf(ctx, "[fetchKnowledgeDataWithShared] userID not found in context, skipping shared KB lookup")
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
logger.Warnf(ctx, "[fetchKnowledgeDataWithShared] userID is empty, skipping shared KB lookup")
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] Looking up %d missing knowledge IDs with userID=%s", len(missingIDs), userID)
|
||||
for _, id := range missingIDs {
|
||||
k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Knowledge %s not found or has no KB", id)
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Permission check error for KB %s: %v", k.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] No permission for KB %s", k.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Found shared knowledge %s in KB %s", id, k.KnowledgeBaseID)
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] After shared lookup, total knowledge found: %d", len(knowledgeMap))
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
// listChunksByIDWithShared fetches chunks by IDs, including chunks from shared KBs the user has access to.
|
||||
func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context,
|
||||
tenantID uint64,
|
||||
chunkIDs []string,
|
||||
) ([]*types.Chunk, error) {
|
||||
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
foundSet := make(map[string]bool)
|
||||
for _, c := range chunks {
|
||||
if c != nil {
|
||||
foundSet[c.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
var missing []string
|
||||
for _, id := range chunkIDs {
|
||||
if !foundSet[id] {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return chunks, nil
|
||||
}
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] %d chunks not found in current tenant, attempting shared KB lookup", len(missing))
|
||||
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] userID not found in context, skipping shared KB lookup")
|
||||
return chunks, nil
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] userID is empty, skipping shared KB lookup")
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] Looking up %d missing chunks with userID=%s", len(missing), userID)
|
||||
crossChunks, err := s.chunkRepo.ListChunksByIDOnly(ctx, missing)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] Failed to fetch chunks by ID only: %v", err)
|
||||
return chunks, nil
|
||||
}
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] Found %d chunks without tenant filter", len(crossChunks))
|
||||
|
||||
for _, c := range crossChunks {
|
||||
if c == nil || c.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, c.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[listChunksByIDWithShared] Permission check error for KB %s: %v", c.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.Debugf(ctx, "[listChunksByIDWithShared] No permission for KB %s", c.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
chunks = append(chunks, c)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] After shared lookup, total chunks: %d", len(chunks))
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
@@ -268,6 +268,62 @@ func (s *modelService) GetEmbeddingModel(ctx context.Context, modelId string) (e
|
||||
return embedder, nil
|
||||
}
|
||||
|
||||
// GetEmbeddingModelForTenant retrieves and initializes an embedding model for a specific tenant
|
||||
// This is used for cross-tenant knowledge base sharing where the embedding model from
|
||||
// the source tenant must be used to ensure vector compatibility
|
||||
func (s *modelService) GetEmbeddingModelForTenant(ctx context.Context, modelId string, tenantID uint64) (embedding.Embedder, error) {
|
||||
// Check if model ID is empty
|
||||
if modelId == "" {
|
||||
logger.Error(ctx, "Model ID is empty")
|
||||
return nil, errors.New("model ID cannot be empty")
|
||||
}
|
||||
|
||||
// Fetch model from repository using the specified tenant ID
|
||||
model, err := s.repo.GetByID(ctx, tenantID, modelId)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": modelId,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if model == nil {
|
||||
logger.Error(ctx, "Model not found for specified tenant")
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
|
||||
if model.Status != types.ModelStatusActive {
|
||||
logger.Errorf(ctx, "Model is not active, status: %s", model.Status)
|
||||
return nil, errors.New("model is not active")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Getting cross-tenant embedding model: %s, source: %s, tenant: %d", model.Name, model.Source, tenantID)
|
||||
|
||||
// Initialize the embedder with model configuration
|
||||
embedder, err := embedding.NewEmbedder(embedding.Config{
|
||||
Source: model.Source,
|
||||
BaseURL: model.Parameters.BaseURL,
|
||||
APIKey: model.Parameters.APIKey,
|
||||
ModelID: model.ID,
|
||||
ModelName: model.Name,
|
||||
Dimensions: model.Parameters.EmbeddingParameters.Dimension,
|
||||
TruncatePromptTokens: model.Parameters.EmbeddingParameters.TruncatePromptTokens,
|
||||
Provider: model.Parameters.Provider,
|
||||
}, s.pooler, s.ollamaService)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": model.ID,
|
||||
"model_name": model.Name,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Cross-tenant embedding model initialized successfully")
|
||||
return embedder, nil
|
||||
}
|
||||
|
||||
// GetRerankModel retrieves and initializes a reranking model instance
|
||||
// Takes a model ID and returns a Reranker interface implementation
|
||||
func (s *modelService) GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error) {
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Default invite code validity in days; allowed values: 0 (never), 1, 7, 30
|
||||
const DefaultInviteCodeValidityDays = 7
|
||||
|
||||
// ValidInviteCodeValidityDays are the allowed values for invite_code_validity_days
|
||||
var ValidInviteCodeValidityDays = map[int]bool{0: true, 1: true, 7: true, 30: true}
|
||||
|
||||
var (
|
||||
ErrOrgNotFound = errors.New("organization not found")
|
||||
ErrOrgPermissionDenied = errors.New("permission denied for this organization")
|
||||
ErrCannotRemoveOwner = errors.New("cannot remove organization owner")
|
||||
ErrCannotChangeOwnerRole = errors.New("cannot change organization owner role")
|
||||
ErrUserNotInOrg = errors.New("user is not a member of this organization")
|
||||
ErrInvalidRole = errors.New("invalid role")
|
||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||
ErrInvalidValidityDays = errors.New("invite_code_validity_days must be 0, 1, 7, or 30")
|
||||
)
|
||||
|
||||
// organizationService implements OrganizationService interface
|
||||
type organizationService struct {
|
||||
orgRepo interfaces.OrganizationRepository
|
||||
userRepo interfaces.UserRepository
|
||||
shareRepo interfaces.KBShareRepository
|
||||
}
|
||||
|
||||
// NewOrganizationService creates a new organization service
|
||||
func NewOrganizationService(orgRepo interfaces.OrganizationRepository, userRepo interfaces.UserRepository, shareRepo interfaces.KBShareRepository) interfaces.OrganizationService {
|
||||
return &organizationService{
|
||||
orgRepo: orgRepo,
|
||||
userRepo: userRepo,
|
||||
shareRepo: shareRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// resolveInviteExpiry returns expiresAt for the given validity days (0 = never, nil expiresAt).
|
||||
func resolveInviteExpiry(validityDays int, now time.Time) *time.Time {
|
||||
if validityDays == 0 {
|
||||
return nil
|
||||
}
|
||||
t := now.AddDate(0, 0, validityDays)
|
||||
return &t
|
||||
}
|
||||
|
||||
// CreateOrganization creates a new organization
|
||||
func (s *organizationService) CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error) {
|
||||
logger.Infof(ctx, "Creating organization: %s by user: %s", req.Name, userID)
|
||||
|
||||
validityDays := DefaultInviteCodeValidityDays
|
||||
if req.InviteCodeValidityDays != nil {
|
||||
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
|
||||
return nil, ErrInvalidValidityDays
|
||||
}
|
||||
validityDays = *req.InviteCodeValidityDays
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
org := &types.Organization{
|
||||
ID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Avatar: strings.TrimSpace(req.Avatar),
|
||||
OwnerID: userID,
|
||||
InviteCode: generateInviteCode(),
|
||||
InviteCodeExpiresAt: resolveInviteExpiry(validityDays, now),
|
||||
InviteCodeValidityDays: validityDays,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if err := s.orgRepo.Create(ctx, org); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create organization: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add the creator as admin member
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: org.ID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: types.OrgRoleAdmin,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
||||
logger.Errorf(ctx, "Failed to add creator as member: %v", err)
|
||||
// Rollback organization creation
|
||||
_ = s.orgRepo.Delete(ctx, org.ID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Organization created successfully: %s", org.ID)
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// GetOrganization gets an organization by ID
|
||||
func (s *organizationService) GetOrganization(ctx context.Context, id string) (*types.Organization, error) {
|
||||
org, err := s.orgRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// GetOrganizationByInviteCode gets an organization by invite code
|
||||
func (s *organizationService) GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) {
|
||||
org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrInviteCodeNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
if errors.Is(err, repository.ErrInviteCodeExpired) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// ListUserOrganizations lists all organizations that a user belongs to
|
||||
func (s *organizationService) ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error) {
|
||||
return s.orgRepo.ListByUserID(ctx, userID)
|
||||
}
|
||||
|
||||
// UpdateOrganization updates an organization
|
||||
func (s *organizationService) UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error) {
|
||||
// Check if user is admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, id, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isAdmin {
|
||||
return nil, ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
org, err := s.orgRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
org.Name = *req.Name
|
||||
}
|
||||
if req.Description != nil {
|
||||
org.Description = *req.Description
|
||||
}
|
||||
if req.Avatar != nil {
|
||||
org.Avatar = strings.TrimSpace(*req.Avatar)
|
||||
}
|
||||
if req.RequireApproval != nil {
|
||||
org.RequireApproval = *req.RequireApproval
|
||||
}
|
||||
if req.InviteCodeValidityDays != nil {
|
||||
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
|
||||
return nil, ErrInvalidValidityDays
|
||||
}
|
||||
org.InviteCodeValidityDays = *req.InviteCodeValidityDays
|
||||
}
|
||||
org.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.orgRepo.Update(ctx, org); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// DeleteOrganization deletes an organization
|
||||
func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string) error {
|
||||
org, err := s.orgRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Only owner can delete organization
|
||||
if org.OwnerID != userID {
|
||||
return ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
// Remove all KB shares for this org so members no longer see associated knowledge bases
|
||||
if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err)
|
||||
}
|
||||
|
||||
return s.orgRepo.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// AddMember adds a member to an organization
|
||||
func (s *organizationService) AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error {
|
||||
if !role.IsValid() {
|
||||
return ErrInvalidRole
|
||||
}
|
||||
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: orgID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: role,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
return s.orgRepo.AddMember(ctx, member)
|
||||
}
|
||||
|
||||
// RemoveMember removes a member from an organization.
|
||||
// When operatorUserID == memberUserID, it is "leave" (self-removal) and does not require admin.
|
||||
// When removing another member, operator must be admin.
|
||||
func (s *organizationService) RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error {
|
||||
// Check if trying to remove owner
|
||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if org.OwnerID == memberUserID {
|
||||
return ErrCannotRemoveOwner
|
||||
}
|
||||
|
||||
// Self-removal (leave): allow any member to leave
|
||||
if operatorUserID == memberUserID {
|
||||
return s.orgRepo.RemoveMember(ctx, orgID, memberUserID)
|
||||
}
|
||||
|
||||
// Removing another member: require operator to be admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isAdmin {
|
||||
return ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
return s.orgRepo.RemoveMember(ctx, orgID, memberUserID)
|
||||
}
|
||||
|
||||
// UpdateMemberRole updates a member's role
|
||||
func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error {
|
||||
if !role.IsValid() {
|
||||
return ErrInvalidRole
|
||||
}
|
||||
|
||||
// Check if operator is admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isAdmin {
|
||||
return ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
// Check if trying to change owner's role
|
||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if org.OwnerID == memberUserID {
|
||||
return ErrCannotChangeOwnerRole
|
||||
}
|
||||
|
||||
return s.orgRepo.UpdateMemberRole(ctx, orgID, memberUserID, role)
|
||||
}
|
||||
|
||||
// ListMembers lists all members of an organization
|
||||
func (s *organizationService) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) {
|
||||
return s.orgRepo.ListMembers(ctx, orgID)
|
||||
}
|
||||
|
||||
// GetMember gets a specific member of an organization
|
||||
func (s *organizationService) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
// GenerateInviteCode generates a new invite code for an organization
|
||||
func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error) {
|
||||
// Check if user is admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !isAdmin {
|
||||
return "", ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
validityDays := org.InviteCodeValidityDays
|
||||
if validityDays != 0 && !ValidInviteCodeValidityDays[validityDays] {
|
||||
validityDays = DefaultInviteCodeValidityDays
|
||||
}
|
||||
// 0 = never expire (expiresAt nil); 1/7/30 = that many days
|
||||
|
||||
inviteCode := generateInviteCode()
|
||||
now := time.Now()
|
||||
expiresAt := resolveInviteExpiry(validityDays, now)
|
||||
if err := s.orgRepo.UpdateInviteCode(ctx, orgID, inviteCode, expiresAt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return inviteCode, nil
|
||||
}
|
||||
|
||||
// JoinByInviteCode allows a user to join an organization via invite code
|
||||
func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error) {
|
||||
org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrInviteCodeNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
if errors.Is(err, repository.ErrInviteCodeExpired) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if user is already a member
|
||||
_, err = s.orgRepo.GetMember(ctx, org.ID, userID)
|
||||
if err == nil {
|
||||
// User is already a member, just return the organization
|
||||
return org, nil
|
||||
}
|
||||
if !errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add user as viewer by default
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: org.ID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: types.OrgRoleViewer,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "User %s joined organization %s via invite code", userID, org.ID)
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// IsOrgAdmin checks if a user is an admin of an organization
|
||||
func (s *organizationService) IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return member.Role == types.OrgRoleAdmin, nil
|
||||
}
|
||||
|
||||
// GetUserRoleInOrg gets a user's role in an organization
|
||||
func (s *organizationService) GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return "", ErrUserNotInOrg
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return member.Role, nil
|
||||
}
|
||||
|
||||
// generateInviteCode generates a random 16-character invite code
|
||||
func generateInviteCode() string {
|
||||
bytes := make([]byte, 8)
|
||||
_, _ = rand.Read(bytes)
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// ----------------
|
||||
// Join Requests
|
||||
// ----------------
|
||||
|
||||
var (
|
||||
ErrPendingRequestExists = errors.New("pending request already exists")
|
||||
ErrJoinRequestNotFound = errors.New("join request not found")
|
||||
ErrCannotUpgradeToSameRole = errors.New("cannot request upgrade to same or lower role")
|
||||
ErrAlreadyAdmin = errors.New("user is already an admin")
|
||||
)
|
||||
|
||||
// SubmitJoinRequest submits a request to join an organization
|
||||
func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error) {
|
||||
logger.Infof(ctx, "User %s submitting join request for organization %s", userID, orgID)
|
||||
|
||||
// Check if there's already a pending join request
|
||||
existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeJoin)
|
||||
if err == nil && existing != nil {
|
||||
return nil, ErrPendingRequestExists
|
||||
}
|
||||
|
||||
// Default to viewer if role is empty or invalid
|
||||
if requestedRole == "" || !requestedRole.IsValid() {
|
||||
requestedRole = types.OrgRoleViewer
|
||||
}
|
||||
|
||||
request := &types.OrganizationJoinRequest{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: orgID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
RequestType: types.JoinRequestTypeJoin,
|
||||
RequestedRole: requestedRole,
|
||||
Status: types.JoinRequestStatusPending,
|
||||
Message: message,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.CreateJoinRequest(ctx, request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Join request %s created for organization %s by user %s", request.ID, orgID, userID)
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// ListJoinRequests lists all join requests for an organization
|
||||
func (s *organizationService) ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error) {
|
||||
return s.orgRepo.ListJoinRequests(ctx, orgID, "")
|
||||
}
|
||||
|
||||
// CountPendingJoinRequests returns the number of pending join requests for an organization
|
||||
func (s *organizationService) CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error) {
|
||||
return s.orgRepo.CountJoinRequests(ctx, orgID, types.JoinRequestStatusPending)
|
||||
}
|
||||
|
||||
// ReviewJoinRequest reviews a join request or upgrade request (approve or reject).
|
||||
// When approving, assignRole overrides the applicant's requested role if set; otherwise uses request.RequestedRole or viewer.
|
||||
func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error {
|
||||
request, err := s.orgRepo.GetJoinRequestByID(ctx, requestID)
|
||||
if err != nil {
|
||||
return ErrJoinRequestNotFound
|
||||
}
|
||||
if request.OrganizationID != orgID {
|
||||
return ErrJoinRequestNotFound
|
||||
}
|
||||
|
||||
if request.Status != types.JoinRequestStatusPending {
|
||||
return errors.New("request has already been reviewed")
|
||||
}
|
||||
|
||||
var status types.JoinRequestStatus
|
||||
if approved {
|
||||
status = types.JoinRequestStatusApproved
|
||||
|
||||
// Role to assign: admin override > applicant's requested role > viewer
|
||||
role := types.OrgRoleViewer
|
||||
if assignRole != nil && assignRole.IsValid() {
|
||||
role = *assignRole
|
||||
} else if request.RequestedRole != "" && request.RequestedRole.IsValid() {
|
||||
role = request.RequestedRole
|
||||
}
|
||||
|
||||
// Handle based on request type
|
||||
if request.RequestType == types.JoinRequestTypeUpgrade {
|
||||
// Upgrade: update existing member's role
|
||||
if err := s.orgRepo.UpdateMemberRole(ctx, request.OrganizationID, request.UserID, role); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "Upgrade request %s approved, user %s role updated to %s in organization %s", requestID, request.UserID, role, request.OrganizationID)
|
||||
} else {
|
||||
// Join: add new member
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: request.OrganizationID,
|
||||
UserID: request.UserID,
|
||||
TenantID: request.TenantID,
|
||||
Role: role,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "Join request %s approved, user %s added to organization %s with role %s", requestID, request.UserID, request.OrganizationID, role)
|
||||
}
|
||||
} else {
|
||||
status = types.JoinRequestStatusRejected
|
||||
logger.Infof(ctx, "Request %s rejected for user %s", requestID, request.UserID)
|
||||
}
|
||||
|
||||
return s.orgRepo.UpdateJoinRequestStatus(ctx, requestID, status, reviewerID, message)
|
||||
}
|
||||
|
||||
// RequestRoleUpgrade submits a request to upgrade role in an organization
|
||||
func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error) {
|
||||
logger.Infof(ctx, "User %s submitting role upgrade request for organization %s to role %s", userID, orgID, requestedRole)
|
||||
|
||||
// Check if user is a member
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Validate the requested role
|
||||
if !requestedRole.IsValid() {
|
||||
return nil, ErrInvalidRole
|
||||
}
|
||||
|
||||
// Check if already admin
|
||||
if member.Role == types.OrgRoleAdmin {
|
||||
return nil, ErrAlreadyAdmin
|
||||
}
|
||||
|
||||
// Check if requested role is higher than current role
|
||||
if !requestedRole.HasPermission(member.Role) || requestedRole == member.Role {
|
||||
return nil, ErrCannotUpgradeToSameRole
|
||||
}
|
||||
|
||||
// Check if there's already a pending upgrade request
|
||||
existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade)
|
||||
if err == nil && existing != nil {
|
||||
return nil, ErrPendingRequestExists
|
||||
}
|
||||
|
||||
request := &types.OrganizationJoinRequest{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: orgID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
RequestType: types.JoinRequestTypeUpgrade,
|
||||
PrevRole: member.Role,
|
||||
RequestedRole: requestedRole,
|
||||
Status: types.JoinRequestStatusPending,
|
||||
Message: message,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.CreateJoinRequest(ctx, request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Role upgrade request %s created for organization %s by user %s (from %s to %s)", request.ID, orgID, userID, member.Role, requestedRole)
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// GetPendingUpgradeRequest gets a pending upgrade request for a user in an organization
|
||||
func (s *organizationService) GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) {
|
||||
request, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrJoinRequestNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
@@ -43,6 +43,7 @@ type sessionService struct {
|
||||
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
|
||||
chunkService interfaces.ChunkService // Service for chunk operations
|
||||
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
|
||||
kbShareService interfaces.KBShareService // Service for KB sharing operations
|
||||
}
|
||||
|
||||
// NewSessionService creates a new session service instance with all required dependencies
|
||||
@@ -58,6 +59,7 @@ func NewSessionService(cfg *config.Config,
|
||||
agentService interfaces.AgentService,
|
||||
sessionStorage llmcontext.ContextStorage,
|
||||
webSearchStateRepo interfaces.WebSearchStateService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) interfaces.SessionService {
|
||||
return &sessionService{
|
||||
cfg: cfg,
|
||||
@@ -72,6 +74,7 @@ func NewSessionService(cfg *config.Config,
|
||||
agentService: agentService,
|
||||
sessionStorage: sessionStorage,
|
||||
webSearchStateRepo: webSearchStateRepo,
|
||||
kbShareService: kbShareService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -301,7 +304,7 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
chat.Message{Role: "system", Content: s.cfg.Conversation.GenerateSessionTitlePrompt},
|
||||
)
|
||||
chatMessages = append(chatMessages,
|
||||
chat.Message{Role: "user", Content: message.Content + " /no_think"},
|
||||
chat.Message{Role: "user", Content: message.Content},
|
||||
)
|
||||
|
||||
// Call model to generate title
|
||||
@@ -729,10 +732,10 @@ func (s *sessionService) selectChatModelID(
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) (string, error) {
|
||||
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs
|
||||
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs (include shared KB files)
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge batch for model selection: %v", err)
|
||||
} else {
|
||||
@@ -818,16 +821,38 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
// Get own knowledge bases
|
||||
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list all knowledge bases: %v", err)
|
||||
return nil
|
||||
}
|
||||
kbIDSet := make(map[string]bool)
|
||||
kbIDs := make([]string, 0, len(allKBs))
|
||||
for _, kb := range allKBs {
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
kbIDSet[kb.ID] = true
|
||||
}
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases", len(kbIDs))
|
||||
|
||||
// Also include shared knowledge bases the user has access to
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||
} else {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases (own + shared)", len(kbIDs))
|
||||
return kbIDs
|
||||
case "selected":
|
||||
logger.Infof(ctx, "KBSelectionMode=selected: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
|
||||
@@ -901,7 +926,7 @@ func (s *sessionService) configureSkillsFromAgent(
|
||||
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
|
||||
// This is called once at the request entry point to avoid repeated queries later in the pipeline
|
||||
// Logic:
|
||||
// - For each knowledgeBaseID: create a SearchTargetTypeKnowledgeBase target
|
||||
// - For each knowledgeBaseID: create a SearchTargetTypeKnowledgeBase target with correct TenantID
|
||||
// - For each knowledgeID: find its knowledgeBaseID, if the KB is already in the list, skip (covered by full KB search)
|
||||
// otherwise create a SearchTargetTypeKnowledge target grouped by KB
|
||||
func (s *sessionService) buildSearchTargets(
|
||||
@@ -912,30 +937,69 @@ func (s *sessionService) buildSearchTargets(
|
||||
) (types.SearchTargets, error) {
|
||||
var targets types.SearchTargets
|
||||
|
||||
// Build a map from KB ID to TenantID for all KBs we need to process
|
||||
kbTenantMap := make(map[string]uint64)
|
||||
|
||||
// Track which KBs are fully searched
|
||||
fullKBSet := make(map[string]bool)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
fullKBSet[kbID] = true
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kbID,
|
||||
})
|
||||
|
||||
// First pass: process knowledge base IDs and get their tenant info
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
// Get KB details to determine their actual tenant IDs (may include shared KBs)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
fullKBSet[kbID] = true
|
||||
// Try to get KB info - first from current tenant, then from shared access
|
||||
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
// May be a shared KB from another tenant - use kbShareService to check
|
||||
if s.kbShareService != nil {
|
||||
userID, _ := ctx.Value(types.UserIDContextKey).(string)
|
||||
if userID != "" {
|
||||
// Check if user has at least viewer permission on this KB
|
||||
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if hasAccess {
|
||||
// Get KB info without tenant filter
|
||||
kbInfo, err := s.knowledgeBaseService.GetKnowledgeBaseByIDOnly(ctx, kbID)
|
||||
if err == nil && kbInfo != nil {
|
||||
kbTenantMap[kbID] = kbInfo.TenantID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if kb != nil {
|
||||
kbTenantMap[kbID] = kb.TenantID
|
||||
}
|
||||
// Default to current tenant if we couldn't determine the actual tenant
|
||||
if kbTenantMap[kbID] == 0 {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenantMap[kbID],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Process individual knowledge IDs
|
||||
// Process individual knowledge IDs (include shared KB files the user has access to)
|
||||
if len(knowledgeIDs) > 0 {
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge batch for search targets: %v", err)
|
||||
return targets, nil // Return what we have, don't fail
|
||||
}
|
||||
|
||||
// Group knowledge IDs by their KB, excluding those already covered by full KB search
|
||||
// Also track KB tenant IDs from knowledge items
|
||||
kbToKnowledgeIDs := make(map[string][]string)
|
||||
for _, k := range knowledgeList {
|
||||
if k == nil || k.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
// Track KB -> TenantID mapping from knowledge items
|
||||
if kbTenantMap[k.KnowledgeBaseID] == 0 {
|
||||
kbTenantMap[k.KnowledgeBaseID] = k.TenantID
|
||||
}
|
||||
// Skip if this KB is already fully searched
|
||||
if fullKBSet[k.KnowledgeBaseID] {
|
||||
continue
|
||||
@@ -945,16 +1009,21 @@ func (s *sessionService) buildSearchTargets(
|
||||
|
||||
// Create SearchTargetTypeKnowledge targets for each KB with specific files
|
||||
for kbID, kidList := range kbToKnowledgeIDs {
|
||||
kbTenant := kbTenantMap[kbID]
|
||||
if kbTenant == 0 {
|
||||
kbTenant = tenantID // fallback
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledge,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenant,
|
||||
KnowledgeIDs: kidList,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial KB",
|
||||
len(targets), len(knowledgeBaseIDs), len(targets)-len(knowledgeBaseIDs))
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial KB, kbTenantMap=%v",
|
||||
len(targets), len(knowledgeBaseIDs), len(targets)-len(knowledgeBaseIDs), kbTenantMap)
|
||||
|
||||
return targets, nil
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ type knowledgeTagService struct {
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
modelService interfaces.ModelService
|
||||
task *asynq.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// NewKnowledgeTagService creates a new tag service.
|
||||
@@ -37,6 +38,7 @@ func NewKnowledgeTagService(
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
modelService interfaces.ModelService,
|
||||
task *asynq.Client,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) (interfaces.KnowledgeTagService, error) {
|
||||
return &knowledgeTagService{
|
||||
kbService: kbService,
|
||||
@@ -46,6 +48,7 @@ func NewKnowledgeTagService(
|
||||
retrieveEngine: retrieveEngine,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
kbShareService: kbShareService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -63,14 +66,33 @@ func (s *knowledgeTagService) ListTags(
|
||||
page = &types.Pagination{}
|
||||
}
|
||||
keyword = strings.TrimSpace(keyword)
|
||||
// Ensure KB exists and belongs to current tenant
|
||||
// Ensure KB exists
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantID := kb.TenantID
|
||||
|
||||
tags, total, err := s.repo.ListByKB(ctx, tenantID, kbID, page, keyword)
|
||||
// Check access permission
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if kb.TenantID != tenantID {
|
||||
// Get user ID from context
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
userID := userIDVal.(string)
|
||||
|
||||
// Check if user has at least viewer permission through organization sharing
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if err != nil || !hasPermission {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
}
|
||||
|
||||
// Use kb's tenant ID for data access
|
||||
effectiveTenantID := kb.TenantID
|
||||
|
||||
tags, total, err := s.repo.ListByKB(ctx, effectiveTenantID, kbID, page, keyword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -88,7 +110,7 @@ func (s *knowledgeTagService) ListTags(
|
||||
}
|
||||
|
||||
// Batch query all reference counts in 2 SQL queries instead of 2*N
|
||||
countsMap, err := s.repo.BatchCountReferences(ctx, tenantID, kbID, tagIDs)
|
||||
countsMap, err := s.repo.BatchCountReferences(ctx, effectiveTenantID, kbID, tagIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
|
||||
@@ -426,3 +426,11 @@ func (s *userService) GetCurrentUser(ctx context.Context) (*types.User, error) {
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// SearchUsers searches users by username or email
|
||||
func (s *userService) SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error) {
|
||||
if query == "" {
|
||||
return []*types.User{}, nil
|
||||
}
|
||||
return s.userRepo.SearchUsers(ctx, query, limit)
|
||||
}
|
||||
|
||||
@@ -202,6 +202,9 @@ func formatPipelineLogValue(value interface{}) string {
|
||||
return strconv.Quote(truncatePipelineValue(v))
|
||||
case fmt.Stringer:
|
||||
return strconv.Quote(truncatePipelineValue(v.String()))
|
||||
case json.RawMessage:
|
||||
bytes, _ := v.MarshalJSON()
|
||||
return string(bytes)
|
||||
default:
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
|
||||
@@ -111,6 +111,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(neo4jRepo.NewNeo4jRepository))
|
||||
must(container.Provide(repository.NewMCPServiceRepository))
|
||||
must(container.Provide(repository.NewCustomAgentRepository))
|
||||
must(container.Provide(repository.NewOrganizationRepository))
|
||||
must(container.Provide(repository.NewKBShareRepository))
|
||||
must(container.Provide(service.NewWebSearchStateService))
|
||||
|
||||
// MCP manager for managing MCP client connections
|
||||
@@ -121,6 +123,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
logger.Debugf(ctx, "[Container] Registering business services...")
|
||||
must(container.Provide(service.NewTenantService))
|
||||
must(container.Provide(service.NewKnowledgeBaseService))
|
||||
must(container.Provide(service.NewOrganizationService))
|
||||
must(container.Provide(service.NewKBShareService)) // KBShareService must be registered before KnowledgeService and KnowledgeTagService
|
||||
must(container.Provide(service.NewKnowledgeService))
|
||||
must(container.Provide(service.NewChunkService))
|
||||
must(container.Provide(service.NewKnowledgeTagService))
|
||||
@@ -199,6 +203,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewCustomAgentHandler))
|
||||
must(container.Provide(service.NewSkillService))
|
||||
must(container.Provide(handler.NewSkillHandler))
|
||||
must(container.Provide(handler.NewOrganizationHandler))
|
||||
logger.Debugf(ctx, "[Container] HTTP handlers registered")
|
||||
|
||||
// Router configuration
|
||||
|
||||
+80
-78
@@ -1,6 +1,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
@@ -14,17 +15,48 @@ import (
|
||||
|
||||
// ChunkHandler defines HTTP handlers for chunk operations
|
||||
type ChunkHandler struct {
|
||||
service interfaces.ChunkService
|
||||
service interfaces.ChunkService
|
||||
kgService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// NewChunkHandler creates a new chunk handler
|
||||
func NewChunkHandler(service interfaces.ChunkService) *ChunkHandler {
|
||||
return &ChunkHandler{service: service}
|
||||
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService) *ChunkHandler {
|
||||
return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService}
|
||||
}
|
||||
|
||||
// effectiveCtxForKnowledge resolves knowledge by ID, validates KB access (owner or shared with required role), and returns context with effectiveTenantID for downstream service calls.
|
||||
func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID 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())
|
||||
|
||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("Knowledge not found")
|
||||
}
|
||||
if knowledge.TenantID == tenantID {
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
if !userExists || h.kbShareService == nil {
|
||||
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 !permission.HasPermission(requiredPermission) {
|
||||
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||
}
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly godoc
|
||||
// @Summary 通过ID获取分块
|
||||
// @Description 仅通过分块ID获取分块详情(不需要knowledge_id)
|
||||
// @Description 仅通过分块ID获取分块详情(不需要knowledge_id);支持共享知识库下的分块访问
|
||||
// @Tags 分块管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -46,18 +78,8 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieving chunk by ID, chunk ID: %s, tenant ID: %d", chunkID, tenantID)
|
||||
|
||||
// Get chunk by ID
|
||||
chunk, err := h.service.GetChunkByID(ctx, chunkID)
|
||||
// Get chunk by ID without tenant filter (chunk may belong to shared KB)
|
||||
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
||||
if err != nil {
|
||||
if err == service.ErrChunkNotFound {
|
||||
logger.Warnf(ctx, "Chunk not found, chunk ID: %s", chunkID)
|
||||
@@ -69,14 +91,9 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Validate tenant ID
|
||||
if chunk.TenantID != tenantID.(uint64) {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access chunk, chunk ID: %s, req tenant: %d, chunk tenant: %d",
|
||||
chunkID, tenantID.(uint64), chunk.TenantID,
|
||||
)
|
||||
c.Error(errors.NewForbiddenError("No permission to access this chunk"))
|
||||
_, err = h.effectiveCtxForKnowledge(c, chunk.KnowledgeID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -116,6 +133,12 @@ func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse pagination parameters
|
||||
var pagination types.Pagination
|
||||
if err := c.ShouldBindQuery(&pagination); err != nil {
|
||||
@@ -135,8 +158,8 @@ func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
|
||||
|
||||
chunkType := []types.ChunkType{types.ChunkTypeText}
|
||||
|
||||
// Use pagination for query
|
||||
result, err := h.service.ListPagedChunksByKnowledgeID(ctx, knowledgeID, &pagination, chunkType)
|
||||
// Use pagination for query (effCtx has effectiveTenantID for shared KB)
|
||||
result, err := h.service.ListPagedChunksByKnowledgeID(effCtx, knowledgeID, &pagination, chunkType)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
@@ -170,59 +193,46 @@ type UpdateChunkRequest struct {
|
||||
ImageInfo string `json:"image_info"`
|
||||
}
|
||||
|
||||
// validateAndGetChunk validates request parameters and retrieves the chunk
|
||||
// Returns chunk information, knowledge ID, and error
|
||||
func (h *ChunkHandler) validateAndGetChunk(c *gin.Context) (*types.Chunk, string, error) {
|
||||
// validateAndGetChunk validates request parameters and retrieves the chunk (supports shared KB via effectiveTenantID).
|
||||
// Returns chunk, knowledge ID, context with effectiveTenantID for downstream calls, and error.
|
||||
func (h *ChunkHandler) validateAndGetChunk(c *gin.Context) (*types.Chunk, string, context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Validate knowledge ID
|
||||
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
|
||||
if knowledgeID == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
return nil, "", errors.NewBadRequestError("Knowledge ID cannot be empty")
|
||||
return nil, "", nil, errors.NewBadRequestError("Knowledge ID cannot be empty")
|
||||
}
|
||||
|
||||
// Validate chunk ID
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Chunk ID is empty")
|
||||
return nil, knowledgeID, errors.NewBadRequestError("Chunk ID cannot be empty")
|
||||
return nil, knowledgeID, nil, errors.NewBadRequestError("Chunk ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, knowledgeID, errors.NewUnauthorizedError("Unauthorized")
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
return nil, knowledgeID, nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieving knowledge chunk information, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||
|
||||
// Get existing chunk
|
||||
chunk, err := h.service.GetChunkByID(ctx, id)
|
||||
chunk, err := h.service.GetChunkByID(effCtx, id)
|
||||
if err != nil {
|
||||
if err == service.ErrChunkNotFound {
|
||||
logger.Warnf(ctx, "Chunk not found, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||
return nil, knowledgeID, errors.NewNotFoundError("Chunk not found")
|
||||
return nil, knowledgeID, nil, errors.NewNotFoundError("Chunk not found")
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, knowledgeID, errors.NewInternalServerError(err.Error())
|
||||
return nil, knowledgeID, nil, errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
|
||||
// Validate tenant ID
|
||||
if chunk.TenantID != tenantID.(uint64) || chunk.KnowledgeID != knowledgeID {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access chunk, knowledge ID: %s, chunk ID: %s, req tenant: %d, chunk tenant: %d",
|
||||
knowledgeID,
|
||||
id,
|
||||
tenantID,
|
||||
chunk.TenantID,
|
||||
)
|
||||
return nil, knowledgeID, errors.NewForbiddenError("No permission to access this chunk")
|
||||
if chunk.KnowledgeID != knowledgeID {
|
||||
logger.Warnf(ctx, "Chunk does not belong to knowledge, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||
return nil, knowledgeID, nil, errors.NewForbiddenError("No permission to access this chunk")
|
||||
}
|
||||
|
||||
return chunk, knowledgeID, nil
|
||||
return chunk, knowledgeID, effCtx, nil
|
||||
}
|
||||
|
||||
// UpdateChunk godoc
|
||||
@@ -244,8 +254,7 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start updating knowledge chunk")
|
||||
|
||||
// Validate parameters and get chunk
|
||||
chunk, knowledgeID, err := h.validateAndGetChunk(c)
|
||||
chunk, knowledgeID, effCtx, err := h.validateAndGetChunk(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -257,14 +266,13 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Update chunk properties
|
||||
if req.Content != "" {
|
||||
chunk.Content = req.Content
|
||||
}
|
||||
|
||||
chunk.IsEnabled = req.IsEnabled
|
||||
|
||||
if err := h.service.UpdateChunk(ctx, chunk); err != nil {
|
||||
if err := h.service.UpdateChunk(effCtx, chunk); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
@@ -296,14 +304,13 @@ func (h *ChunkHandler) DeleteChunk(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start deleting knowledge chunk")
|
||||
|
||||
// Validate parameters and get chunk
|
||||
chunk, _, err := h.validateAndGetChunk(c)
|
||||
chunk, _, effCtx, err := h.validateAndGetChunk(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.DeleteChunk(ctx, chunk.ID); err != nil {
|
||||
if err := h.service.DeleteChunk(effCtx, chunk.ID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
@@ -338,8 +345,13 @@ func (h *ChunkHandler) DeleteChunksByKnowledgeID(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Delete all chunks under the knowledge
|
||||
err := h.service.DeleteChunksByKnowledgeID(ctx, knowledgeID)
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.DeleteChunksByKnowledgeID(effCtx, knowledgeID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
@@ -386,16 +398,7 @@ func (h *ChunkHandler) DeleteGeneratedQuestion(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
|
||||
// Verify chunk exists and belongs to tenant
|
||||
chunk, err := h.service.GetChunkByID(ctx, chunkID)
|
||||
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
||||
if err != nil {
|
||||
if err == service.ErrChunkNotFound {
|
||||
logger.Warnf(ctx, "Chunk not found, chunk ID: %s", chunkID)
|
||||
@@ -407,14 +410,13 @@ func (h *ChunkHandler) DeleteGeneratedQuestion(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if chunk.TenantID != tenantID.(uint64) {
|
||||
logger.Warnf(ctx, "Tenant has no permission to access chunk, chunk ID: %s", chunkID)
|
||||
c.Error(errors.NewForbiddenError("No permission to access this chunk"))
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, chunk.KnowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the generated question by ID
|
||||
if err := h.service.DeleteGeneratedQuestion(ctx, chunkID, req.QuestionID); err != nil {
|
||||
if err := h.service.DeleteGeneratedQuestion(effCtx, chunkID, req.QuestionID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
|
||||
+280
-74
@@ -1,6 +1,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -18,50 +19,156 @@ import (
|
||||
|
||||
// KnowledgeHandler processes HTTP requests related to knowledge resources
|
||||
type KnowledgeHandler struct {
|
||||
kgService interfaces.KnowledgeService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kgService interfaces.KnowledgeService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// NewKnowledgeHandler creates a new knowledge handler instance
|
||||
func NewKnowledgeHandler(
|
||||
kgService interfaces.KnowledgeService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) *KnowledgeHandler {
|
||||
return &KnowledgeHandler{kgService: kgService, kbService: kbService}
|
||||
return &KnowledgeHandler{
|
||||
kgService: kgService,
|
||||
kbService: kbService,
|
||||
kbShareService: kbShareService,
|
||||
}
|
||||
}
|
||||
|
||||
// validateKnowledgeBaseAccess validates access permissions to a knowledge base
|
||||
// Returns the knowledge base, the knowledge base ID, and any errors encountered
|
||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, error) {
|
||||
// Returns the knowledge base, the knowledge base ID, effective tenant ID, permission level, and any errors encountered
|
||||
// For owned KBs, effectiveTenantID is the caller's tenant ID
|
||||
// For shared KBs, effectiveTenantID is the source tenant ID (owner's tenant)
|
||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
|
||||
// Get user ID from context (needed for shared KB permission check)
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
// Get knowledge base ID from URL path parameter
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
if kbID == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
return nil, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get knowledge base details
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, kbID, errors.NewInternalServerError(err.Error())
|
||||
return nil, kbID, 0, "", errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
|
||||
// Verify tenant permissions
|
||||
if kb.TenantID != c.GetUint64(types.TenantIDContextKey.String()) {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Permission denied to access this knowledge base, tenant ID mismatch, "+
|
||||
"requested tenant ID: %d, knowledge base tenant ID: %d",
|
||||
c.GetUint64(types.TenantIDContextKey.String()),
|
||||
kb.TenantID,
|
||||
)
|
||||
return nil, kbID, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
// Check 1: Verify tenant ownership (owner has full access)
|
||||
if kb.TenantID == tenantID {
|
||||
return kb, kbID, tenantID, types.OrgRoleAdmin, nil
|
||||
}
|
||||
|
||||
return kb, kbID, nil
|
||||
// Check 2: If not owner, check organization shared access
|
||||
if userExists && h.kbShareService != nil {
|
||||
// Check if user has shared access through organization
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
// User has shared access, get the source tenant ID for queries
|
||||
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 kb, kbID, sourceTenantID, permission, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No permission: not owner and no shared access
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Permission denied to access this knowledge base, tenant ID mismatch, "+
|
||||
"requested tenant ID: %d, knowledge base tenant ID: %d",
|
||||
tenantID,
|
||||
kb.TenantID,
|
||||
)
|
||||
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
// validateKnowledgeBaseAccessWithKBID validates access to the given knowledge base ID (e.g. from query or body).
|
||||
// Returns the knowledge base, kbID, effective tenant ID, permission, and error.
|
||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, kbID string) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
kbID = secutils.SanitizeForLog(kbID)
|
||||
if kbID == "" {
|
||||
return nil, "", 0, "", 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, kbID, 0, "", errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
if kb.TenantID == tenantID {
|
||||
return kb, kbID, tenantID, types.OrgRoleAdmin, nil
|
||||
}
|
||||
if userExists && h.kbShareService != nil {
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
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 kb, kbID, sourceTenantID, permission, 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")
|
||||
}
|
||||
|
||||
// resolveKnowledgeAndValidateKBAccess resolves knowledge by ID and validates KB access (owner or shared with required permission).
|
||||
// Returns the knowledge, context with effectiveTenantID set for downstream service calls, and error.
|
||||
func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, knowledgeID string, requiredPermission types.OrgMemberRole) (*types.Knowledge, context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
return nil, ctx, errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
return nil, ctx, errors.NewNotFoundError("Knowledge not found")
|
||||
}
|
||||
|
||||
// Owner: knowledge belongs to caller's tenant
|
||||
if knowledge.TenantID == tenantID {
|
||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
|
||||
// Shared KB: check organization permission
|
||||
if !userExists || h.kbShareService == nil {
|
||||
return nil, ctx, 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, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
if !permission.HasPermission(requiredPermission) {
|
||||
return nil, ctx, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||
}
|
||||
effectiveTenantID := knowledge.TenantID
|
||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
|
||||
}
|
||||
|
||||
// handleDuplicateKnowledgeError handles cases where duplicate knowledge is detected
|
||||
@@ -104,12 +211,19 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating knowledge from file")
|
||||
|
||||
// Validate access to the knowledge base
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
// Validate access to the knowledge base (only owner or admin/editor can create)
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Check write permission
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
|
||||
return
|
||||
}
|
||||
|
||||
// Get the uploaded file
|
||||
file, err := c.FormFile("file")
|
||||
@@ -217,12 +331,19 @@ func (h *KnowledgeHandler) CreateKnowledgeFromURL(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating knowledge from URL")
|
||||
|
||||
// Validate access to the knowledge base
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
// Validate access to the knowledge base (only owner or admin/editor can create)
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Check write permission
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse URL from request body
|
||||
var req struct {
|
||||
@@ -286,11 +407,19 @@ func (h *KnowledgeHandler) CreateManualKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating manual knowledge")
|
||||
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
// Validate access to the knowledge base (only owner or admin/editor can create)
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Check write permission
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
|
||||
return
|
||||
}
|
||||
|
||||
var req types.ManualKnowledgePayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -338,7 +467,6 @@ func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start retrieving knowledge")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
@@ -346,20 +474,15 @@ func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieving knowledge, ID: %s", secutils.SanitizeForLog(id))
|
||||
knowledge, err := h.kgService.GetKnowledgeByID(ctx, id)
|
||||
// Resolve knowledge and validate KB access (at least viewer)
|
||||
knowledge, _, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge retrieved successfully, ID: %s, title: %s",
|
||||
secutils.SanitizeForLog(knowledge.ID),
|
||||
secutils.SanitizeForLog(knowledge.Title),
|
||||
)
|
||||
logger.Infof(ctx, "Knowledge retrieved successfully, ID: %s, title: %s",
|
||||
secutils.SanitizeForLog(knowledge.ID), secutils.SanitizeForLog(knowledge.Title))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": knowledge,
|
||||
@@ -388,14 +511,16 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start retrieving knowledge list")
|
||||
|
||||
// Get knowledge base ID from URL path parameter
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
if kbID == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Knowledge base ID cannot be empty"))
|
||||
// Validate access to the knowledge base (read access - any permission level)
|
||||
_, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Update context with effective tenant ID for shared KB access
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Parse pagination parameters from query string
|
||||
var pagination types.Pagination
|
||||
if err := c.ShouldBindQuery(&pagination); err != nil {
|
||||
@@ -410,13 +535,14 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d",
|
||||
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d, effectiveTenantID: %d",
|
||||
secutils.SanitizeForLog(kbID),
|
||||
secutils.SanitizeForLog(tagID),
|
||||
secutils.SanitizeForLog(keyword),
|
||||
secutils.SanitizeForLog(fileType),
|
||||
pagination.Page,
|
||||
pagination.PageSize,
|
||||
effectiveTenantID,
|
||||
)
|
||||
|
||||
// Retrieve paginated knowledge entries
|
||||
@@ -459,7 +585,6 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start deleting knowledge")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
@@ -467,8 +592,13 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Deleting knowledge, ID: %s", secutils.SanitizeForLog(id))
|
||||
err := h.kgService.DeleteKnowledge(ctx, id)
|
||||
err = h.kgService.DeleteKnowledge(effCtx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
@@ -499,7 +629,6 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start downloading knowledge file")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
@@ -507,10 +636,14 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Retrieving knowledge file, ID: %s", secutils.SanitizeForLog(id))
|
||||
|
||||
// Get file content and filename
|
||||
file, filename, err := h.kgService.GetKnowledgeFile(ctx, id)
|
||||
file, filename, err := h.kgService.GetKnowledgeFile(effCtx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to retrieve file").WithDetails(err.Error()))
|
||||
@@ -547,33 +680,34 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
||||
|
||||
// GetKnowledgeBatchRequest defines parameters for batch knowledge retrieval
|
||||
type GetKnowledgeBatchRequest struct {
|
||||
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
|
||||
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
|
||||
KBID string `form:"kb_id"` // Optional: scope to this KB (validates access and uses effective tenant for shared KB)
|
||||
}
|
||||
|
||||
// GetKnowledgeBatch godoc
|
||||
// @Summary 批量获取知识
|
||||
// @Description 根据ID列表批量获取知识条目
|
||||
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的租户解析
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param ids query []string true "知识ID列表"
|
||||
// @Success 200 {object} map[string]interface{} "知识列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Param ids query []string true "知识ID列表"
|
||||
// @Param kb_id query string false "可选,知识库ID(用于共享知识库时指定范围)"
|
||||
// @Success 200 {object} map[string]interface{} "知识列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /knowledge/batch [get]
|
||||
func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := c.Get(types.TenantIDContextKey.String())
|
||||
if !ok {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
effectiveTenantID := tenantID.(uint64)
|
||||
|
||||
// Parse request parameters from query string
|
||||
var req GetKnowledgeBatchRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
@@ -581,27 +715,41 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Batch retrieving knowledge, tenant ID: %d, number of knowledge IDs: %d",
|
||||
tenantID, len(req.IDs),
|
||||
)
|
||||
var knowledges []*types.Knowledge
|
||||
var err error
|
||||
|
||||
// Optional kb_id: validate KB access and use effective tenant for shared KB
|
||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||
_, _, effID, _, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
effectiveTenantID = effID
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
logger.Infof(ctx, "Batch retrieving knowledge with kb_id, effective tenant ID: %d, IDs count: %d",
|
||||
effectiveTenantID, len(req.IDs))
|
||||
|
||||
knowledges, err = h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, req.IDs)
|
||||
} else {
|
||||
// No kb_id provided: use GetKnowledgeBatchWithSharedAccess to support cross-tenant shared files
|
||||
// This is needed when page is refreshed and frontend doesn't have kb_id mapping
|
||||
logger.Infof(ctx, "Batch retrieving knowledge without kb_id (using shared access), tenant ID: %d, IDs count: %d",
|
||||
effectiveTenantID, len(req.IDs))
|
||||
|
||||
knowledges, err = h.kgService.GetKnowledgeBatchWithSharedAccess(ctx, effectiveTenantID, req.IDs)
|
||||
}
|
||||
|
||||
// Retrieve knowledge entries in batch
|
||||
knowledges, err := h.kgService.GetKnowledgeBatch(ctx, tenantID.(uint64), req.IDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to retrieve knowledge list").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Batch knowledge retrieval successful, requested count: %d, returned count: %d",
|
||||
len(req.IDs), len(knowledges),
|
||||
)
|
||||
logger.Infof(ctx, "Batch knowledge retrieval successful, requested count: %d, returned count: %d",
|
||||
len(req.IDs), len(knowledges))
|
||||
|
||||
// Return results
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": knowledges,
|
||||
@@ -623,7 +771,7 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
||||
// @Router /knowledge/{id} [put]
|
||||
func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
// Get knowledge ID from URL path parameter
|
||||
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
@@ -631,14 +779,21 @@ func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var knowledge types.Knowledge
|
||||
if err := c.ShouldBindJSON(&knowledge); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
knowledge.ID = id
|
||||
|
||||
if err := h.kgService.UpdateKnowledge(ctx, &knowledge); err != nil {
|
||||
if err := h.kgService.UpdateKnowledge(effCtx, &knowledge); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
@@ -675,6 +830,12 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req types.ManualKnowledgePayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse manual knowledge update request", err)
|
||||
@@ -682,7 +843,7 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
knowledge, err := h.kgService.UpdateManualKnowledge(ctx, id, &req)
|
||||
knowledge, err := h.kgService.UpdateManualKnowledge(effCtx, id, &req)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
c.Error(appErr)
|
||||
@@ -704,15 +865,16 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
||||
|
||||
type knowledgeTagBatchRequest struct {
|
||||
Updates map[string]*string `json:"updates" binding:"required,min=1"`
|
||||
KBID string `json:"kb_id"` // Optional: scope to this KB (validates editor access and uses effective tenant for shared KB)
|
||||
}
|
||||
|
||||
// UpdateKnowledgeTagBatch godoc
|
||||
// @Summary 批量更新知识标签
|
||||
// @Description 批量更新知识条目的标签
|
||||
// @Description 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的租户解析
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body object true "标签更新请求"
|
||||
// @Param request body object true "标签更新请求(updates 必填,kb_id 可选)"
|
||||
// @Success 200 {object} map[string]interface{} "更新成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
@@ -720,12 +882,49 @@ type knowledgeTagBatchRequest struct {
|
||||
// @Router /knowledge/tags [put]
|
||||
func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Ensure tenant ID is in context (service reads it; may be missing if request context was not set by auth)
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
|
||||
|
||||
var req knowledgeTagBatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse knowledge tag batch request", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
// Resolve effective tenant: explicit kb_id, or infer from first knowledge ID (for shared KB when frontend doesn't send kb_id)
|
||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||
_, _, effID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to update knowledge tags"))
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effID)
|
||||
} else if len(req.Updates) > 0 {
|
||||
// No kb_id: infer from first knowledge ID so shared-KB updates work without client sending kb_id
|
||||
var firstKnowledgeID string
|
||||
for id := range req.Updates {
|
||||
firstKnowledgeID = id
|
||||
break
|
||||
}
|
||||
if firstKnowledgeID != "" {
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = effCtx
|
||||
}
|
||||
}
|
||||
if err := h.kgService.UpdateKnowledgeTagBatch(ctx, req.Updates); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -754,7 +953,6 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start updating image info")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
@@ -768,6 +966,12 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var request struct {
|
||||
ImageInfo string `json:"image_info"`
|
||||
}
|
||||
@@ -778,9 +982,8 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Update chunk properties
|
||||
logger.Infof(ctx, "Updating knowledge chunk, knowledge ID: %s, chunk ID: %s", id, chunkID)
|
||||
err := h.kgService.UpdateImageInfo(ctx, id, chunkID, secutils.SanitizeForLog(request.ImageInfo))
|
||||
err = h.kgService.UpdateImageInfo(effCtx, id, chunkID, secutils.SanitizeForLog(request.ImageInfo))
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
@@ -811,6 +1014,9 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
||||
// @Router /knowledge/search [get]
|
||||
func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if userID, ok := c.Get(types.UserIDContextKey.String()); ok {
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
|
||||
}
|
||||
keyword := c.Query("keyword")
|
||||
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
|
||||
@@ -826,7 +1032,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve knowledge entries (empty keyword returns recent files)
|
||||
// Retrieve knowledge entries (own + shared KBs; empty keyword returns recent files)
|
||||
knowledges, hasMore, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
type KnowledgeBaseHandler struct {
|
||||
service interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
asynqClient *asynq.Client
|
||||
}
|
||||
|
||||
@@ -29,11 +30,13 @@ type KnowledgeBaseHandler struct {
|
||||
func NewKnowledgeBaseHandler(
|
||||
service interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
asynqClient *asynq.Client,
|
||||
) *KnowledgeBaseHandler {
|
||||
return &KnowledgeBaseHandler{
|
||||
service: service,
|
||||
knowledgeService: knowledgeService,
|
||||
kbShareService: kbShareService,
|
||||
asynqClient: asynqClient,
|
||||
}
|
||||
}
|
||||
@@ -56,11 +59,10 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start hybrid search")
|
||||
|
||||
// Validate knowledge base ID
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Knowledge base ID cannot be empty"))
|
||||
// Validate and check permission for knowledge base access
|
||||
_, id, effectiveTenantID, _, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -72,10 +74,11 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Executing hybrid search, knowledge base ID: %s, query: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.QueryText))
|
||||
logger.Infof(ctx, "Executing hybrid search, knowledge base ID: %s, query: %s, effectiveTenantID: %d",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.QueryText), effectiveTenantID)
|
||||
|
||||
// Execute hybrid search with default search parameters
|
||||
// Note: For shared KBs, the service uses effectiveTenantID internally via context
|
||||
results, err := h.service.HybridSearch(ctx, id, req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
@@ -139,43 +142,64 @@ func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) {
|
||||
}
|
||||
|
||||
// validateAndGetKnowledgeBase validates request parameters and retrieves the knowledge base
|
||||
// Returns the knowledge base, knowledge base ID, and any errors encountered
|
||||
func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*types.KnowledgeBase, string, error) {
|
||||
// Returns the knowledge base, knowledge base ID, effective tenant ID for embedding, permission level, and any errors encountered
|
||||
// For owned KBs, effectiveTenantID is the caller's tenant ID
|
||||
// For shared KBs, effectiveTenantID is the source tenant ID (owner's tenant)
|
||||
func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
|
||||
// Get user ID from context (needed for shared KB permission check)
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
// Get knowledge base ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
return nil, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
|
||||
// Verify tenant has permission to access this knowledge base
|
||||
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, id, errors.NewInternalServerError(err.Error())
|
||||
return nil, id, 0, "", errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
|
||||
// Verify tenant ownership
|
||||
if kb.TenantID != tenantID.(uint64) {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access this knowledge base, knowledge base ID: %s, "+
|
||||
"request tenant ID: %d, knowledge base tenant ID: %d",
|
||||
id, tenantID.(uint64), kb.TenantID,
|
||||
)
|
||||
return nil, id, errors.NewForbiddenError("No permission to operate")
|
||||
// Check 1: Verify tenant ownership (owner has full access)
|
||||
if kb.TenantID == tenantID.(uint64) {
|
||||
return kb, id, tenantID.(uint64), types.OrgRoleAdmin, nil
|
||||
}
|
||||
|
||||
return kb, id, nil
|
||||
// Check 2: If not owner, check organization shared access
|
||||
if userExists && h.kbShareService != nil {
|
||||
// Check if user has shared access through organization
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, id, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
// User has shared access, get the source tenant ID for embedding queries
|
||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, id)
|
||||
if srcErr == nil {
|
||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
||||
userID.(string), id, permission, sourceTenantID)
|
||||
return kb, id, sourceTenantID, permission, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No permission: not owner and no shared access
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access this knowledge base, knowledge base ID: %s, "+
|
||||
"request tenant ID: %d, knowledge base tenant ID: %d",
|
||||
id, tenantID.(uint64), kb.TenantID,
|
||||
)
|
||||
return nil, id, 0, "", errors.NewForbiddenError("No permission to operate")
|
||||
}
|
||||
|
||||
// GetKnowledgeBase godoc
|
||||
@@ -193,7 +217,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, _, _, _, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -226,6 +250,25 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Get share counts for all knowledge bases
|
||||
if len(kbs) > 0 && h.kbShareService != nil {
|
||||
kbIDs := make([]string, len(kbs))
|
||||
for i, kb := range kbs {
|
||||
kbIDs[i] = kb.ID
|
||||
}
|
||||
|
||||
shareCounts, err := h.kbShareService.CountSharesByKnowledgeBaseIDs(ctx, kbIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get share counts: %v", err)
|
||||
} else {
|
||||
for _, kb := range kbs {
|
||||
if count, ok := shareCounts[kb.ID]; ok {
|
||||
kb.ShareCount = count
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": kbs,
|
||||
@@ -257,12 +300,18 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
|
||||
logger.Info(ctx, "Start updating knowledge base")
|
||||
|
||||
// Validate and get the knowledge base
|
||||
_, id, err := h.validateAndGetKnowledgeBase(c)
|
||||
_, id, _, permission, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Only admin/editor can update knowledge base
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to update knowledge base"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var req UpdateKnowledgeBaseRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -307,12 +356,19 @@ func (h *KnowledgeBaseHandler) DeleteKnowledgeBase(c *gin.Context) {
|
||||
logger.Info(ctx, "Start deleting knowledge base")
|
||||
|
||||
// Validate and get the knowledge base
|
||||
kb, id, err := h.validateAndGetKnowledgeBase(c)
|
||||
kb, id, _, permission, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Only owner (admin with matching tenant) can delete knowledge base
|
||||
tenantID, _ := c.Get(types.TenantIDContextKey.String())
|
||||
if kb.TenantID != tenantID.(uint64) || permission != types.OrgRoleAdmin {
|
||||
c.Error(errors.NewForbiddenError("Only knowledge base owner can delete"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Deleting knowledge base, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(kb.Name))
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -86,6 +86,48 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
}
|
||||
}
|
||||
|
||||
// Merge @mentioned items into knowledge_base_ids and knowledge_ids so that
|
||||
// retrieval (quick-answer and agent mode) uses the same targets the user @mentioned.
|
||||
// This fixes the case where user only @mentions a (shared) KB in the input but
|
||||
// does not select it in the sidebar — without this merge, retrieval would not search those KBs.
|
||||
kbIDs := make([]string, 0, len(request.KnowledgeBaseIDs)+len(request.MentionedItems))
|
||||
kbIDSet := make(map[string]bool)
|
||||
for _, id := range request.KnowledgeBaseIDs {
|
||||
if id != "" && !kbIDSet[id] {
|
||||
kbIDs = append(kbIDs, id)
|
||||
kbIDSet[id] = true
|
||||
}
|
||||
}
|
||||
knowledgeIDs := make([]string, 0, len(request.KnowledgeIds)+len(request.MentionedItems))
|
||||
knowledgeIDSet := make(map[string]bool)
|
||||
for _, id := range request.KnowledgeIds {
|
||||
if id != "" && !knowledgeIDSet[id] {
|
||||
knowledgeIDs = append(knowledgeIDs, id)
|
||||
knowledgeIDSet[id] = true
|
||||
}
|
||||
}
|
||||
for _, item := range request.MentionedItems {
|
||||
if item.ID == "" {
|
||||
continue
|
||||
}
|
||||
switch item.Type {
|
||||
case "kb":
|
||||
if !kbIDSet[item.ID] {
|
||||
kbIDs = append(kbIDs, item.ID)
|
||||
kbIDSet[item.ID] = true
|
||||
}
|
||||
case "file":
|
||||
if !knowledgeIDSet[item.ID] {
|
||||
knowledgeIDs = append(knowledgeIDs, item.ID)
|
||||
knowledgeIDSet[item.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log merge results for debugging
|
||||
logger.Infof(ctx, "[%s] @mention merge: request.KnowledgeBaseIDs=%v, request.MentionedItems=%d, merged kbIDs=%v, merged knowledgeIDs=%v",
|
||||
logPrefix, request.KnowledgeBaseIDs, len(request.MentionedItems), kbIDs, knowledgeIDs)
|
||||
|
||||
// Build request context
|
||||
reqCtx := &qaRequestContext{
|
||||
ctx: ctx,
|
||||
@@ -101,8 +143,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
},
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(request.KnowledgeBaseIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(request.KnowledgeIds),
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
|
||||
+88
-21
@@ -16,9 +16,11 @@ import (
|
||||
|
||||
// TagHandler handles knowledge base tag operations.
|
||||
type TagHandler struct {
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// DeleteTagRequest represents the request body for deleting a tag
|
||||
@@ -27,19 +29,62 @@ type DeleteTagRequest struct {
|
||||
}
|
||||
|
||||
// NewTagHandler creates a new TagHandler.
|
||||
func NewTagHandler(tagService interfaces.KnowledgeTagService, tagRepo interfaces.KnowledgeTagRepository, chunkRepo interfaces.ChunkRepository) *TagHandler {
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo}
|
||||
func NewTagHandler(
|
||||
tagService interfaces.KnowledgeTagService,
|
||||
tagRepo interfaces.KnowledgeTagRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) *TagHandler {
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService}
|
||||
}
|
||||
|
||||
// effectiveCtxForKB validates KB access (owner or shared) and returns context with effectiveTenantID for downstream service calls.
|
||||
func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
// resolveTagID resolves tag_id parameter which can be either UUID or seq_id (integer).
|
||||
// Returns the UUID of the tag.
|
||||
// Uses tenant from c's context. Use resolveTagIDWithCtx when effectiveTenantID is set (e.g. shared KB).
|
||||
func (h *TagHandler) resolveTagID(c *gin.Context) (string, error) {
|
||||
ctx := c.Request.Context()
|
||||
return h.resolveTagIDWithCtx(c, c.Request.Context())
|
||||
}
|
||||
|
||||
// resolveTagIDWithCtx resolves tag_id using the given context for tenant (e.g. effCtx for shared KB).
|
||||
func (h *TagHandler) resolveTagIDWithCtx(c *gin.Context, ctx context.Context) (string, error) {
|
||||
tagIDParam := secutils.SanitizeForLog(c.Param("tag_id"))
|
||||
|
||||
// Try to parse as integer (seq_id)
|
||||
if seqID, err := strconv.ParseInt(tagIDParam, 10, 64); err == nil {
|
||||
// It's an integer, look up by seq_id
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
tag, err := h.tagRepo.GetBySeqID(ctx, tenantID, seqID)
|
||||
if err != nil {
|
||||
@@ -47,8 +92,6 @@ func (h *TagHandler) resolveTagID(c *gin.Context) (string, error) {
|
||||
}
|
||||
return tag.ID, nil
|
||||
}
|
||||
|
||||
// It's a UUID string
|
||||
return tagIDParam, nil
|
||||
}
|
||||
|
||||
@@ -76,6 +119,12 @@ func (h *TagHandler) ListTags(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
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)
|
||||
@@ -85,7 +134,7 @@ func (h *TagHandler) ListTags(c *gin.Context) {
|
||||
|
||||
keyword := secutils.SanitizeForLog(c.Query("keyword"))
|
||||
|
||||
tags, err := h.tagService.ListTags(ctx, kbID, &page, keyword)
|
||||
tags, err := h.tagService.ListTags(effCtx, kbID, &page, keyword)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -121,6 +170,12 @@ func (h *TagHandler) CreateTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req createTagRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind create tag payload", err)
|
||||
@@ -128,7 +183,7 @@ func (h *TagHandler) CreateTag(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
tag, err := h.tagService.CreateTag(ctx, kbID,
|
||||
tag, err := h.tagService.CreateTag(effCtx, kbID,
|
||||
secutils.SanitizeForLog(req.Name), secutils.SanitizeForLog(req.Color), req.SortOrder)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
@@ -166,8 +221,15 @@ type updateTagRequest struct {
|
||||
// @Router /knowledge-bases/{id}/tags/{tag_id} [put]
|
||||
func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
tagID, err := h.resolveTagID(c)
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
tagID, err := h.resolveTagIDWithCtx(c, effCtx)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -180,7 +242,7 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
tag, err := h.tagService.UpdateTag(ctx, tagID, req.Name, req.Color, req.SortOrder)
|
||||
tag, err := h.tagService.UpdateTag(effCtx, tagID, req.Name, req.Color, req.SortOrder)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tag_id": tagID,
|
||||
@@ -213,8 +275,15 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/tags/{tag_id} [delete]
|
||||
func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
tagID, err := h.resolveTagID(c)
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
tagID, err := h.resolveTagIDWithCtx(c, effCtx)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -224,14 +293,12 @@ func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
contentOnly := c.Query("content_only") == "true"
|
||||
|
||||
var req DeleteTagRequest
|
||||
// Ignore bind error since body is optional
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
|
||||
// Convert seq_ids to UUIDs for excludeIDs
|
||||
var excludeUUIDs []string
|
||||
if len(req.ExcludeIDs) > 0 {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
chunks, err := h.getChunksBySeqIDs(ctx, tenantID, req.ExcludeIDs)
|
||||
tenantID := effCtx.Value(types.TenantIDContextKey).(uint64)
|
||||
chunks, err := h.getChunksBySeqIDs(effCtx, tenantID, req.ExcludeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to resolve exclude_ids: %v", err)
|
||||
} else {
|
||||
@@ -242,7 +309,7 @@ func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.tagService.DeleteTag(ctx, tagID, force, contentOnly, excludeUUIDs); err != nil {
|
||||
if err := h.tagService.DeleteTag(effCtx, tagID, force, contentOnly, excludeUUIDs); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tag_id": tagID,
|
||||
})
|
||||
|
||||
@@ -292,6 +292,8 @@ func CloneContext(ctx context.Context) context.Context {
|
||||
types.TenantIDContextKey,
|
||||
types.RequestIDContextKey,
|
||||
types.TenantInfoContextKey,
|
||||
types.UserIDContextKey,
|
||||
types.UserContextKey,
|
||||
} {
|
||||
if v := ctx.Value(k); v != nil {
|
||||
newCtx = context.WithValue(newCtx, k, v)
|
||||
|
||||
@@ -131,13 +131,17 @@ func Auth(
|
||||
c.Set(types.TenantIDContextKey.String(), targetTenantID)
|
||||
c.Set(types.TenantInfoContextKey.String(), tenant)
|
||||
c.Set(types.UserContextKey.String(), user)
|
||||
c.Set(types.UserIDContextKey.String(), user.ID)
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID),
|
||||
types.TenantInfoContextKey, tenant,
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID),
|
||||
types.TenantInfoContextKey, tenant,
|
||||
),
|
||||
types.UserContextKey, user,
|
||||
),
|
||||
types.UserContextKey, user,
|
||||
types.UserIDContextKey, user.ID,
|
||||
),
|
||||
)
|
||||
c.Next()
|
||||
|
||||
@@ -49,6 +49,7 @@ type RouterParams struct {
|
||||
TagHandler *handler.TagHandler
|
||||
CustomAgentHandler *handler.CustomAgentHandler
|
||||
SkillHandler *handler.SkillHandler
|
||||
OrganizationHandler *handler.OrganizationHandler
|
||||
}
|
||||
|
||||
// NewRouter 创建新的路由
|
||||
@@ -114,6 +115,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
|
||||
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler)
|
||||
RegisterSkillRoutes(v1, params.SkillHandler)
|
||||
RegisterOrganizationRoutes(v1, params.OrganizationHandler)
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -450,3 +452,65 @@ func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler)
|
||||
skills.GET("", skillHandler.ListSkills)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterOrganizationRoutes registers organization and sharing routes
|
||||
func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.OrganizationHandler) {
|
||||
// Organization routes
|
||||
orgs := r.Group("/organizations")
|
||||
{
|
||||
// Create organization
|
||||
orgs.POST("", orgHandler.CreateOrganization)
|
||||
// List my organizations
|
||||
orgs.GET("", orgHandler.ListMyOrganizations)
|
||||
// Preview organization by invite code (without joining)
|
||||
orgs.GET("/preview/:code", orgHandler.PreviewByInviteCode)
|
||||
// Join organization by invite code
|
||||
orgs.POST("/join", orgHandler.JoinByInviteCode)
|
||||
// Submit join request (for organizations that require approval)
|
||||
orgs.POST("/join-request", orgHandler.SubmitJoinRequest)
|
||||
// Get organization by ID
|
||||
orgs.GET("/:id", orgHandler.GetOrganization)
|
||||
// Update organization
|
||||
orgs.PUT("/:id", orgHandler.UpdateOrganization)
|
||||
// Delete organization
|
||||
orgs.DELETE("/:id", orgHandler.DeleteOrganization)
|
||||
// Leave organization
|
||||
orgs.POST("/:id/leave", orgHandler.LeaveOrganization)
|
||||
// Request role upgrade (for existing members)
|
||||
orgs.POST("/:id/request-upgrade", orgHandler.RequestRoleUpgrade)
|
||||
// Generate invite code
|
||||
orgs.POST("/:id/invite-code", orgHandler.GenerateInviteCode)
|
||||
// Search users for invite (admin only)
|
||||
orgs.GET("/:id/search-users", orgHandler.SearchUsersForInvite)
|
||||
// Invite member directly (admin only)
|
||||
orgs.POST("/:id/invite", orgHandler.InviteMember)
|
||||
// List members
|
||||
orgs.GET("/:id/members", orgHandler.ListMembers)
|
||||
// Update member role
|
||||
orgs.PUT("/:id/members/:user_id", orgHandler.UpdateMemberRole)
|
||||
// Remove member
|
||||
orgs.DELETE("/:id/members/:user_id", orgHandler.RemoveMember)
|
||||
// List join requests (admin only)
|
||||
orgs.GET("/:id/join-requests", orgHandler.ListJoinRequests)
|
||||
// Review join request (admin only)
|
||||
orgs.PUT("/:id/join-requests/:request_id/review", orgHandler.ReviewJoinRequest)
|
||||
// List knowledge bases shared to this organization
|
||||
orgs.GET("/:id/shares", orgHandler.ListOrgShares)
|
||||
}
|
||||
|
||||
// Knowledge base sharing routes (add to existing kb routes)
|
||||
kbShares := r.Group("/knowledge-bases/:id/shares")
|
||||
{
|
||||
// Share knowledge base
|
||||
kbShares.POST("", orgHandler.ShareKnowledgeBase)
|
||||
// List shares
|
||||
kbShares.GET("", orgHandler.ListKBShares)
|
||||
// Update share permission
|
||||
kbShares.PUT("/:share_id", orgHandler.UpdateSharePermission)
|
||||
// Remove share
|
||||
kbShares.DELETE("/:share_id", orgHandler.RemoveShare)
|
||||
}
|
||||
|
||||
// Shared knowledge bases route
|
||||
r.GET("/shared-knowledge-bases", orgHandler.ListSharedKnowledgeBases)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ const (
|
||||
LoggerContextKey ContextKey = "Logger"
|
||||
// UserContextKey is the context key for user information
|
||||
UserContextKey ContextKey = "User"
|
||||
// UserIDContextKey is the context key for user ID
|
||||
UserIDContextKey ContextKey = "UserID"
|
||||
)
|
||||
|
||||
// String returns the string representation of the context key
|
||||
|
||||
@@ -12,10 +12,14 @@ type ChunkRepository interface {
|
||||
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
|
||||
// GetChunkByID gets a chunk by id
|
||||
GetChunkByID(ctx context.Context, tenantID uint64, id string) (*types.Chunk, error)
|
||||
// GetChunkByIDOnly gets a chunk by id without tenant filter (for permission resolution)
|
||||
GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error)
|
||||
// GetChunkBySeqID gets a chunk by seq_id
|
||||
GetChunkBySeqID(ctx context.Context, tenantID uint64, seqID int64) (*types.Chunk, error)
|
||||
// ListChunksByID lists chunks by ids
|
||||
ListChunksByID(ctx context.Context, tenantID uint64, ids []string) ([]*types.Chunk, error)
|
||||
// ListChunksByIDOnly lists chunks by ids without tenant filter (for shared KB resolution).
|
||||
ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error)
|
||||
// ListChunksBySeqID lists chunks by seq_ids
|
||||
ListChunksBySeqID(ctx context.Context, tenantID uint64, seqIDs []int64) ([]*types.Chunk, error)
|
||||
// ListChunksByKnowledgeID lists chunks by knowledge id
|
||||
@@ -84,8 +88,10 @@ type ChunkRepository interface {
|
||||
type ChunkService interface {
|
||||
// CreateChunks creates chunks
|
||||
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
|
||||
// GetChunkByID gets a chunk by id
|
||||
// GetChunkByID gets a chunk by id (uses tenant from context)
|
||||
GetChunkByID(ctx context.Context, id string) (*types.Chunk, error)
|
||||
// GetChunkByIDOnly gets a chunk by id without tenant filter (for permission resolution)
|
||||
GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error)
|
||||
// ListChunksByKnowledgeID lists chunks by knowledge id
|
||||
ListChunksByKnowledgeID(ctx context.Context, knowledgeID string) ([]*types.Chunk, error)
|
||||
// ListPagedChunksByKnowledgeID lists paged chunks by knowledge id
|
||||
|
||||
@@ -42,10 +42,14 @@ type KnowledgeService interface {
|
||||
kbID string,
|
||||
payload *types.ManualKnowledgePayload,
|
||||
) (*types.Knowledge, error)
|
||||
// GetKnowledgeByID retrieves knowledge by ID.
|
||||
// GetKnowledgeByID retrieves knowledge by ID (uses tenant from context).
|
||||
GetKnowledgeByID(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeByIDOnly retrieves knowledge by ID without tenant filter (for permission resolution).
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeBatch retrieves a batch of knowledge by IDs.
|
||||
GetKnowledgeBatch(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
|
||||
// GetKnowledgeBatchWithSharedAccess retrieves knowledge by IDs including items from shared KBs the user has access to.
|
||||
GetKnowledgeBatchWithSharedAccess(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
|
||||
// ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base.
|
||||
ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error)
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination.
|
||||
@@ -148,6 +152,8 @@ type KnowledgeService interface {
|
||||
type KnowledgeRepository interface {
|
||||
CreateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
|
||||
GetKnowledgeByID(ctx context.Context, tenantID uint64, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution).
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Knowledge, error)
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination.
|
||||
// When tagID is non-empty, results are filtered by tag_id.
|
||||
@@ -182,6 +188,8 @@ type KnowledgeRepository interface {
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant.
|
||||
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
|
||||
SearchKnowledge(ctx context.Context, tenantID uint64, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
// SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (own + shared).
|
||||
SearchKnowledgeInScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
// ListIDsByTagID returns all knowledge IDs that have the specified tag ID.
|
||||
ListIDsByTagID(ctx context.Context, tenantID uint64, kbID, tagID string) ([]string, error)
|
||||
}
|
||||
|
||||
@@ -32,6 +32,16 @@ type KnowledgeBaseService interface {
|
||||
// - Possible errors such as not existing, insufficient permissions, etc.
|
||||
GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error)
|
||||
|
||||
// GetKnowledgeBaseByIDOnly retrieves knowledge base by ID without tenant filter
|
||||
// Used for cross-tenant shared KB access where permission is checked elsewhere
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the knowledge base
|
||||
// Returns:
|
||||
// - Knowledge base object, if found
|
||||
// - Possible errors such as not existing, etc.
|
||||
GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error)
|
||||
|
||||
// ListKnowledgeBases lists all knowledge bases under the current tenant
|
||||
// Parameters:
|
||||
// - ctx: Context information, containing tenant information
|
||||
|
||||
@@ -23,6 +23,8 @@ type ModelService interface {
|
||||
DeleteModel(ctx context.Context, id string) error
|
||||
// GetEmbeddingModel gets an embedding model
|
||||
GetEmbeddingModel(ctx context.Context, modelId string) (embedding.Embedder, error)
|
||||
// GetEmbeddingModelForTenant gets an embedding model for a specific tenant (for cross-tenant sharing)
|
||||
GetEmbeddingModelForTenant(ctx context.Context, modelId string, tenantID uint64) (embedding.Embedder, error)
|
||||
// GetRerankModel gets a rerank model
|
||||
GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error)
|
||||
// GetChatModel gets a chat model
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// OrganizationService defines the organization service interface
|
||||
type OrganizationService interface {
|
||||
// Organization CRUD
|
||||
CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error)
|
||||
GetOrganization(ctx context.Context, id string) (*types.Organization, error)
|
||||
GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
||||
ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error)
|
||||
UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error)
|
||||
DeleteOrganization(ctx context.Context, id string, userID string) error
|
||||
|
||||
// Member Management
|
||||
AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error
|
||||
RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error
|
||||
UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error
|
||||
ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error)
|
||||
GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error)
|
||||
|
||||
// Invite Code
|
||||
GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error)
|
||||
JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error)
|
||||
|
||||
// Join Requests (for organizations that require approval)
|
||||
SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error)
|
||||
ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error)
|
||||
CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error)
|
||||
ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error
|
||||
|
||||
// Role Upgrade Requests (for existing members to request higher permissions)
|
||||
RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error)
|
||||
GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error)
|
||||
|
||||
// Permission Check
|
||||
IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error)
|
||||
GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error)
|
||||
}
|
||||
|
||||
// OrganizationRepository defines the organization repository interface
|
||||
type OrganizationRepository interface {
|
||||
// Organization CRUD
|
||||
Create(ctx context.Context, org *types.Organization) error
|
||||
GetByID(ctx context.Context, id string) (*types.Organization, error)
|
||||
GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
||||
ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error)
|
||||
Update(ctx context.Context, org *types.Organization) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// Member operations
|
||||
AddMember(ctx context.Context, member *types.OrganizationMember) error
|
||||
RemoveMember(ctx context.Context, orgID string, userID string) error
|
||||
UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error
|
||||
ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error)
|
||||
GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error)
|
||||
CountMembers(ctx context.Context, orgID string) (int64, error)
|
||||
|
||||
// Invite code
|
||||
UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error
|
||||
|
||||
// Join requests
|
||||
CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error
|
||||
GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error)
|
||||
GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error)
|
||||
GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error)
|
||||
ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error)
|
||||
CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error)
|
||||
UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error
|
||||
}
|
||||
|
||||
// KBShareService defines the knowledge base sharing service interface
|
||||
type KBShareService interface {
|
||||
// Share Management
|
||||
ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error)
|
||||
UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error
|
||||
RemoveShare(ctx context.Context, shareID string, userID string) error
|
||||
|
||||
// Query
|
||||
ListSharesByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error)
|
||||
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
|
||||
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||
|
||||
// Permission Check
|
||||
CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error)
|
||||
HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error)
|
||||
|
||||
// Get source tenant for cross-tenant embedding
|
||||
GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error)
|
||||
|
||||
// Count shares for knowledge bases
|
||||
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
||||
}
|
||||
|
||||
// KBShareRepository defines the knowledge base sharing repository interface
|
||||
type KBShareRepository interface {
|
||||
// CRUD
|
||||
Create(ctx context.Context, share *types.KnowledgeBaseShare) error
|
||||
GetByID(ctx context.Context, id string) (*types.KnowledgeBaseShare, error)
|
||||
GetByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||
Update(ctx context.Context, share *types.KnowledgeBaseShare) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
// DeleteByKnowledgeBaseID soft-deletes all shares for a knowledge base (e.g. when KB is deleted)
|
||||
DeleteByKnowledgeBaseID(ctx context.Context, kbID string) error
|
||||
// DeleteByOrganizationID soft-deletes all shares for an organization (e.g. when the org is deleted)
|
||||
DeleteByOrganizationID(ctx context.Context, orgID string) error
|
||||
|
||||
// List
|
||||
ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
|
||||
// Query for user's accessible shared knowledge bases
|
||||
ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error)
|
||||
|
||||
// Count shares
|
||||
CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error)
|
||||
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
||||
}
|
||||
@@ -36,6 +36,8 @@ type UserService interface {
|
||||
RevokeToken(ctx context.Context, token string) error
|
||||
// GetCurrentUser gets current user from context
|
||||
GetCurrentUser(ctx context.Context) (*types.User, error)
|
||||
// SearchUsers searches users by username or email
|
||||
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
|
||||
}
|
||||
|
||||
// UserRepository defines the user repository interface
|
||||
@@ -54,6 +56,8 @@ type UserRepository interface {
|
||||
DeleteUser(ctx context.Context, id string) error
|
||||
// ListUsers lists users with pagination
|
||||
ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error)
|
||||
// SearchUsers searches users by username or email
|
||||
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
|
||||
}
|
||||
|
||||
// AuthTokenRepository defines the auth token repository interface
|
||||
|
||||
@@ -147,6 +147,12 @@ type ManualKnowledgePayload struct {
|
||||
TagID string `json:"tag_id"`
|
||||
}
|
||||
|
||||
// KnowledgeSearchScope defines a (tenant_id, knowledge_base_id) scope for knowledge search (e.g. own KBs + shared KBs).
|
||||
type KnowledgeSearchScope struct {
|
||||
TenantID uint64
|
||||
KBID string
|
||||
}
|
||||
|
||||
// NewManualKnowledgeMetadata creates a new ManualKnowledgeMetadata instance.
|
||||
func NewManualKnowledgeMetadata(content, status string, version int) *ManualKnowledgeMetadata {
|
||||
if version <= 0 {
|
||||
|
||||
@@ -81,6 +81,8 @@ type KnowledgeBase struct {
|
||||
IsProcessing bool `yaml:"is_processing" json:"is_processing" gorm:"-"`
|
||||
// ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)
|
||||
ProcessingCount int64 `yaml:"processing_count" json:"processing_count" gorm:"-"`
|
||||
// ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)
|
||||
ShareCount int64 `yaml:"share_count" json:"share_count" gorm:"-"`
|
||||
}
|
||||
|
||||
// KnowledgeBaseConfig represents the knowledge base configuration
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OrgMemberRole represents the role of an organization member
|
||||
type OrgMemberRole string
|
||||
|
||||
const (
|
||||
// OrgRoleAdmin has full control over the organization and shared knowledge bases
|
||||
OrgRoleAdmin OrgMemberRole = "admin"
|
||||
// OrgRoleEditor can edit shared knowledge base content but cannot manage settings
|
||||
OrgRoleEditor OrgMemberRole = "editor"
|
||||
// OrgRoleViewer can only view and search shared knowledge bases
|
||||
OrgRoleViewer OrgMemberRole = "viewer"
|
||||
)
|
||||
|
||||
// IsValid checks if the role is valid
|
||||
func (r OrgMemberRole) IsValid() bool {
|
||||
switch r {
|
||||
case OrgRoleAdmin, OrgRoleEditor, OrgRoleViewer:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// HasPermission checks if this role has at least the required permission level
|
||||
func (r OrgMemberRole) HasPermission(required OrgMemberRole) bool {
|
||||
roleLevel := map[OrgMemberRole]int{
|
||||
OrgRoleAdmin: 3,
|
||||
OrgRoleEditor: 2,
|
||||
OrgRoleViewer: 1,
|
||||
}
|
||||
return roleLevel[r] >= roleLevel[required]
|
||||
}
|
||||
|
||||
// Organization represents a collaboration organization for cross-tenant sharing
|
||||
type Organization struct {
|
||||
// Unique identifier of the organization
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Name of the organization
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
// Description of the organization
|
||||
Description string `json:"description" gorm:"type:text"`
|
||||
// Avatar URL for display in list and settings
|
||||
Avatar string `json:"avatar" gorm:"type:varchar(512)"`
|
||||
// User ID of the organization owner
|
||||
OwnerID string `json:"owner_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Unique invitation code for joining the organization
|
||||
InviteCode string `json:"invite_code" gorm:"type:varchar(32);uniqueIndex"`
|
||||
// When the current invite code expires; nil means no expiry
|
||||
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at" gorm:"type:timestamp with time zone"`
|
||||
// Invite link validity in days: 0=never, 1/7/30
|
||||
InviteCodeValidityDays int `json:"invite_code_validity_days" gorm:"default:7"`
|
||||
// Whether joining requires admin approval
|
||||
RequireApproval bool `json:"require_approval" gorm:"default:false"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Deletion time (soft delete)
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
Owner *User `json:"owner,omitempty" gorm:"foreignKey:OwnerID"`
|
||||
Members []OrganizationMember `json:"members,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
Shares []KnowledgeBaseShare `json:"shares,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (Organization) TableName() string {
|
||||
return "organizations"
|
||||
}
|
||||
|
||||
// OrganizationMember represents a member of an organization
|
||||
type OrganizationMember struct {
|
||||
// Unique identifier
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Organization ID
|
||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||
// User ID of the member
|
||||
UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Tenant ID that the member belongs to
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
// Role in the organization (admin/editor/viewer)
|
||||
Role OrgMemberRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (OrganizationMember) TableName() string {
|
||||
return "organization_members"
|
||||
}
|
||||
|
||||
// JoinRequestStatus represents the status of a join request
|
||||
type JoinRequestStatus string
|
||||
|
||||
const (
|
||||
JoinRequestStatusPending JoinRequestStatus = "pending"
|
||||
JoinRequestStatusApproved JoinRequestStatus = "approved"
|
||||
JoinRequestStatusRejected JoinRequestStatus = "rejected"
|
||||
)
|
||||
|
||||
// JoinRequestType represents the type of a join request
|
||||
type JoinRequestType string
|
||||
|
||||
const (
|
||||
// JoinRequestTypeJoin is for new member join requests
|
||||
JoinRequestTypeJoin JoinRequestType = "join"
|
||||
// JoinRequestTypeUpgrade is for role upgrade requests from existing members
|
||||
JoinRequestTypeUpgrade JoinRequestType = "upgrade"
|
||||
)
|
||||
|
||||
// OrganizationJoinRequest represents a request to join an organization or upgrade role
|
||||
type OrganizationJoinRequest struct {
|
||||
// Unique identifier
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Organization ID
|
||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||
// User ID of the requester
|
||||
UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Tenant ID of the requester
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null"`
|
||||
// Type of request: 'join' for new member, 'upgrade' for role upgrade
|
||||
RequestType JoinRequestType `json:"request_type" gorm:"type:varchar(32);not null;default:'join';index"`
|
||||
// Previous role before upgrade (only for upgrade requests)
|
||||
PrevRole OrgMemberRole `json:"prev_role" gorm:"column:prev_role;type:varchar(32)"`
|
||||
// Role requested by the applicant (admin/editor/viewer)
|
||||
RequestedRole OrgMemberRole `json:"requested_role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
// Status of the request
|
||||
Status JoinRequestStatus `json:"status" gorm:"type:varchar(32);not null;default:'pending';index"`
|
||||
// Optional message from the requester
|
||||
Message string `json:"message" gorm:"type:text"`
|
||||
// User ID of the admin who reviewed the request
|
||||
ReviewedBy string `json:"reviewed_by" gorm:"type:varchar(36)"`
|
||||
// Time when the request was reviewed
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
// Optional message from the reviewer
|
||||
ReviewMessage string `json:"review_message" gorm:"type:text"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
||||
Reviewer *User `json:"reviewer,omitempty" gorm:"foreignKey:ReviewedBy"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (OrganizationJoinRequest) TableName() string {
|
||||
return "organization_join_requests"
|
||||
}
|
||||
|
||||
// KnowledgeBaseShare represents a sharing record of a knowledge base to an organization
|
||||
type KnowledgeBaseShare struct {
|
||||
// Unique identifier
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Knowledge base ID being shared
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Organization ID receiving the share
|
||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||
// User ID who shared the knowledge base
|
||||
SharedByUserID string `json:"shared_by_user_id" gorm:"type:varchar(36);not null"`
|
||||
// Original tenant ID of the knowledge base (for cross-tenant embedding model access)
|
||||
SourceTenantID uint64 `json:"source_tenant_id" gorm:"not null;index"`
|
||||
// Permission level (admin/editor/viewer)
|
||||
Permission OrgMemberRole `json:"permission" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Deletion time (soft delete)
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
KnowledgeBase *KnowledgeBase `json:"knowledge_base,omitempty" gorm:"foreignKey:KnowledgeBaseID"`
|
||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (KnowledgeBaseShare) TableName() string {
|
||||
return "kb_shares"
|
||||
}
|
||||
|
||||
// SharedKnowledgeBaseInfo represents a shared knowledge base with additional sharing info
|
||||
type SharedKnowledgeBaseInfo struct {
|
||||
KnowledgeBase *KnowledgeBase `json:"knowledge_base"`
|
||||
ShareID string `json:"share_id"`
|
||||
OrganizationID string `json:"organization_id"`
|
||||
OrgName string `json:"org_name"`
|
||||
Permission OrgMemberRole `json:"permission"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
SharedAt time.Time `json:"shared_at"`
|
||||
}
|
||||
|
||||
// ----------------------
|
||||
// Request/Response Types
|
||||
// ----------------------
|
||||
|
||||
// CreateOrganizationRequest represents a request to create an organization
|
||||
type CreateOrganizationRequest struct {
|
||||
Name string `json:"name" binding:"required,min=1,max=255"`
|
||||
Description string `json:"description" binding:"max=1000"`
|
||||
Avatar string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
|
||||
InviteCodeValidityDays *int `json:"invite_code_validity_days"` // optional: 0=never, 1, 7, 30; default 7
|
||||
}
|
||||
|
||||
// UpdateOrganizationRequest represents a request to update an organization
|
||||
type UpdateOrganizationRequest struct {
|
||||
Name *string `json:"name" binding:"omitempty,min=1,max=255"`
|
||||
Description *string `json:"description" binding:"omitempty,max=1000"`
|
||||
Avatar *string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
|
||||
RequireApproval *bool `json:"require_approval"`
|
||||
InviteCodeValidityDays *int `json:"invite_code_validity_days"` // 0=never, 1, 7, 30
|
||||
}
|
||||
|
||||
// AddMemberRequest represents a request to add a member to an organization
|
||||
type AddMemberRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Role OrgMemberRole `json:"role" binding:"required"`
|
||||
}
|
||||
|
||||
// UpdateMemberRoleRequest represents a request to update a member's role
|
||||
type UpdateMemberRoleRequest struct {
|
||||
Role OrgMemberRole `json:"role" binding:"required"`
|
||||
}
|
||||
|
||||
// JoinOrganizationRequest represents a request to join an organization via invite code
|
||||
type JoinOrganizationRequest struct {
|
||||
InviteCode string `json:"invite_code" binding:"required,min=8,max=32"`
|
||||
}
|
||||
|
||||
// SubmitJoinRequestRequest represents a request to submit a join request for approval
|
||||
type SubmitJoinRequestRequest struct {
|
||||
InviteCode string `json:"invite_code" binding:"required,min=8,max=32"`
|
||||
Message string `json:"message" binding:"max=500"`
|
||||
Role OrgMemberRole `json:"role"` // Optional: role the applicant requests (admin/editor/viewer); default viewer
|
||||
}
|
||||
|
||||
// ReviewJoinRequestRequest represents a request to review a join request
|
||||
type ReviewJoinRequestRequest struct {
|
||||
Approved bool `json:"approved"`
|
||||
Message string `json:"message" binding:"max=500"`
|
||||
Role OrgMemberRole `json:"role"` // Optional: role to assign when approving; overrides applicant's requested role
|
||||
}
|
||||
|
||||
// RequestRoleUpgradeRequest represents a request to upgrade role in an organization
|
||||
type RequestRoleUpgradeRequest struct {
|
||||
RequestedRole OrgMemberRole `json:"requested_role" binding:"required"` // The role user wants to upgrade to
|
||||
Message string `json:"message" binding:"max=500"` // Optional message explaining the reason
|
||||
}
|
||||
|
||||
// InviteMemberRequest represents a request to directly invite a user to organization
|
||||
type InviteMemberRequest struct {
|
||||
UserID string `json:"user_id" binding:"required"` // User ID to invite
|
||||
Role OrgMemberRole `json:"role" binding:"required"` // Role to assign: admin/editor/viewer
|
||||
}
|
||||
|
||||
// ShareKnowledgeBaseRequest represents a request to share a knowledge base
|
||||
type ShareKnowledgeBaseRequest struct {
|
||||
OrganizationID string `json:"organization_id" binding:"required"`
|
||||
Permission OrgMemberRole `json:"permission" binding:"required"`
|
||||
}
|
||||
|
||||
// UpdateSharePermissionRequest represents a request to update share permission
|
||||
type UpdateSharePermissionRequest struct {
|
||||
Permission OrgMemberRole `json:"permission" binding:"required"`
|
||||
}
|
||||
|
||||
// OrganizationResponse represents an organization in API responses
|
||||
type OrganizationResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar,omitempty"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
InviteCode string `json:"invite_code,omitempty"`
|
||||
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
|
||||
InviteCodeValidityDays int `json:"invite_code_validity_days"`
|
||||
RequireApproval bool `json:"require_approval"`
|
||||
MemberCount int `json:"member_count"`
|
||||
ShareCount int `json:"share_count"` // 共享到该组织的知识库数量
|
||||
PendingJoinRequestCount int `json:"pending_join_request_count"` // 待审批加入申请数(仅管理员可见)
|
||||
IsOwner bool `json:"is_owner"`
|
||||
MyRole string `json:"my_role,omitempty"`
|
||||
HasPendingUpgrade bool `json:"has_pending_upgrade"` // 当前用户是否有待处理的权限升级申请
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// OrganizationMemberResponse represents a member in API responses
|
||||
type OrganizationMemberResponse struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
}
|
||||
|
||||
// KnowledgeBaseShareResponse represents a share record in API responses
|
||||
type KnowledgeBaseShareResponse struct {
|
||||
ID string `json:"id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
KnowledgeBaseName string `json:"knowledge_base_name"`
|
||||
KnowledgeBaseType string `json:"knowledge_base_type"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
ChunkCount int64 `json:"chunk_count"`
|
||||
OrganizationID string `json:"organization_id"`
|
||||
OrganizationName string `json:"organization_name"`
|
||||
SharedByUserID string `json:"shared_by_user_id"`
|
||||
SharedByUsername string `json:"shared_by_username"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
Permission string `json:"permission"` // Share permission (what the space was granted: viewer/editor)
|
||||
MyRoleInOrg string `json:"my_role_in_org"` // Current user's role in this organization (admin/editor/viewer)
|
||||
MyPermission string `json:"my_permission"` // Effective permission for current user = min(Permission, MyRoleInOrg)
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
RequireApproval bool `json:"require_approval"`
|
||||
}
|
||||
|
||||
// ListOrganizationsResponse represents the response for listing organizations
|
||||
type ListOrganizationsResponse struct {
|
||||
Organizations []OrganizationResponse `json:"organizations"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// JoinRequestResponse represents a join request in API responses
|
||||
type JoinRequestResponse struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Message string `json:"message"`
|
||||
RequestType string `json:"request_type"` // 'join' or 'upgrade'
|
||||
PrevRole string `json:"prev_role"` // Previous role (only for upgrade requests)
|
||||
RequestedRole string `json:"requested_role"` // Role the applicant requested (admin/editor/viewer)
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at,omitempty"`
|
||||
}
|
||||
|
||||
// ListJoinRequestsResponse represents the response for listing join requests
|
||||
type ListJoinRequestsResponse struct {
|
||||
Requests []JoinRequestResponse `json:"requests"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// ListMembersResponse represents the response for listing members
|
||||
type ListMembersResponse struct {
|
||||
Members []OrganizationMemberResponse `json:"members"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// ListSharesResponse represents the response for listing shares
|
||||
type ListSharesResponse struct {
|
||||
Shares []KnowledgeBaseShareResponse `json:"shares"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
@@ -22,6 +22,9 @@ type SearchTarget struct {
|
||||
Type SearchTargetType `json:"type"`
|
||||
// KnowledgeBaseID is the ID of the knowledge base to search
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
// TenantID is the tenant ID that owns this knowledge base
|
||||
// Required for cross-tenant shared KB queries
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
// KnowledgeIDs is the list of specific knowledge IDs to search within the knowledge base
|
||||
// Only used when Type is SearchTargetTypeKnowledge
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
@@ -43,6 +46,38 @@ func (st SearchTargets) GetAllKnowledgeBaseIDs() []string {
|
||||
return result
|
||||
}
|
||||
|
||||
// GetKBTenantMap returns a map from knowledge base ID to tenant ID
|
||||
func (st SearchTargets) GetKBTenantMap() map[string]uint64 {
|
||||
result := make(map[string]uint64)
|
||||
for _, t := range st {
|
||||
if t.KnowledgeBaseID != "" {
|
||||
result[t.KnowledgeBaseID] = t.TenantID
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetTenantIDForKB returns the tenant ID for a given knowledge base ID
|
||||
// Returns 0 if not found
|
||||
func (st SearchTargets) GetTenantIDForKB(kbID string) uint64 {
|
||||
for _, t := range st {
|
||||
if t.KnowledgeBaseID == kbID {
|
||||
return t.TenantID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ContainsKB checks if the search targets contain a given knowledge base ID
|
||||
func (st SearchTargets) ContainsKB(kbID string) bool {
|
||||
for _, t := range st {
|
||||
if t.KnowledgeBaseID == kbID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SearchResult represents the search result
|
||||
type SearchResult struct {
|
||||
// ID
|
||||
|
||||
Reference in New Issue
Block a user