feat(wiki): implement folder management features in wiki API

Add new API functions for managing wiki folders, including creating, updating, deleting, and listing folders. Introduce a new WikiFolder interface to represent folder structure and enhance the WikiBrowser component with folder actions. Update internationalization strings for folder-related actions in English, Korean, Russian, and Chinese locales. Refactor existing code to accommodate folder hierarchy and improve user experience in the wiki browser.
This commit is contained in:
wizardchen
2026-06-16 23:48:35 +08:00
committed by lyingbug
parent 83eeec0ddf
commit e76738d054
24 changed files with 1903 additions and 399 deletions
+68 -15
View File
@@ -156,17 +156,43 @@ type WikiPageService interface {
// merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
// ListDistinctCategoryPaths returns unique non-empty category_path
// values from entity/concept pages. Used by wiki ingest to inject
// established folder taxonomy into extraction prompts.
// ListDistinctCategoryPaths returns the existing wiki folder paths (split
// into segments), capped at maxPaths. Used by wiki ingest's taxonomy
// planner as the pool of folders to reuse.
ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error)
// ListDistinctCategoryPathsByType returns the direct child folders of
// parentPath for the given page types (with per-child page counts),
// paginated. The second return value is the total number of distinct
// child folders before pagination. Used by the wiki browser to render the
// directory tree level by level.
ListDistinctCategoryPathsByType(ctx context.Context, kbID string, pageTypes []string, parentPath []string, page, pageSize int) ([]types.WikiCategoryPath, int, error)
// --- Folder tree (wiki_folders) ---
// ListChildFolders returns the direct child folders of parentID ("" =
// root) relevant to the given page types, each enriched with a recursive
// page count (the folder's whole subtree, restricted to pageTypes) and
// whether it has relevant sub-folders. A folder is shown when its subtree
// holds at least one page of pageTypes, or when it is entirely empty (a
// user-created container with no pages of any type). When pageTypes is
// empty every type counts.
ListChildFolders(
ctx context.Context, kbID string, parentID string, pageTypes []string,
) ([]types.WikiFolderNode, error)
// GetFolder retrieves a single folder by id.
GetFolder(ctx context.Context, kbID string, id string) (*types.WikiFolder, error)
// CreateFolder creates a new (initially empty) folder under parentID and
// returns it. Fails if a sibling with the same name already exists.
CreateFolder(ctx context.Context, kbID string, tenantID uint64, parentID string, name string) (*types.WikiFolder, error)
// RenameOrMoveFolder renames and/or reparents a folder, recomputing the
// materialized path/depth of the whole subtree and the cached paths of
// every page underneath. Returns the updated folder.
RenameOrMoveFolder(ctx context.Context, kbID string, id string, newName string, newParentID string, moveParent bool) (*types.WikiFolder, error)
// DeleteFolder removes an empty folder. Fails if it still contains pages
// or child folders (the UI must move or delete contents first).
DeleteFolder(ctx context.Context, kbID string, id string) error
// FindOrCreateFolderPath resolves a category path (e.g. ["AI","RAG"]) to a
// folder id, creating any missing intermediate folders. Returns the leaf
// folder id and the canonical (cleaned) path. An empty/blank path resolves
// to the root ("").
FindOrCreateFolderPath(ctx context.Context, kbID string, tenantID uint64, path []string) (string, []string, error)
// MovePage relocates a page into folderID ("" = root), recomputing its
// cached category path. Returns the updated page.
MovePage(ctx context.Context, kbID string, slug string, folderID string) (*types.WikiPage, error)
// CountByType returns page counts grouped by type for a knowledge
// base. Re-exposed at the service layer so the index intro
@@ -276,14 +302,41 @@ type WikiPageRepository interface {
// surface candidate merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
// ListDistinctCategoryPaths scans entity/concept pages and returns
// unique non-empty category_path values for wiki ingest prompts.
// ListDistinctCategoryPaths returns the materialized paths of existing
// wiki folders (split into segments), capped at maxPaths. Used by the
// wiki ingest taxonomy planner as the pool of folders to reuse.
ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error)
// ListDistinctCategoryPathsByType returns the direct child folders of
// parentPath for the given page types (with per-child page counts),
// paginated, plus the total number of distinct child folders.
ListDistinctCategoryPathsByType(ctx context.Context, kbID string, pageTypes []string, parentPath []string, page, pageSize int) ([]types.WikiCategoryPath, int, error)
// --- Folder tree (wiki_folders) ---
// CreateFolder inserts a new directory node.
CreateFolder(ctx context.Context, folder *types.WikiFolder) error
// GetFolderByID retrieves a folder by id within a knowledge base.
GetFolderByID(ctx context.Context, kbID string, id string) (*types.WikiFolder, error)
// GetChildFolderByName returns the live child folder of parentID with the
// given name, or ErrWikiFolderNotFound. Used by find-or-create.
GetChildFolderByName(ctx context.Context, kbID string, parentID string, name string) (*types.WikiFolder, error)
// ListChildFolders returns the direct child folders of parentID, ordered
// by sort_order then name.
ListChildFolders(ctx context.Context, kbID string, parentID string) ([]*types.WikiFolder, error)
// ListAllFolders returns every folder in the knowledge base.
ListAllFolders(ctx context.Context, kbID string) ([]*types.WikiFolder, error)
// UpdateFolder rewrites a folder's mutable fields (name, parent_id, path,
// depth, sort_order, updated_at).
UpdateFolder(ctx context.Context, folder *types.WikiFolder) error
// DeleteFolder soft-deletes a folder by id.
DeleteFolder(ctx context.Context, kbID string, id string) error
// CountPagesInFolder returns the number of live (non-archived) pages
// directly in the folder (folder_id = id).
CountPagesInFolder(ctx context.Context, kbID string, folderID string) (int64, error)
// CountPagesByFolder returns live (non-archived) page counts grouped by
// folder_id. When pageTypes is non-empty the count is restricted to those
// page types; otherwise all types are counted. Pages at the wiki root carry
// the empty-string key.
CountPagesByFolder(ctx context.Context, kbID string, pageTypes []string) (map[string]int64, error)
// ListPagesByFolderIDs returns all pages whose folder_id is in the set.
// Used to recompute cached paths when a folder subtree is moved/renamed.
ListPagesByFolderIDs(ctx context.Context, kbID string, folderIDs []string) ([]*types.WikiPage, error)
// ListAll retrieves all wiki pages in a knowledge base (for link rebuilding, graph generation).
ListAll(ctx context.Context, kbID string) ([]*types.WikiPage, error)
+77 -39
View File
@@ -88,21 +88,6 @@ func SplitWikiPageTypes(raw string) []string {
return out
}
// WikiCategoryLevels flattens a (already cleaned) category path into the three
// fixed level columns used for SQL grouping. Missing levels yield "".
func WikiCategoryLevels(path []string) (l1, l2, l3 string) {
if len(path) > 0 {
l1 = path[0]
}
if len(path) > 1 {
l2 = path[1]
}
if len(path) > 2 {
l3 = path[2]
}
return l1, l2, l3
}
func isWikiTypeCategoryLabel(label string) bool {
normalized := strings.ToLower(strings.TrimSpace(label))
normalized = strings.TrimSuffix(normalized, "s")
@@ -182,11 +167,17 @@ type WikiPage struct {
Aliases StringArray `json:"aliases" gorm:"type:json"`
// ParentSlug optionally points at the wiki page that should act as this
// page's semantic parent in the directory tree. The parent may be empty
// when the page is grouped only by CategoryPath.
// when the page is grouped only by FolderID.
ParentSlug string `json:"parent_slug,omitempty" gorm:"type:varchar(255);index"`
// FolderID is the single source of truth for where this page sits in the
// directory tree — a reference to wiki_folders.id ("" = wiki root). The
// CategoryPath / WikiPath / Depth fields below are denormalized caches
// recomputed from this folder's chain on every write so list/index/search
// queries don't have to join wiki_folders.
FolderID string `json:"folder_id,omitempty" gorm:"column:folder_id;type:varchar(36);index;default:''"`
// CategoryPath is the directory breadcrumb that groups this page in the
// wiki browser, e.g. ["AI", "LLM 应用", "RAG"]. It is intentionally
// label-based so intermediate directory nodes do not need to be real pages.
// wiki browser, e.g. ["AI", "LLM 应用", "RAG"]. Derived cache of the
// folder chain identified by FolderID.
CategoryPath StringArray `json:"category_path,omitempty" gorm:"type:json"`
// WikiPath is a normalized, sortable path derived from page_type,
// category_path, and title. It keeps large directory listings cheap to sort.
@@ -196,13 +187,6 @@ type WikiPage struct {
// SortOrder allows generated or manually edited pages to control sibling
// ordering before falling back to title.
SortOrder int `json:"sort_order,omitempty" gorm:"default:0;index"`
// CategoryL1/L2/L3 mirror CategoryPath[0..2] as flat columns. They exist
// solely so the directory-listing query can GROUP BY / paginate folders in
// plain, cross-dialect SQL (no JSON parsing). They are NOT part of the API
// surface (hence json:"-") and are kept in sync by normalizeWikiHierarchy.
CategoryL1 string `json:"-" gorm:"column:category_l1;type:varchar(255);default:''"`
CategoryL2 string `json:"-" gorm:"column:category_l2;type:varchar(255);default:''"`
CategoryL3 string `json:"-" gorm:"column:category_l3;type:varchar(255);default:''"`
// References to source knowledge IDs that contributed to this page.
// Format matches the legacy "<knowledge_id>|<doc_title>" convention used
// across the ingest pipeline, so retract / display code can split on `|`
@@ -241,6 +225,73 @@ func (WikiPage) TableName() string {
return "wiki_pages"
}
// WikiFolderRootID is the sentinel parent/folder id meaning "the wiki root"
// (a page or folder directly under the top level, with no parent folder).
const WikiFolderRootID = ""
// WikiFolder is a first-class directory node in the wiki browser. Folders
// exist independently of pages — an empty folder persists so users can lay
// out a skeleton and file pages into it later. The tree is an adjacency list
// (ParentID, "" = root); Path is the materialized "/"-joined name chain kept
// purely for cheap display/sort. A wiki page's placement is WikiPage.FolderID.
type WikiFolder struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"index"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
ParentID string `json:"parent_id" gorm:"column:parent_id;type:varchar(36);index;default:''"`
Name string `json:"name" gorm:"type:varchar(255)"`
Path string `json:"path" gorm:"type:varchar(1024)"`
Depth int `json:"depth" gorm:"default:0"`
SortOrder int `json:"sort_order" gorm:"default:0"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// TableName specifies the database table name
func (WikiFolder) TableName() string {
return "wiki_folders"
}
// WikiFolderNode is one directory node returned to the browser, enriched with
// the live page count directly under it and whether it has child folders so
// the UI can render an expand affordance without a second round-trip.
type WikiFolderNode struct {
WikiFolder
PageCount int64 `json:"page_count"`
HasChildren bool `json:"has_children"`
}
// WikiFolderListResponse is the payload for listing the direct children of a
// folder (parent_id="" = root level).
type WikiFolderListResponse struct {
ParentID string `json:"parent_id"`
Folders []WikiFolderNode `json:"folders"`
}
// WikiFolderCreateRequest creates a new (initially empty) folder under ParentID.
type WikiFolderCreateRequest struct {
ParentID string `json:"parent_id"`
Name string `json:"name"`
}
// WikiFolderUpdateRequest renames and/or reparents a folder. ParentID is
// applied only when MoveParent is true so a pure rename doesn't have to
// re-send the (possibly root "") parent and risk an accidental move.
type WikiFolderUpdateRequest struct {
Name string `json:"name,omitempty"`
ParentID string `json:"parent_id,omitempty"`
MoveParent bool `json:"move_parent,omitempty"`
}
// WikiPageMoveRequest relocates the page identified by Slug into FolderID
// ("" = root). Slug is carried in the body (not the path) because wiki slugs
// are hierarchical ("entity/acme") and would collide with gin's catch-all.
type WikiPageMoveRequest struct {
Slug string `json:"slug" binding:"required"`
FolderID string `json:"folder_id"`
}
// WikiExtractionGranularity controls how aggressive Pass 0 (candidate slug
// extraction) is. Higher granularity = more slugs, lower = tighter focus on
// the document's main subjects.
@@ -368,6 +419,7 @@ type WikiPageListRequest struct {
PageType string `json:"page_type,omitempty"` // filter by type
Status string `json:"status,omitempty"` // filter by status
Query string `json:"query,omitempty"` // full-text search
FolderID *string `json:"folder_id,omitempty"` // exact folder placement ("" = root)
CategoryPath StringArray `json:"category_path,omitempty"` // exact directory path
CategoryDepth *int `json:"category_depth,omitempty"` // exact directory depth, including 0 for root
Page int `json:"page,omitempty"` // pagination page (1-based)
@@ -385,20 +437,6 @@ type WikiPageListResponse struct {
TotalPages int `json:"total_pages"`
}
// WikiCategoryPathListResponse returns the directory skeleton for wiki pages.
type WikiCategoryPathListResponse struct {
Paths []WikiCategoryPath `json:"paths"`
Total int `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalPages int `json:"total_pages"`
}
// WikiCategoryPath is one directory node in the wiki sidebar skeleton.
type WikiCategoryPath struct {
Path []string `json:"path"`
Count int64 `json:"count"`
}
// WikiGraphMode enumerates the graph query modes exposed to the API.
const (