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:
@@ -109,10 +109,8 @@ func (r *wikiPageRepository) UpdateMeta(ctx context.Context, page *types.WikiPag
|
||||
"chunk_refs": page.ChunkRefs,
|
||||
"page_metadata": page.PageMetadata,
|
||||
"parent_slug": page.ParentSlug,
|
||||
"folder_id": page.FolderID,
|
||||
"category_path": page.CategoryPath,
|
||||
"category_l1": page.CategoryL1,
|
||||
"category_l2": page.CategoryL2,
|
||||
"category_l3": page.CategoryL3,
|
||||
"wiki_path": page.WikiPath,
|
||||
"depth": page.Depth,
|
||||
"sort_order": page.SortOrder,
|
||||
@@ -180,6 +178,9 @@ func (r *wikiPageRepository) List(ctx context.Context, req *types.WikiPageListRe
|
||||
// whose stored text is json.Marshal of the cleaned path, so we compare
|
||||
// against the same encoding. Postgres needs an explicit jsonb cast for array
|
||||
// equality; SQLite stores JSON as TEXT and compares directly.
|
||||
if req.FolderID != nil {
|
||||
query = query.Where("folder_id = ?", *req.FolderID)
|
||||
}
|
||||
if req.CategoryDepth != nil {
|
||||
query = query.Where("depth = ?", *req.CategoryDepth)
|
||||
}
|
||||
@@ -414,13 +415,11 @@ func (r *wikiPageRepository) ListBySlugs(
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListDistinctCategoryPaths returns the distinct non-empty category paths used
|
||||
// by entity/concept pages. The distinctness is pushed entirely to SQL over the
|
||||
// flat category_l1/l2/l3 columns (indexed by idx_wiki_pages_category_levels),
|
||||
// so the cost scales with the number of distinct folders — not the page count —
|
||||
// and there is no full-table scan to bound. maxPaths caps the returned folder
|
||||
// count. Used by the batch taxonomy planner as the candidate pool of existing
|
||||
// folders to reuse (similarity preprocessing then narrows it per batch).
|
||||
// ListDistinctCategoryPaths returns the materialized paths of existing wiki
|
||||
// folders (split into segments), ordered by path and capped at maxPaths. Used
|
||||
// by the batch taxonomy planner as the candidate pool of folders to reuse
|
||||
// (similarity preprocessing then narrows it per batch). The folder tree is the
|
||||
// single source of truth, so this no longer scans page rows.
|
||||
func (r *wikiPageRepository) ListDistinctCategoryPaths(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
@@ -429,123 +428,175 @@ func (r *wikiPageRepository) ListDistinctCategoryPaths(
|
||||
if maxPaths <= 0 {
|
||||
maxPaths = 150
|
||||
}
|
||||
|
||||
type row struct {
|
||||
L1 string `gorm:"column:category_l1"`
|
||||
L2 string `gorm:"column:category_l2"`
|
||||
L3 string `gorm:"column:category_l3"`
|
||||
}
|
||||
var rows []row
|
||||
var paths []string
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.WikiPage{}).
|
||||
Distinct("category_l1", "category_l2", "category_l3").
|
||||
Where("knowledge_base_id = ? AND page_type IN ? AND status <> ? AND category_l1 <> ?",
|
||||
kbID,
|
||||
[]string{types.WikiPageTypeEntity, types.WikiPageTypeConcept},
|
||||
types.WikiPageStatusArchived,
|
||||
"",
|
||||
).
|
||||
Order("category_l1 ASC").
|
||||
Order("category_l2 ASC").
|
||||
Order("category_l3 ASC").
|
||||
Model(&types.WikiFolder{}).
|
||||
Where("knowledge_base_id = ? AND path <> ?", kbID, "").
|
||||
Order("path ASC").
|
||||
Limit(maxPaths).
|
||||
Scan(&rows).Error; err != nil {
|
||||
Pluck("path", &paths).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out := make([][]string, 0, len(rows))
|
||||
for _, rw := range rows {
|
||||
path := make([]string, 0, 3)
|
||||
for _, label := range []string{rw.L1, rw.L2, rw.L3} {
|
||||
if label == "" {
|
||||
break // levels are contiguous; an empty level ends the path
|
||||
}
|
||||
path = append(path, label)
|
||||
}
|
||||
if len(path) > 0 {
|
||||
out = append(out, path)
|
||||
out := make([][]string, 0, len(paths))
|
||||
for _, p := range paths {
|
||||
if seg := types.CleanWikiCategoryPath(strings.Split(p, "/")); len(seg) > 0 {
|
||||
out = append(out, seg)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// wikiCategoryLevelColumns maps a parent depth (0/1/2) to the flat level column
|
||||
// holding that depth's direct child. Depth >= WikiCategoryMaxDepth has no child.
|
||||
var wikiCategoryLevelColumns = []string{"category_l1", "category_l2", "category_l3"}
|
||||
// --- Folder tree (wiki_folders) ---
|
||||
|
||||
// ListDistinctCategoryPathsByType returns the DIRECT child folders of
|
||||
// parentPath for the given page types, with the page count under each child,
|
||||
// paginated. Grouping and pagination are pushed entirely to SQL over the flat
|
||||
// category_l1/l2/l3 columns (kept in sync by normalizeWikiHierarchy), so this
|
||||
// is cheap, indexable, and identical across Postgres and SQLite — no JSON
|
||||
// parsing and no full in-memory scan. The second return value is the total
|
||||
// number of distinct child folders (before pagination).
|
||||
func (r *wikiPageRepository) ListDistinctCategoryPathsByType(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
pageTypes []string,
|
||||
parentPath []string,
|
||||
page, pageSize int,
|
||||
) ([]types.WikiCategoryPath, int, error) {
|
||||
if len(pageTypes) == 0 {
|
||||
return nil, 0, nil
|
||||
}
|
||||
parent := types.CleanWikiCategoryPath(parentPath)
|
||||
if len(parent) >= len(wikiCategoryLevelColumns) {
|
||||
return nil, 0, nil // no level deeper than the cap can exist
|
||||
}
|
||||
childCol := wikiCategoryLevelColumns[len(parent)]
|
||||
// ErrWikiFolderNotFound is returned when a wiki folder is not found.
|
||||
var ErrWikiFolderNotFound = errors.New("wiki folder not found")
|
||||
|
||||
// Build the shared WHERE as a closure so the count and the page query each
|
||||
// start from a fresh statement (GORM chains mutate in place otherwise).
|
||||
scoped := func() *gorm.DB {
|
||||
q := r.db.WithContext(ctx).
|
||||
Model(&types.WikiPage{}).
|
||||
Where("knowledge_base_id = ? AND page_type IN ? AND status <> ?",
|
||||
kbID, pageTypes, types.WikiPageStatusArchived).
|
||||
Where(childCol+" <> ?", "")
|
||||
for i, label := range parent {
|
||||
q = q.Where(wikiCategoryLevelColumns[i]+" = ?", label)
|
||||
// ErrWikiFolderConflict is returned when a sibling folder with the same name
|
||||
// already exists under the same parent.
|
||||
var ErrWikiFolderConflict = errors.New("wiki folder name conflict")
|
||||
|
||||
func (r *wikiPageRepository) CreateFolder(ctx context.Context, folder *types.WikiFolder) error {
|
||||
return r.db.WithContext(ctx).Create(folder).Error
|
||||
}
|
||||
|
||||
func (r *wikiPageRepository) GetFolderByID(ctx context.Context, kbID string, id string) (*types.WikiFolder, error) {
|
||||
var folder types.WikiFolder
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND id = ?", kbID, id).
|
||||
First(&folder).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrWikiFolderNotFound
|
||||
}
|
||||
return q
|
||||
return nil, err
|
||||
}
|
||||
return &folder, nil
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := scoped().Distinct(childCol).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if total == 0 {
|
||||
return nil, 0, nil
|
||||
func (r *wikiPageRepository) GetChildFolderByName(
|
||||
ctx context.Context, kbID string, parentID string, name string,
|
||||
) (*types.WikiFolder, error) {
|
||||
var folder types.WikiFolder
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND parent_id = ? AND name = ?", kbID, parentID, name).
|
||||
First(&folder).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrWikiFolderNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &folder, nil
|
||||
}
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 2000
|
||||
func (r *wikiPageRepository) ListChildFolders(
|
||||
ctx context.Context, kbID string, parentID string,
|
||||
) ([]*types.WikiFolder, error) {
|
||||
var folders []*types.WikiFolder
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND parent_id = ?", kbID, parentID).
|
||||
Order("sort_order ASC").
|
||||
Order("name ASC").
|
||||
Find(&folders).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return folders, nil
|
||||
}
|
||||
|
||||
type row struct {
|
||||
Label string `gorm:"column:label"`
|
||||
Cnt int64 `gorm:"column:cnt"`
|
||||
}
|
||||
var rows []row
|
||||
if err := scoped().
|
||||
Select(childCol + " AS label, COUNT(*) AS cnt").
|
||||
Group(childCol).
|
||||
Order("label ASC").
|
||||
Offset((page - 1) * pageSize).
|
||||
Limit(pageSize).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
func (r *wikiPageRepository) ListAllFolders(ctx context.Context, kbID string) ([]*types.WikiFolder, error) {
|
||||
var folders []*types.WikiFolder
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Order("depth ASC").
|
||||
Order("path ASC").
|
||||
Find(&folders).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return folders, nil
|
||||
}
|
||||
|
||||
out := make([]types.WikiCategoryPath, 0, len(rows))
|
||||
for _, rw := range rows {
|
||||
full := append(append([]string(nil), parent...), rw.Label)
|
||||
out = append(out, types.WikiCategoryPath{Path: full, Count: rw.Cnt})
|
||||
func (r *wikiPageRepository) UpdateFolder(ctx context.Context, folder *types.WikiFolder) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Model(&types.WikiFolder{}).
|
||||
Where("id = ?", folder.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"parent_id": folder.ParentID,
|
||||
"name": folder.Name,
|
||||
"path": folder.Path,
|
||||
"depth": folder.Depth,
|
||||
"sort_order": folder.SortOrder,
|
||||
"updated_at": folder.UpdatedAt,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
return out, int(total), nil
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrWikiFolderNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *wikiPageRepository) DeleteFolder(ctx context.Context, kbID string, id string) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND id = ?", kbID, id).
|
||||
Delete(&types.WikiFolder{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrWikiFolderNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *wikiPageRepository) CountPagesInFolder(ctx context.Context, kbID string, folderID string) (int64, error) {
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.WikiPage{}).
|
||||
Where("knowledge_base_id = ? AND folder_id = ? AND status <> ?",
|
||||
kbID, folderID, types.WikiPageStatusArchived).
|
||||
Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r *wikiPageRepository) CountPagesByFolder(
|
||||
ctx context.Context, kbID string, pageTypes []string,
|
||||
) (map[string]int64, error) {
|
||||
type folderCount struct {
|
||||
FolderID string
|
||||
Cnt int64
|
||||
}
|
||||
var rows []folderCount
|
||||
q := r.db.WithContext(ctx).
|
||||
Model(&types.WikiPage{}).
|
||||
Select("folder_id, COUNT(*) as cnt").
|
||||
Where("knowledge_base_id = ? AND status <> ?", kbID, types.WikiPageStatusArchived)
|
||||
if len(pageTypes) > 0 {
|
||||
q = q.Where("page_type IN ?", pageTypes)
|
||||
}
|
||||
if err := q.Group("folder_id").Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]int64, len(rows))
|
||||
for _, row := range rows {
|
||||
out[row.FolderID] = row.Cnt
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *wikiPageRepository) ListPagesByFolderIDs(
|
||||
ctx context.Context, kbID string, folderIDs []string,
|
||||
) ([]*types.WikiPage, error) {
|
||||
if len(folderIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var pages []*types.WikiPage
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND folder_id IN ?", kbID, folderIDs).
|
||||
Find(&pages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
// ListSummariesByKnowledgeIDs returns summary-page content keyed by the
|
||||
|
||||
@@ -30,13 +30,11 @@ CREATE TABLE IF NOT EXISTS wiki_pages (
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
parent_slug VARCHAR(255) NOT NULL DEFAULT '',
|
||||
folder_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||
category_path TEXT DEFAULT '[]',
|
||||
wiki_path VARCHAR(1024) NOT NULL DEFAULT '',
|
||||
depth INTEGER NOT NULL DEFAULT 0,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
category_l1 VARCHAR(255) NOT NULL DEFAULT '',
|
||||
category_l2 VARCHAR(255) NOT NULL DEFAULT '',
|
||||
category_l3 VARCHAR(255) NOT NULL DEFAULT '',
|
||||
source_refs TEXT DEFAULT '[]',
|
||||
chunk_refs TEXT DEFAULT '[]',
|
||||
in_links TEXT DEFAULT '[]',
|
||||
@@ -50,11 +48,29 @@ CREATE TABLE IF NOT EXISTS wiki_pages (
|
||||
);
|
||||
`
|
||||
|
||||
// wikiFoldersTestDDL mirrors the production wiki_folders DDL for SQLite.
|
||||
const wikiFoldersTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS wiki_folders (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL DEFAULT 0,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
parent_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||
name VARCHAR(255) NOT NULL,
|
||||
path VARCHAR(1024) NOT NULL DEFAULT '',
|
||||
depth INTEGER NOT NULL DEFAULT 0,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
func setupWikiPagesTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(wikiPagesTestDDL).Error)
|
||||
require.NoError(t, db.Exec(wikiFoldersTestDDL).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
@@ -89,9 +105,6 @@ func makeCategorizedWikiPage(kbID, slug, pageType, status string, categoryPath .
|
||||
if len(categoryPath) > 0 {
|
||||
page.WikiPath = pageType + "/" + strings.Join(categoryPath, "/") + "/" + page.Title
|
||||
page.Depth = len(categoryPath)
|
||||
// Mirror the flat level columns the directory query groups on, the same
|
||||
// way normalizeWikiHierarchy would on a real write.
|
||||
page.CategoryL1, page.CategoryL2, page.CategoryL3 = types.WikiCategoryLevels(categoryPath)
|
||||
}
|
||||
return page
|
||||
}
|
||||
@@ -130,57 +143,68 @@ func TestList_WikiPathSortReturnsCategorizedPagesFirst(t *testing.T) {
|
||||
assert.Equal(t, "entity/001-root", got[2].Slug)
|
||||
}
|
||||
|
||||
// TestListDistinctCategoryPathsByType_GroupsAndPaginatesInSQL verifies the
|
||||
// directory listing groups direct child folders, counts pages under each
|
||||
// (including deeper pages), and paginates — all pushed to SQL over the flat
|
||||
// level columns, so it must behave identically on SQLite.
|
||||
func TestListDistinctCategoryPathsByType_GroupsAndPaginatesInSQL(t *testing.T) {
|
||||
// TestFolderTree_CRUDAndChildListing exercises the wiki_folders repository:
|
||||
// child listing ordered by sort_order/name, find-by-name, page counting under
|
||||
// a folder, and that ListDistinctCategoryPaths reflects the folder paths.
|
||||
func TestFolderTree_CRUDAndChildListing(t *testing.T) {
|
||||
db := setupWikiPagesTestDB(t)
|
||||
repo := NewWikiPageRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
pages := []*types.WikiPage{
|
||||
makeCategorizedWikiPage("kb-c", "entity/a1", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI"),
|
||||
makeCategorizedWikiPage("kb-c", "entity/a2", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI"),
|
||||
makeCategorizedWikiPage("kb-c", "entity/a3", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI", "LLM"),
|
||||
makeCategorizedWikiPage("kb-c", "entity/p1", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "人物"),
|
||||
makeWikiPage("kb-c", "entity/root", types.WikiPageTypeEntity, types.WikiPageStatusPublished),
|
||||
makeCategorizedWikiPage("kb-c", "entity/arch", types.WikiPageTypeEntity, types.WikiPageStatusArchived, "AI"),
|
||||
mk := func(id, parentID, name, path string, depth int) *types.WikiFolder {
|
||||
return &types.WikiFolder{
|
||||
ID: id, TenantID: 1, KnowledgeBaseID: "kb-f",
|
||||
ParentID: parentID, Name: name, Path: path, Depth: depth,
|
||||
CreatedAt: time.Now(), UpdatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
for _, p := range pages {
|
||||
ai := mk("f-ai", types.WikiFolderRootID, "AI", "AI", 1)
|
||||
people := mk("f-people", types.WikiFolderRootID, "人物", "人物", 1)
|
||||
llm := mk("f-llm", "f-ai", "LLM", "AI/LLM", 2)
|
||||
for _, f := range []*types.WikiFolder{ai, people, llm} {
|
||||
require.NoError(t, repo.CreateFolder(ctx, f))
|
||||
}
|
||||
|
||||
// Root children: AI, 人物 (ordered by name within equal sort_order).
|
||||
roots, err := repo.ListChildFolders(ctx, "kb-f", types.WikiFolderRootID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, roots, 2)
|
||||
|
||||
// Direct child of AI is LLM.
|
||||
child, err := repo.GetChildFolderByName(ctx, "kb-f", "f-ai", "LLM")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "f-llm", child.ID)
|
||||
|
||||
// Missing child surfaces the typed not-found error.
|
||||
_, err = repo.GetChildFolderByName(ctx, "kb-f", "f-ai", "Nope")
|
||||
assert.ErrorIs(t, err, ErrWikiFolderNotFound)
|
||||
|
||||
// Pages filed into folders are counted (archived excluded).
|
||||
pAI := makeCategorizedWikiPage("kb-f", "entity/a1", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI")
|
||||
pAI.FolderID = "f-ai"
|
||||
pLLM := makeCategorizedWikiPage("kb-f", "entity/a2", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI", "LLM")
|
||||
pLLM.FolderID = "f-llm"
|
||||
pArch := makeCategorizedWikiPage("kb-f", "entity/a3", types.WikiPageTypeEntity, types.WikiPageStatusArchived, "AI")
|
||||
pArch.FolderID = "f-ai"
|
||||
for _, p := range []*types.WikiPage{pAI, pLLM, pArch} {
|
||||
require.NoError(t, repo.Create(ctx, p))
|
||||
}
|
||||
|
||||
types4 := []string{types.WikiPageTypeEntity}
|
||||
|
||||
// Root level: two folders (AI, 人物); the loose root page and archived page
|
||||
// are excluded. AI counts all 3 non-archived pages whose first level is AI.
|
||||
roots, total, err := repo.ListDistinctCategoryPathsByType(ctx, "kb-c", types4, nil, 1, 100)
|
||||
aiCount, err := repo.CountPagesInFolder(ctx, "kb-f", "f-ai")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, total)
|
||||
require.Len(t, roots, 2)
|
||||
byLabel := map[string]int64{}
|
||||
for _, p := range roots {
|
||||
require.Len(t, p.Path, 1)
|
||||
byLabel[p.Path[0]] = p.Count
|
||||
}
|
||||
assert.Equal(t, int64(3), byLabel["AI"])
|
||||
assert.Equal(t, int64(1), byLabel["人物"])
|
||||
assert.Equal(t, int64(1), aiCount, "archived page excluded; LLM page is under f-llm, not f-ai")
|
||||
|
||||
// Child of [AI]: only the [AI, LLM] page.
|
||||
children, total, err := repo.ListDistinctCategoryPathsByType(ctx, "kb-c", types4, []string{"AI"}, 1, 100)
|
||||
// ListDistinctCategoryPaths returns the folder paths split into segments.
|
||||
paths, err := repo.ListDistinctCategoryPaths(ctx, "kb-f", 100)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, total)
|
||||
require.Len(t, children, 1)
|
||||
assert.Equal(t, []string{"AI", "LLM"}, children[0].Path)
|
||||
assert.Equal(t, int64(1), children[0].Count)
|
||||
assert.Contains(t, paths, []string{"AI"})
|
||||
assert.Contains(t, paths, []string{"AI", "LLM"})
|
||||
assert.Contains(t, paths, []string{"人物"})
|
||||
|
||||
// Pagination: page size 1 over the two root folders returns one row but the
|
||||
// total still reflects both distinct folders.
|
||||
firstPage, total, err := repo.ListDistinctCategoryPathsByType(ctx, "kb-c", types4, nil, 1, 1)
|
||||
// Pages can be fetched by their folder ids for subtree recompute.
|
||||
pages, err := repo.ListPagesByFolderIDs(ctx, "kb-f", []string{"f-ai", "f-llm"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, total)
|
||||
require.Len(t, firstPage, 1)
|
||||
assert.Len(t, pages, 3)
|
||||
}
|
||||
|
||||
// TestListByTypeLight_ProjectsNarrowColumnsAndExcludesArchived verifies
|
||||
|
||||
@@ -659,12 +659,15 @@ type WikiBatchContext struct {
|
||||
// three valid values.
|
||||
ExtractionGranularity types.WikiExtractionGranularity
|
||||
|
||||
// PlannedCategory holds the per-slug directory path assigned by the batch
|
||||
// taxonomy planning pass (planBatchTaxonomy), keyed by page slug. Reduce
|
||||
// applies it only to pages that don't already have a category, so the whole
|
||||
// batch lands on one coherent tree without churning user-curated pages.
|
||||
// Populated before the reduce phase and read-only during it.
|
||||
PlannedCategory map[string][]string
|
||||
// PlannedFolderID holds the per-slug wiki_folders.id assigned by the batch
|
||||
// taxonomy planning pass (planBatchTaxonomy + folder resolution), keyed by
|
||||
// page slug. Reduce applies it only to pages that aren't already filed
|
||||
// (FolderID == ""), so the whole batch lands on one coherent tree without
|
||||
// churning user-curated placements. The folders themselves are created
|
||||
// sequentially before reduce, so the parallel reduce phase only assigns
|
||||
// pre-resolved ids and never races on folder creation. Read-only during
|
||||
// reduce.
|
||||
PlannedFolderID map[string]string
|
||||
}
|
||||
|
||||
// SlugUpdate represents a single update operation for a specific slug
|
||||
|
||||
@@ -490,7 +490,8 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
// single pass assigns every new entity/concept slug a coherent category_path
|
||||
// that reuses existing folders. Reduce then only applies the plan to pages
|
||||
// that don't already have a category (user-curated pages are never churned).
|
||||
batchCtx.PlannedCategory = s.planBatchTaxonomy(ctx, chatModel, kb, slugUpdates, lang)
|
||||
batchCtx.PlannedFolderID = s.resolvePlannedFolders(ctx, kb,
|
||||
s.planBatchTaxonomy(ctx, chatModel, kb, slugUpdates, lang))
|
||||
|
||||
// 2. REDUCE PHASE (Parallel upserting grouped by Slug)
|
||||
egReduce, reduceCtx := errgroup.WithContext(ctx)
|
||||
@@ -1637,13 +1638,14 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
||||
}
|
||||
}
|
||||
|
||||
// Apply the batch taxonomy plan, but only to pages that don't already have a
|
||||
// category — so brand-new pages get filed coherently while previously-filed
|
||||
// or user-curated categories are preserved (manual edits are authoritative).
|
||||
if len(page.CategoryPath) == 0 && batchCtx != nil {
|
||||
if planned := types.CleanWikiCategoryPath(batchCtx.PlannedCategory[slug]); len(planned) > 0 {
|
||||
page.CategoryPath = types.StringArray(planned)
|
||||
page.WikiPath = ""
|
||||
// Apply the batch taxonomy plan, but only to pages that aren't already
|
||||
// filed — so brand-new pages get a coherent folder while previously-filed
|
||||
// or user-moved pages keep their placement (manual edits are authoritative).
|
||||
// The page's category_path cache is derived from folder_id downstream by
|
||||
// CreatePage/UpdatePage, so assigning the folder id is sufficient here.
|
||||
if page.FolderID == "" && batchCtx != nil {
|
||||
if fid := batchCtx.PlannedFolderID[slug]; fid != "" {
|
||||
page.FolderID = fid
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +101,44 @@ func (s *wikiIngestService) planBatchTaxonomy(
|
||||
return result
|
||||
}
|
||||
|
||||
// resolvePlannedFolders reifies the planner's per-slug paths into real
|
||||
// wiki_folders rows and returns a slug -> folder id map. Folder creation is
|
||||
// done here, sequentially and before the parallel reduce phase, so reduce only
|
||||
// assigns pre-resolved ids and never races two goroutines into creating the
|
||||
// same folder. Distinct paths are resolved once and cached. Blank paths (and
|
||||
// any resolution failure) map to the root and are simply omitted.
|
||||
func (s *wikiIngestService) resolvePlannedFolders(
|
||||
ctx context.Context, kb *types.KnowledgeBase, planned map[string][]string,
|
||||
) map[string]string {
|
||||
if kb == nil || len(planned) == 0 || s.wikiService == nil {
|
||||
return nil
|
||||
}
|
||||
pathCache := make(map[string]string) // "a/b" -> folder id
|
||||
out := make(map[string]string, len(planned))
|
||||
for slug, path := range planned {
|
||||
clean := types.CleanWikiCategoryPath(path)
|
||||
if len(clean) == 0 {
|
||||
continue
|
||||
}
|
||||
key := strings.Join(clean, "/")
|
||||
fid, ok := pathCache[key]
|
||||
if !ok {
|
||||
resolved, _, err := s.wikiService.FindOrCreateFolderPath(ctx, kb.ID, kb.TenantID, clean)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: resolve folder %q failed: %v", key, err)
|
||||
pathCache[key] = "" // negative-cache so we don't retry per slug
|
||||
continue
|
||||
}
|
||||
fid = resolved
|
||||
pathCache[key] = fid
|
||||
}
|
||||
if fid != "" {
|
||||
out[slug] = fid
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// selectRelevantFolders narrows the existing folder pool to the subset worth
|
||||
// showing the planner for THIS batch. A healthy navigation directory is small,
|
||||
// so it is fed whole (perfect reuse recall, no embedding cost). Only once folders
|
||||
|
||||
@@ -67,6 +67,9 @@ func (s *wikiPageService) CreatePage(ctx context.Context, page *types.WikiPage)
|
||||
|
||||
// Parse outbound links from content
|
||||
page.OutLinks = s.parseOutLinks(page.Content)
|
||||
if err := s.applyFolderToPage(ctx, page); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalizeWikiHierarchy(page)
|
||||
|
||||
now := time.Now()
|
||||
@@ -117,13 +120,17 @@ func (s *wikiPageService) UpdatePage(ctx context.Context, page *types.WikiPage)
|
||||
existing.ChunkRefs = page.ChunkRefs
|
||||
existing.PageMetadata = page.PageMetadata
|
||||
existing.ParentSlug = page.ParentSlug
|
||||
existing.CategoryPath = page.CategoryPath
|
||||
existing.WikiPath = page.WikiPath
|
||||
existing.Depth = page.Depth
|
||||
existing.FolderID = page.FolderID
|
||||
existing.SortOrder = page.SortOrder
|
||||
existing.Status = page.Status
|
||||
existing.UpdatedAt = time.Now()
|
||||
|
||||
// CategoryPath is a derived cache of FolderID — recompute it from the
|
||||
// folder chain rather than trusting whatever the caller sent.
|
||||
if err := s.applyFolderToPage(ctx, existing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Outbound links are a pure derivative of content, so they only shift
|
||||
// when content shifts. Re-parse unconditionally to stay consistent with
|
||||
// the stored body.
|
||||
@@ -831,21 +838,12 @@ func (s *wikiPageService) FindSimilarPages(ctx context.Context, kbID string, que
|
||||
return s.repo.FindSimilarPages(ctx, kbID, query, pageTypes, limit)
|
||||
}
|
||||
|
||||
// ListDistinctCategoryPaths returns unique category_path folders already used
|
||||
// by entity/concept pages. Used by wiki ingest to ground extraction prompts.
|
||||
// ListDistinctCategoryPaths returns the existing wiki folder paths. Used by
|
||||
// wiki ingest's taxonomy planner to ground folder reuse.
|
||||
func (s *wikiPageService) ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error) {
|
||||
return s.repo.ListDistinctCategoryPaths(ctx, kbID, maxPaths)
|
||||
}
|
||||
|
||||
// ListDistinctCategoryPathsByType returns the direct child folders of
|
||||
// parentPath across the given page types, paginated, plus the total distinct
|
||||
// child count. The browser uses this to expand the directory tree level by
|
||||
// level; passing several types lets one tab (e.g. the merged knowledge tab)
|
||||
// build a single directory skeleton server-side.
|
||||
func (s *wikiPageService) ListDistinctCategoryPathsByType(ctx context.Context, kbID string, pageTypes []string, parentPath []string, page, pageSize int) ([]types.WikiCategoryPath, int, error) {
|
||||
return s.repo.ListDistinctCategoryPathsByType(ctx, kbID, pageTypes, parentPath, page, pageSize)
|
||||
}
|
||||
|
||||
// CountByType is a service-layer pass-through over the repo. Used by
|
||||
// the index intro path to frame the LLM prompt's "showing N of M" hint.
|
||||
func (s *wikiPageService) CountByType(ctx context.Context, kbID string) (map[string]int64, error) {
|
||||
@@ -969,7 +967,6 @@ func normalizeWikiHierarchy(page *types.WikiPage) {
|
||||
cleanPath := types.StringArray(types.CleanWikiCategoryPath(page.CategoryPath))
|
||||
page.CategoryPath = cleanPath
|
||||
page.Depth = len(cleanPath)
|
||||
page.CategoryL1, page.CategoryL2, page.CategoryL3 = types.WikiCategoryLevels(cleanPath)
|
||||
|
||||
display := strings.TrimSpace(page.Title)
|
||||
if display == "" {
|
||||
@@ -1050,6 +1047,389 @@ func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, issueID string,
|
||||
return s.repo.UpdateIssueStatus(ctx, issueID, status)
|
||||
}
|
||||
|
||||
// --- Folder tree (wiki_folders) ---
|
||||
|
||||
// wikiFolderSegments splits a materialized folder path ("AI/RAG") into cleaned
|
||||
// segments. Empty/blank path yields nil (the wiki root).
|
||||
func wikiFolderSegments(path string) []string {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil
|
||||
}
|
||||
return types.CleanWikiCategoryPath(strings.Split(path, "/"))
|
||||
}
|
||||
|
||||
// applyFolderToPage refreshes a page's derived category_path cache from its
|
||||
// authoritative FolderID. Root ("") clears the path. A folder id that does not
|
||||
// resolve is treated as a hard error so we never silently misplace a page.
|
||||
func (s *wikiPageService) applyFolderToPage(ctx context.Context, page *types.WikiPage) error {
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(page.FolderID) == "" {
|
||||
page.FolderID = ""
|
||||
page.CategoryPath = nil
|
||||
return nil
|
||||
}
|
||||
folder, err := s.repo.GetFolderByID(ctx, page.KnowledgeBaseID, page.FolderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrWikiFolderNotFound) {
|
||||
return fmt.Errorf("wiki page references unknown folder %q", page.FolderID)
|
||||
}
|
||||
return fmt.Errorf("resolve page folder: %w", err)
|
||||
}
|
||||
page.CategoryPath = types.StringArray(wikiFolderSegments(folder.Path))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetFolder retrieves a single folder by id.
|
||||
func (s *wikiPageService) GetFolder(ctx context.Context, kbID string, id string) (*types.WikiFolder, error) {
|
||||
return s.repo.GetFolderByID(ctx, kbID, id)
|
||||
}
|
||||
|
||||
// ListChildFolders returns the direct children of parentID for a tree view
|
||||
// scoped to pageTypes. PageCount is recursive (the folder's whole subtree) so
|
||||
// a parent reflects everything filed beneath it, and a folder is only shown
|
||||
// when its subtree holds a page of pageTypes or it is entirely empty — which
|
||||
// keeps, say, the summary tab from listing folders that only hold entity pages.
|
||||
func (s *wikiPageService) ListChildFolders(
|
||||
ctx context.Context, kbID string, parentID string, pageTypes []string,
|
||||
) ([]types.WikiFolderNode, error) {
|
||||
all, err := s.repo.ListAllFolders(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scopedDirect, err := s.repo.CountPagesByFolder(ctx, kbID, pageTypes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allDirect := scopedDirect
|
||||
if len(pageTypes) > 0 {
|
||||
allDirect, err = s.repo.CountPagesByFolder(ctx, kbID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
recScoped := recursiveFolderCounts(all, scopedDirect)
|
||||
recAll := recursiveFolderCounts(all, allDirect)
|
||||
// A folder belongs in this view if it (recursively) contains a page of the
|
||||
// requested types, or if it is a completely empty container (no pages of
|
||||
// any type anywhere underneath).
|
||||
relevant := func(id string) bool { return recScoped[id] > 0 || recAll[id] == 0 }
|
||||
|
||||
out := make([]types.WikiFolderNode, 0)
|
||||
for _, f := range all {
|
||||
if f.ParentID != parentID || !relevant(f.ID) {
|
||||
continue
|
||||
}
|
||||
hasChildren := false
|
||||
for _, g := range all {
|
||||
if g.ParentID == f.ID && relevant(g.ID) {
|
||||
hasChildren = true
|
||||
break
|
||||
}
|
||||
}
|
||||
out = append(out, types.WikiFolderNode{
|
||||
WikiFolder: *f,
|
||||
PageCount: recScoped[f.ID],
|
||||
HasChildren: hasChildren,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// recursiveFolderCounts maps each folder id to the sum of `direct` page counts
|
||||
// over the folder and all of its descendants, using the materialized path so a
|
||||
// single pass over the (navigation-sized) folder set suffices.
|
||||
func recursiveFolderCounts(all []*types.WikiFolder, direct map[string]int64) map[string]int64 {
|
||||
res := make(map[string]int64, len(all))
|
||||
for _, f := range all {
|
||||
sum := direct[f.ID]
|
||||
prefix := f.Path + "/"
|
||||
for _, g := range all {
|
||||
if g.ID != f.ID && strings.HasPrefix(g.Path, prefix) {
|
||||
sum += direct[g.ID]
|
||||
}
|
||||
}
|
||||
res[f.ID] = sum
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// validateFolderName trims and rejects blank names or names carrying directory
|
||||
// separators (a folder name is a single tree level).
|
||||
func validateFolderName(name string) (string, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return "", errors.New("folder name is required")
|
||||
}
|
||||
if strings.ContainsAny(name, "/||/") {
|
||||
return "", fmt.Errorf("folder name %q must not contain a path separator", name)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// CreateFolder creates a new empty folder under parentID.
|
||||
func (s *wikiPageService) CreateFolder(
|
||||
ctx context.Context, kbID string, tenantID uint64, parentID string, name string,
|
||||
) (*types.WikiFolder, error) {
|
||||
name, err := validateFolderName(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
parentPath := ""
|
||||
depth := 1
|
||||
if parentID != types.WikiFolderRootID {
|
||||
parent, err := s.repo.GetFolderByID(ctx, kbID, parentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parentPath = parent.Path
|
||||
depth = parent.Depth + 1
|
||||
}
|
||||
|
||||
if _, err := s.repo.GetChildFolderByName(ctx, kbID, parentID, name); err == nil {
|
||||
return nil, repository.ErrWikiFolderConflict
|
||||
} else if !errors.Is(err, repository.ErrWikiFolderNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
path := name
|
||||
if parentPath != "" {
|
||||
path = parentPath + "/" + name
|
||||
}
|
||||
now := time.Now()
|
||||
folder := &types.WikiFolder{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
ParentID: parentID,
|
||||
Name: name,
|
||||
Path: path,
|
||||
Depth: depth,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := s.repo.CreateFolder(ctx, folder); err != nil {
|
||||
return nil, fmt.Errorf("create wiki folder: %w", err)
|
||||
}
|
||||
return folder, nil
|
||||
}
|
||||
|
||||
// FindOrCreateFolderPath resolves a category path to a leaf folder id, creating
|
||||
// any missing intermediate folders along the way. Concurrency-safe against the
|
||||
// unique (kb, parent, name) constraint via a re-fetch on create conflict.
|
||||
func (s *wikiPageService) FindOrCreateFolderPath(
|
||||
ctx context.Context, kbID string, tenantID uint64, path []string,
|
||||
) (string, []string, error) {
|
||||
clean := types.CleanWikiCategoryPath(path)
|
||||
if len(clean) == 0 {
|
||||
return types.WikiFolderRootID, nil, nil
|
||||
}
|
||||
parentID := types.WikiFolderRootID
|
||||
parentPath := ""
|
||||
for depth, name := range clean {
|
||||
child, err := s.repo.GetChildFolderByName(ctx, kbID, parentID, name)
|
||||
if err != nil {
|
||||
if !errors.Is(err, repository.ErrWikiFolderNotFound) {
|
||||
return "", nil, err
|
||||
}
|
||||
fp := name
|
||||
if parentPath != "" {
|
||||
fp = parentPath + "/" + name
|
||||
}
|
||||
now := time.Now()
|
||||
child = &types.WikiFolder{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
ParentID: parentID,
|
||||
Name: name,
|
||||
Path: fp,
|
||||
Depth: depth + 1,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if cerr := s.repo.CreateFolder(ctx, child); cerr != nil {
|
||||
// Lost a create race (or unique violation): the sibling must
|
||||
// now exist — re-fetch it rather than failing the whole plan.
|
||||
child, err = s.repo.GetChildFolderByName(ctx, kbID, parentID, name)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("create wiki folder %q: %w", fp, cerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
parentID = child.ID
|
||||
parentPath = child.Path
|
||||
}
|
||||
return parentID, clean, nil
|
||||
}
|
||||
|
||||
// MovePage relocates a page into folderID ("" = root) and refreshes its cached
|
||||
// category path. Bookkeeping-only write (no version bump).
|
||||
func (s *wikiPageService) MovePage(
|
||||
ctx context.Context, kbID string, slug string, folderID string,
|
||||
) (*types.WikiPage, error) {
|
||||
page, err := s.repo.GetBySlug(ctx, kbID, slug)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page.FolderID = strings.TrimSpace(folderID)
|
||||
if err := s.applyFolderToPage(ctx, page); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page.UpdatedAt = time.Now()
|
||||
normalizeWikiHierarchy(page)
|
||||
if err := s.repo.UpdateMeta(ctx, page); err != nil {
|
||||
return nil, fmt.Errorf("move wiki page: %w", err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// RenameOrMoveFolder renames and/or reparents a folder, then recomputes the
|
||||
// materialized path/depth of the entire subtree and the cached category path of
|
||||
// every page underneath. Guards against cycles (moving a folder into itself or
|
||||
// one of its descendants) and sibling name collisions.
|
||||
func (s *wikiPageService) RenameOrMoveFolder(
|
||||
ctx context.Context, kbID string, id string, newName string, newParentID string, moveParent bool,
|
||||
) (*types.WikiFolder, error) {
|
||||
folder, err := s.repo.GetFolderByID(ctx, kbID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
name := folder.Name
|
||||
if strings.TrimSpace(newName) != "" {
|
||||
if name, err = validateFolderName(newName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
targetParent := folder.ParentID
|
||||
if moveParent {
|
||||
targetParent = newParentID
|
||||
}
|
||||
|
||||
parentPath := ""
|
||||
depthBase := 0
|
||||
if targetParent != types.WikiFolderRootID {
|
||||
if targetParent == folder.ID {
|
||||
return nil, errors.New("cannot move a folder into itself")
|
||||
}
|
||||
parent, err := s.repo.GetFolderByID(ctx, kbID, targetParent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parent.Path == folder.Path || strings.HasPrefix(parent.Path, folder.Path+"/") {
|
||||
return nil, errors.New("cannot move a folder into its own descendant")
|
||||
}
|
||||
parentPath = parent.Path
|
||||
depthBase = parent.Depth
|
||||
}
|
||||
|
||||
if existing, err := s.repo.GetChildFolderByName(ctx, kbID, targetParent, name); err == nil {
|
||||
if existing.ID != folder.ID {
|
||||
return nil, repository.ErrWikiFolderConflict
|
||||
}
|
||||
} else if !errors.Is(err, repository.ErrWikiFolderNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
oldPath := folder.Path
|
||||
newPath := name
|
||||
if parentPath != "" {
|
||||
newPath = parentPath + "/" + name
|
||||
}
|
||||
if newPath == oldPath && targetParent == folder.ParentID {
|
||||
return folder, nil // no-op
|
||||
}
|
||||
|
||||
all, err := s.repo.ListAllFolders(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
affected := make([]string, 0)
|
||||
var updated *types.WikiFolder
|
||||
for _, f := range all {
|
||||
switch {
|
||||
case f.ID == folder.ID:
|
||||
f.ParentID = targetParent
|
||||
f.Name = name
|
||||
f.Path = newPath
|
||||
f.Depth = depthBase + 1
|
||||
case strings.HasPrefix(f.Path, oldPath+"/"):
|
||||
f.Path = newPath + f.Path[len(oldPath):]
|
||||
f.Depth = len(wikiFolderSegments(f.Path))
|
||||
default:
|
||||
continue
|
||||
}
|
||||
f.UpdatedAt = now
|
||||
if err := s.repo.UpdateFolder(ctx, f); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
affected = append(affected, f.ID)
|
||||
if f.ID == folder.ID {
|
||||
updated = f
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.recomputePagesForFolders(ctx, kbID, affected); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if updated == nil {
|
||||
updated = folder
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// recomputePagesForFolders refreshes the cached category_path/wiki_path/depth of
|
||||
// every page filed under any of the given folder ids (used after a folder
|
||||
// subtree is moved/renamed). Bookkeeping-only writes (no version bump).
|
||||
func (s *wikiPageService) recomputePagesForFolders(ctx context.Context, kbID string, folderIDs []string) error {
|
||||
if len(folderIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
pages, err := s.repo.ListPagesByFolderIDs(ctx, kbID, folderIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, page := range pages {
|
||||
if err := s.applyFolderToPage(ctx, page); err != nil {
|
||||
return err
|
||||
}
|
||||
page.UpdatedAt = time.Now()
|
||||
normalizeWikiHierarchy(page)
|
||||
if err := s.repo.UpdateMeta(ctx, page); err != nil {
|
||||
logger.Warnf(ctx, "wiki: recompute folder path for page %s failed: %v", page.Slug, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteFolder removes a folder that has no pages and no child folders. The UI
|
||||
// must relocate contents first; this keeps deletion non-destructive.
|
||||
func (s *wikiPageService) DeleteFolder(ctx context.Context, kbID string, id string) error {
|
||||
if _, err := s.repo.GetFolderByID(ctx, kbID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
children, err := s.repo.ListChildFolders(ctx, kbID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(children) > 0 {
|
||||
return errors.New("folder is not empty: it still has sub-folders")
|
||||
}
|
||||
pages, err := s.repo.ListPagesByFolderIDs(ctx, kbID, []string{id})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(pages) > 0 {
|
||||
return errors.New("folder is not empty: it still contains pages")
|
||||
}
|
||||
return s.repo.DeleteFolder(ctx, kbID, id)
|
||||
}
|
||||
|
||||
// InjectCrossLinks scans affected pages and injects [[wiki-links]] for mentions
|
||||
// of other wiki page titles in the content. Pure text replacement, no LLM call.
|
||||
// Shares the linkifyContent helper with the ingest pipeline so both paths honor
|
||||
|
||||
Reference in New Issue
Block a user