Commit 0bff09ec by 黄南光

新增项目知识库

1 parent 90acd053
"use client";
import NotesPanel from "@/components/notes/NotesPanel";
/** 知识录入页:登录后的默认落地页,侧边栏「知识录入」入口。 */
export default function NotesPage() {
return <NotesPanel />;
}
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
X, Plus, Trash2, Save, Send, Search, Eye, Pencil, Users, FolderPlus,
Bold, Italic, Heading, List, Code, Quote, Link2, Loader2, ChevronDown,
} from "lucide-react";
import {
listNotes, createNote, updateNote, deleteNote, promoteNote,
myProjectKbs, createProjectKb, listCollaborators, addCollaborator,
removeCollaborator, searchProjectUsers,
type NoteItem, type ProjectKb, type ProjectCollaborator,
} from "@/lib/auth";
import { NoteCategoryLabel, NoteCategoryOrder, NoteStatusLabel, NoteStatusOrder } from "@/lib/noteEnums";
import { usePerms } from "@/lib/usePerms";
type Draft = {
id?: string;
title: string;
content: string;
category: string;
tags: string[];
status: string;
source: string;
promotedKbId?: string | null;
};
const EMPTY_DRAFT: Draft = {
title: "", content: "", category: "project", tags: [], status: "draft", source: "", promotedKbId: null,
};
export default function NotesPanel() {
const { has } = usePerms();
const canProject = has("kb:project:manage");
const [notes, setNotes] = useState<NoteItem[]>([]);
const [loading, setLoading] = useState(false);
const [fCategory, setFCategory] = useState("");
const [fStatus, setFStatus] = useState("");
const [kw, setKw] = useState("");
const [kwInput, setKwInput] = useState("");
const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);
const [tagInput, setTagInput] = useState("");
const [preview, setPreview] = useState(false);
const [saving, setSaving] = useState(false);
const [msg, setMsg] = useState<string | null>(null);
const taRef = useRef<HTMLTextAreaElement | null>(null);
const [projects, setProjects] = useState<ProjectKb[]>([]);
const [promoteKb, setPromoteKb] = useState("");
const [showProjectMgr, setShowProjectMgr] = useState(false);
const writableProjects = useMemo(
() => projects.filter((p) => p.access === "owner" || p.access === "editor"),
[projects]
);
const load = useCallback(async () => {
setLoading(true);
try {
const d = await listNotes({ category: fCategory, status: fStatus, keyword: kw });
setNotes(d.items);
} finally {
setLoading(false);
}
}, [fCategory, fStatus, kw]);
const loadProjects = useCallback(async () => {
if (!canProject) return;
try {
const d = await myProjectKbs();
setProjects(d.items);
} catch { /* 忽略 */ }
}, [canProject]);
useEffect(() => { load(); }, [load]);
useEffect(() => { loadProjects(); }, [loadProjects]);
const flash = (m: string) => { setMsg(m); setTimeout(() => setMsg(null), 2500); };
const selectNote = (n: NoteItem) => {
setDraft({
id: n.id, title: n.title, content: n.content, category: n.category,
tags: n.tags, status: n.status, source: n.source, promotedKbId: n.promotedKbId,
});
setPreview(false);
setPromoteKb("");
};
const newDraft = () => { setDraft(EMPTY_DRAFT); setPreview(false); setPromoteKb(""); };
const onSave = async () => {
if (!draft.title.trim() && !draft.content.trim()) { flash("标题与正文不能都为空"); return; }
setSaving(true);
try {
const body = {
title: draft.title, content: draft.content, category: draft.category,
tags: draft.tags, status: draft.status, source: draft.source,
};
const r = draft.id ? await updateNote(draft.id, body) : await createNote(body);
selectNote(r.item);
await load();
flash("已保存");
} catch (e) { flash((e as Error).message); } finally { setSaving(false); }
};
const onDelete = async () => {
if (!draft.id) { newDraft(); return; }
if (!confirm("删除这条笔记?(已沉淀的 wiki 页不受影响)")) return;
try {
await deleteNote(draft.id);
newDraft();
await load();
flash("已删除");
} catch (e) { flash((e as Error).message); }
};
const onPromote = async () => {
if (!draft.id) { flash("请先保存笔记再沉淀"); return; }
if (!promoteKb) { flash("请选择目标项目库"); return; }
if (!confirm("将这条笔记沉淀(原文直写)到所选项目库,生成一个 wiki 页?")) return;
setSaving(true);
try {
await promoteNote(draft.id, promoteKb);
await load();
setDraft((d) => ({ ...d, status: "archived", promotedKbId: promoteKb }));
flash("已沉淀到项目库");
} catch (e) { flash((e as Error).message); } finally { setSaving(false); }
};
// Markdown 工具条:在光标处插入/包裹语法
const wrap = (before: string, after = "", placeholder = "") => {
const ta = taRef.current;
if (!ta) return;
const s = ta.selectionStart, e = ta.selectionEnd;
const val = draft.content;
const sel = val.slice(s, e) || placeholder;
const next = val.slice(0, s) + before + sel + after + val.slice(e);
setDraft((d) => ({ ...d, content: next }));
requestAnimationFrame(() => {
ta.focus();
ta.selectionStart = s + before.length;
ta.selectionEnd = s + before.length + sel.length;
});
};
const addTag = () => {
const t = tagInput.trim();
if (t && !draft.tags.includes(t)) setDraft((d) => ({ ...d, tags: [...d.tags, t] }));
setTagInput("");
};
return (
<div className="flex h-full flex-col bg-white min-h-0">
{/* 顶栏 */}
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 shrink-0">
<div className="flex items-center gap-3">
<Pencil className="w-5 h-5 text-blue-600" />
<div>
<h2 className="text-lg font-bold text-slate-800">知识录入</h2>
<p className="text-xs text-slate-400">随手记录项目知识、经验与想法,可沉淀到项目库</p>
</div>
{msg && <span className="text-sm text-emerald-600 font-medium">{msg}</span>}
</div>
{canProject && (
<button
onClick={() => setShowProjectMgr((v) => !v)}
className={`flex items-center gap-1.5 px-3 py-2 text-sm font-semibold rounded-lg ${showProjectMgr ? "bg-blue-50 text-blue-600" : "text-slate-600 bg-slate-50 hover:bg-slate-100"}`}
>
<Users className="w-4 h-4" /> 项目库管理
</button>
)}
</div>
{showProjectMgr && canProject ? (
<ProjectManager onDone={loadProjects} projects={projects} />
) : (
<div className="flex flex-1 min-h-0">
{/* 左:列表 + 筛选 */}
<div className="w-80 border-r border-slate-100 flex flex-col shrink-0">
<div className="p-3 space-y-2 border-b border-slate-100">
<button
onClick={newDraft}
className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700"
>
<Plus className="w-4 h-4" /> 新建笔记
</button>
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
<input
value={kwInput}
onChange={(e) => setKwInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && setKw(kwInput.trim())}
placeholder="搜索标题/正文"
className="w-full pl-8 pr-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500"
/>
</div>
<div className="flex gap-2">
<select value={fCategory} onChange={(e) => setFCategory(e.target.value)}
className="flex-1 min-w-0 px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-xs outline-none">
<option value="">全部类型</option>
{NoteCategoryOrder.map((c) => <option key={c} value={c}>{NoteCategoryLabel[c]}</option>)}
</select>
<select value={fStatus} onChange={(e) => setFStatus(e.target.value)}
className="flex-1 min-w-0 px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-xs outline-none">
<option value="">全部状态</option>
{NoteStatusOrder.map((s) => <option key={s} value={s}>{NoteStatusLabel[s]}</option>)}
</select>
</div>
</div>
<div className="flex-1 overflow-y-auto">
{loading ? (
<div className="p-6 text-center text-slate-400"><Loader2 className="w-5 h-5 animate-spin inline" /></div>
) : notes.length === 0 ? (
<div className="p-6 text-center text-sm text-slate-400">暂无笔记,点「新建笔记」开始</div>
) : (
notes.map((n) => (
<button
key={n.id}
onClick={() => selectNote(n)}
className={`w-full text-left px-3 py-2.5 border-b border-slate-50 hover:bg-slate-50 ${draft.id === n.id ? "bg-blue-50" : ""}`}
>
<div className="flex items-center gap-2">
<span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 shrink-0">
{NoteCategoryLabel[n.category] || "其他"}
</span>
<span className="text-sm font-semibold text-slate-700 truncate flex-1 min-w-0">
{n.title || "(无标题)"}
</span>
{n.promotedFileId && <Send className="w-3 h-3 text-emerald-500 shrink-0" />}
</div>
<div className="text-xs text-slate-400 truncate mt-1">{n.content || ""}</div>
</button>
))
)}
</div>
</div>
{/* 右:编辑器 */}
<div className="flex-1 min-w-0 flex flex-col">
<div className="p-4 space-y-3 overflow-y-auto flex-1">
<input
value={draft.title}
onChange={(e) => setDraft((d) => ({ ...d, title: e.target.value }))}
placeholder="标题(可选)"
className="w-full px-3 py-2 text-lg font-bold border-b border-slate-100 outline-none focus:border-blue-500"
/>
{/* 分类维度 */}
<div className="flex flex-wrap items-center gap-2">
<select value={draft.category} onChange={(e) => setDraft((d) => ({ ...d, category: e.target.value }))}
className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
{NoteCategoryOrder.map((c) => <option key={c} value={c}>{NoteCategoryLabel[c]}</option>)}
</select>
<select value={draft.status} onChange={(e) => setDraft((d) => ({ ...d, status: e.target.value }))}
className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
{NoteStatusOrder.map((s) => <option key={s} value={s}>{NoteStatusLabel[s]}</option>)}
</select>
<input
value={draft.source}
onChange={(e) => setDraft((d) => ({ ...d, source: e.target.value }))}
placeholder="来源(可选)"
className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none w-40"
/>
</div>
{/* 标签 */}
<div className="flex flex-wrap items-center gap-1.5">
{draft.tags.map((t) => (
<span key={t} className="flex items-center gap-1 text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded-full">
{t}
<button onClick={() => setDraft((d) => ({ ...d, tags: d.tags.filter((x) => x !== t) }))}>
<X className="w-3 h-3" />
</button>
</span>
))}
<input
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addTag())}
placeholder="+ 标签回车"
className="text-xs px-2 py-1 border border-dashed border-slate-300 rounded-full outline-none w-24"
/>
</div>
{/* 工具条 */}
<div className="flex items-center gap-1 border border-slate-200 rounded-lg p-1 bg-slate-50">
<TB onClick={() => wrap("**", "**", "加粗")}><Bold className="w-4 h-4" /></TB>
<TB onClick={() => wrap("*", "*", "斜体")}><Italic className="w-4 h-4" /></TB>
<TB onClick={() => wrap("## ", "", "标题")}><Heading className="w-4 h-4" /></TB>
<TB onClick={() => wrap("- ", "", "列表项")}><List className="w-4 h-4" /></TB>
<TB onClick={() => wrap("`", "`", "代码")}><Code className="w-4 h-4" /></TB>
<TB onClick={() => wrap("> ", "", "引用")}><Quote className="w-4 h-4" /></TB>
<TB onClick={() => wrap("[", "](url)", "链接文字")}><Link2 className="w-4 h-4" /></TB>
<div className="flex-1" />
<TB onClick={() => setPreview((v) => !v)} active={preview}>
<Eye className="w-4 h-4" /> <span className="text-xs">{preview ? "编辑" : "预览"}</span>
</TB>
</div>
{/* 正文 */}
{preview ? (
<div className="prose prose-sm max-w-none min-h-[240px] p-3 border border-slate-100 rounded-lg overflow-auto">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{draft.content || "(空)"}</ReactMarkdown>
</div>
) : (
<textarea
ref={taRef}
value={draft.content}
onChange={(e) => setDraft((d) => ({ ...d, content: e.target.value }))}
placeholder="记录你脑海中的知识、经验、想法…(支持 Markdown)"
className="w-full min-h-[240px] p-3 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500 font-mono leading-relaxed resize-y"
/>
)}
</div>
{/* 底部动作栏 */}
<div className="flex items-center gap-2 px-4 py-3 border-t border-slate-100 shrink-0 flex-wrap">
<button onClick={onSave} disabled={saving}
className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700 disabled:opacity-50">
<Save className="w-4 h-4" /> 保存
</button>
<button onClick={onDelete}
className="flex items-center gap-1.5 px-3 py-2 text-sm text-slate-500 hover:text-red-500 hover:bg-red-50 rounded-lg">
<Trash2 className="w-4 h-4" /> 删除
</button>
<div className="flex-1" />
{/* 沉淀到项目库 */}
{canProject ? (
<div className="flex items-center gap-2">
<select value={promoteKb} onChange={(e) => setPromoteKb(e.target.value)}
className="px-2 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none max-w-48">
<option value="">选择项目库…</option>
{writableProjects.map((p) => (
<option key={p.id} value={p.id}>{p.kbName}{p.isOwner ? "(我的)" : ""}</option>
))}
</select>
<button onClick={onPromote} disabled={saving || !draft.id}
className="flex items-center gap-1.5 px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-bold hover:bg-emerald-700 disabled:opacity-50">
<Send className="w-4 h-4" /> 沉淀到 Wiki
</button>
</div>
) : (
<span className="text-xs text-slate-400">(无项目库权限,无法沉淀)</span>
)}
</div>
</div>
</div>
)}
</div>
);
}
function TB({ children, onClick, active }: { children: React.ReactNode; onClick: () => void; active?: boolean }) {
return (
<button
onClick={onClick}
className={`flex items-center gap-1 px-2 py-1 rounded hover:bg-white text-slate-600 ${active ? "bg-white text-blue-600" : ""}`}
>
{children}
</button>
);
}
/* ============ 项目库管理:创建 + 协作者 ============ */
function ProjectManager({ projects, onDone }: { projects: ProjectKb[]; onDone: () => void }) {
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [expandKb, setExpandKb] = useState<string | null>(null);
const owned = useMemo(() => projects.filter((p) => p.isOwner), [projects]);
const create = async () => {
if (!name.trim()) return;
setBusy(true);
try { await createProjectKb(name.trim()); setName(""); await onDone(); }
catch (e) { alert((e as Error).message); } finally { setBusy(false); }
};
return (
<div className="flex-1 overflow-y-auto p-6 space-y-6">
<div>
<h3 className="text-sm font-bold text-slate-700 mb-2">新建项目库</h3>
<div className="flex gap-2 max-w-md">
<input value={name} onChange={(e) => setName(e.target.value)}
placeholder="项目库名称,如「谈客话术库」" onKeyDown={(e) => e.key === "Enter" && create()}
className="flex-1 px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500" />
<button onClick={create} disabled={busy}
className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700 disabled:opacity-50">
<FolderPlus className="w-4 h-4" /> 创建
</button>
</div>
<p className="text-xs text-slate-400 mt-1">创建者即 owner(读写 + 管协作者);协作者按人授 editor(读写)/ reader(只读),类似 git 协作。</p>
</div>
<div>
<h3 className="text-sm font-bold text-slate-700 mb-2">我创建的项目库({owned.length})</h3>
{owned.length === 0 ? (
<div className="text-sm text-slate-400">还没有项目库</div>
) : (
<div className="space-y-2">
{owned.map((p) => (
<div key={p.id} className="border border-slate-200 rounded-lg">
<button onClick={() => setExpandKb(expandKb === p.id ? null : p.id)}
className="w-full flex items-center justify-between px-4 py-2.5 hover:bg-slate-50">
<span className="font-semibold text-slate-700 text-sm">{p.kbName}</span>
<ChevronDown className={`w-4 h-4 text-slate-400 transition-transform ${expandKb === p.id ? "rotate-180" : ""}`} />
</button>
{expandKb === p.id && <CollaboratorEditor kbId={p.id} />}
</div>
))}
</div>
)}
</div>
</div>
);
}
function CollaboratorEditor({ kbId }: { kbId: string }) {
const [rows, setRows] = useState<ProjectCollaborator[]>([]);
const [q, setQ] = useState("");
const [results, setResults] = useState<{ id: string; name: string; username: string }[]>([]);
const [access, setAccess] = useState<"editor" | "reader">("editor");
const load = useCallback(async () => {
try { const d = await listCollaborators(kbId); setRows(d.items); } catch { /* */ }
}, [kbId]);
useEffect(() => { load(); }, [load]);
useEffect(() => {
const t = setTimeout(async () => {
if (!q.trim()) { setResults([]); return; }
try { const d = await searchProjectUsers(q.trim()); setResults(d.items); } catch { /* */ }
}, 300);
return () => clearTimeout(t);
}, [q]);
const add = async (userId: string) => {
try { await addCollaborator(kbId, userId, access); setQ(""); setResults([]); await load(); }
catch (e) { alert((e as Error).message); }
};
const remove = async (userId: string) => {
try { await removeCollaborator(kbId, userId); await load(); } catch (e) { alert((e as Error).message); }
};
return (
<div className="px-4 pb-4 pt-1 border-t border-slate-100 space-y-3">
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="搜索同事姓名/账号添加协作者"
className="w-full pl-8 pr-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500" />
{results.length > 0 && (
<div className="absolute z-10 mt-1 w-full bg-white border border-slate-200 rounded-lg shadow-lg max-h-48 overflow-auto">
{results.map((u) => (
<button key={u.id} onClick={() => add(u.id)}
className="w-full text-left px-3 py-2 hover:bg-blue-50 text-sm">
{u.name} <span className="text-slate-400 text-xs">{u.username}</span>
</button>
))}
</div>
)}
</div>
<select value={access} onChange={(e) => setAccess(e.target.value as "editor" | "reader")}
className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
<option value="editor">读写</option>
<option value="reader">只读</option>
</select>
</div>
{rows.length === 0 ? (
<div className="text-xs text-slate-400">暂无协作者</div>
) : (
<div className="space-y-1">
{rows.map((r) => (
<div key={r.grantId} className="flex items-center justify-between text-sm px-2 py-1.5 bg-slate-50 rounded-lg">
<span className="text-slate-700">{r.userName}
<span className="ml-2 text-xs text-slate-400">{r.access === "editor" ? "读写" : "只读"}</span>
</span>
<button onClick={() => remove(r.userId)} className="text-slate-400 hover:text-red-500">
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
</div>
)}
</div>
);
}
/**
* 采集笔记枚举镜像(与后端 src/api/routes/notes.py 的 NOTE_CATEGORIES / NOTE_STATUSES 一致)。
*/
export const NoteCategoryLabel: Record<string, string> = {
project: "项目知识",
lesson: "经验教训",
sop: "操作流程",
term: "术语概念",
idea: "想法",
pitfall: "踩坑",
reference: "参考链接",
meeting: "会议纪要",
other: "其他",
};
export const NoteCategoryOrder = [
"project", "lesson", "sop", "term", "idea", "pitfall", "reference", "meeting", "other",
] as const;
export const NoteStatusLabel: Record<string, string> = {
draft: "草稿",
pending: "待整理",
archived: "已归档",
};
export const NoteStatusOrder = ["draft", "pending", "archived"] as const;
"""采集/速记笔记路由(前缀 /notes)。
低门槛捕获用户脑海中的项目知识:私有笔记(仅本人可见/可编辑),带分类,
可一键沉淀(promote)到**自己有写权限的项目库**,生成一个 wiki 页(直写保真,不经 LLM 改写)。
严格隔离:所有读写都强制 where user_id == me.id;沉淀目标库必须 kb_type=project 且当前用户可写,
绝不允许写入他人库或部门/基础库。
"""
from __future__ import annotations
import json
import os
import re
from datetime import datetime
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
from sqlalchemy import func, select
from config import BASE_DIR
from src.database.models import (
WikiFile,
WikiFilePage,
WikiKbInfo,
WikiNote,
WikiOaUser,
uuid_str,
)
from src.database.session import AsyncSessionLocal
from src.services.identity.tokens import get_current_user
from src.services.oa import enums
from src.services.oa.audit import log_oper
from src.services.oa.kb_paths import kb_raw_dir, kb_raw_rel, kb_wiki_dir, kb_wiki_rel, ensure_kb_dirs
from src.services.oa.perms import resolve_kb_access
from src.tools.wiki_tools import rebuild_index
router = APIRouter(tags=["notes"])
# 分类维度(前端镜像见 frontend/src/lib/noteEnums.ts)
NOTE_CATEGORIES = (
"project", "lesson", "sop", "term", "idea", "pitfall", "reference", "meeting", "other",
)
NOTE_STATUSES = ("draft", "pending", "archived")
def _parse_tags(raw) -> list[str]:
"""输入标签规整为字符串列表(接受 list 或 JSON 串)。"""
if raw is None:
return []
if isinstance(raw, list):
return [str(t).strip() for t in raw if str(t).strip()]
try:
arr = json.loads(raw)
return [str(t).strip() for t in arr if str(t).strip()] if isinstance(arr, list) else []
except Exception:
return []
def _dump_tags(tags: list[str]) -> str:
return json.dumps(tags, ensure_ascii=False)
def _serialize(n: WikiNote) -> dict:
return {
"id": n.id,
"title": n.title or "",
"content": n.content or "",
"category": n.category,
"tags": _parse_tags(n.tags),
"status": n.status,
"source": n.source or "",
"promotedKbId": n.promoted_kb_id,
"promotedFileId": n.promoted_file_id,
"createdAt": n.created_at.strftime("%Y-%m-%d %H:%M:%S") if n.created_at else None,
"updatedAt": n.updated_at.strftime("%Y-%m-%d %H:%M:%S") if n.updated_at else None,
}
def _safe_stem(title: str) -> str:
"""把标题净化成安全文件名主干(去路径分隔符/非法字符,限长),空则用 note。"""
stem = (title or "").strip() or "note"
stem = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", stem)
stem = re.sub(r"\s+", "_", stem).strip("._")
return (stem or "note")[:60]
async def _get_own_note(session, note_id: str, me: WikiOaUser) -> WikiNote:
n = await session.get(WikiNote, note_id)
if n is None or n.del_flag != enums.DEL_NORMAL or n.user_id != me.id:
raise HTTPException(status_code=404, detail="笔记不存在")
return n
@router.get("/notes")
async def list_notes(
category: str = Query(default=""),
status_: str = Query(default="", alias="status"),
keyword: str = Query(default=""),
limit: int = Query(default=50, ge=1, le=500),
offset: int = Query(default=0, ge=0),
me: WikiOaUser = Depends(get_current_user),
):
"""当前用户自己的笔记列表(按更新时间倒序),支持 类型/状态/关键词 筛选。"""
async with AsyncSessionLocal() as session:
stmt = select(WikiNote).where(
WikiNote.user_id == me.id, WikiNote.del_flag == enums.DEL_NORMAL
)
count_stmt = select(func.count(WikiNote.id)).where(
WikiNote.user_id == me.id, WikiNote.del_flag == enums.DEL_NORMAL
)
if category.strip() in NOTE_CATEGORIES:
stmt = stmt.where(WikiNote.category == category.strip())
count_stmt = count_stmt.where(WikiNote.category == category.strip())
if status_.strip() in NOTE_STATUSES:
stmt = stmt.where(WikiNote.status == status_.strip())
count_stmt = count_stmt.where(WikiNote.status == status_.strip())
kw = keyword.strip()
if kw:
cond = WikiNote.title.like(f"%{kw}%") | WikiNote.content.like(f"%{kw}%")
stmt = stmt.where(cond)
count_stmt = count_stmt.where(cond)
total = (await session.execute(count_stmt)).scalar() or 0
rows = (
await session.execute(
stmt.order_by(WikiNote.updated_at.desc()).limit(limit).offset(offset)
)
).scalars().all()
return {"success": True, "total": total, "items": [_serialize(n) for n in rows]}
@router.post("/notes")
async def create_note(
title: str = Body(default="", embed=True),
content: str = Body(default="", embed=True),
category: str = Body(default="other", embed=True),
tags: list[str] = Body(default=[], embed=True),
status: str = Body(default="draft", embed=True),
source: str = Body(default="", embed=True),
me: WikiOaUser = Depends(get_current_user),
):
"""新建一条私有笔记。"""
cat = category if category in NOTE_CATEGORIES else "other"
st = status if status in NOTE_STATUSES else "draft"
if not (title or "").strip() and not (content or "").strip():
raise HTTPException(status_code=400, detail="标题与正文不能都为空")
async with AsyncSessionLocal() as session:
note = WikiNote(
user_id=me.id,
title=(title or "").strip() or None,
content=content or None,
category=cat,
tags=_dump_tags(_parse_tags(tags)),
status=st,
source=(source or "").strip() or None,
)
session.add(note)
await session.commit()
note = await session.get(WikiNote, note.id)
data = _serialize(note)
return {"success": True, "item": data}
@router.patch("/notes/{note_id}")
async def update_note(
note_id: str,
title: str | None = Body(default=None, embed=True),
content: str | None = Body(default=None, embed=True),
category: str | None = Body(default=None, embed=True),
tags: list[str] | None = Body(default=None, embed=True),
status: str | None = Body(default=None, embed=True),
source: str | None = Body(default=None, embed=True),
me: WikiOaUser = Depends(get_current_user),
):
"""更新自己的笔记(仅本人)。"""
async with AsyncSessionLocal() as session:
note = await _get_own_note(session, note_id, me)
if title is not None:
note.title = title.strip() or None
if content is not None:
note.content = content or None
if category is not None and category in NOTE_CATEGORIES:
note.category = category
if tags is not None:
note.tags = _dump_tags(_parse_tags(tags))
if status is not None and status in NOTE_STATUSES:
note.status = status
if source is not None:
note.source = source.strip() or None
await session.commit()
note = await session.get(WikiNote, note_id)
data = _serialize(note)
return {"success": True, "item": data}
@router.delete("/notes/{note_id}")
async def delete_note(note_id: str, me: WikiOaUser = Depends(get_current_user)):
"""逻辑删除自己的笔记(不影响已沉淀的 wiki 页)。"""
async with AsyncSessionLocal() as session:
note = await _get_own_note(session, note_id, me)
note.del_flag = enums.DEL_DELETED
await session.commit()
return {"success": True}
@router.post("/notes/{note_id}/promote")
async def promote_note(
note_id: str,
request: Request,
kbId: str = Body(..., embed=True),
me: WikiOaUser = Depends(get_current_user),
):
"""把笔记沉淀(直写保真)到指定**项目库**,生成一个 wiki 页。
强约束:目标库必须存在、kb_type=project、且当前用户对其有写权限(owner/editor);
否则一律拒绝——绝不允许写入他人库或部门/基础库。
"""
target = (kbId or "").strip()
if not target:
raise HTTPException(status_code=400, detail="请选择目标项目库")
async with AsyncSessionLocal() as session:
note = await _get_own_note(session, note_id, me)
if not (note.content or "").strip():
raise HTTPException(status_code=400, detail="空笔记无法沉淀")
kb = await session.get(WikiKbInfo, target)
if kb is None or kb.del_flag != enums.DEL_NORMAL or kb.status != enums.STATUS_ACTIVE:
raise HTTPException(status_code=404, detail="目标项目库不存在")
if kb.kb_type != enums.KB_PROJECT:
raise HTTPException(status_code=400, detail="笔记只能沉淀到项目库")
access = await resolve_kb_access(me, kb)
if access not in enums.KB_WRITE_LEVELS:
raise HTTPException(status_code=403, detail="对该项目库无写权限")
ensure_kb_dirs(kb)
stem = _safe_stem(note.title or "")
file_id = uuid_str()
title = (note.title or stem).strip()
tags = _parse_tags(note.tags)
# 1) 原始文件(raw):与上传落盘约定一致(含 uuid,允许同名)
raw_dir = os.path.join(kb_raw_dir(kb), "md")
os.makedirs(raw_dir, exist_ok=True)
raw_disk = os.path.join(raw_dir, f"{stem}_{file_id}.md")
with open(raw_disk, "w", encoding="utf-8") as f:
f.write(note.content or "")
raw_path = f"{kb_raw_rel(kb)}/md/{stem}_{file_id}.md"
# 2) wiki 页(直写保真,带 frontmatter 供 index 收录)
fm_tags = "[" + ", ".join(json.dumps(t, ensure_ascii=False) for t in tags) + "]"
fm_lines = [
"---",
f"title: {json.dumps(title, ensure_ascii=False)}",
"type: note",
f"category: {note.category}",
f"tags: {fm_tags}",
]
if note.source:
fm_lines.append(f"source: {json.dumps(note.source, ensure_ascii=False)}")
fm_lines.append(f"created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
fm_lines.append("---")
page_text = "\n".join(fm_lines) + "\n\n" + (note.content or "")
wiki_dir = os.path.join(kb_wiki_dir(kb), "notes")
os.makedirs(wiki_dir, exist_ok=True)
wiki_disk = os.path.join(wiki_dir, f"{stem}_{file_id}.md")
with open(wiki_disk, "w", encoding="utf-8") as f:
f.write(page_text)
page_path = f"{kb_wiki_rel(kb)}/notes/{stem}_{file_id}.md"
# 3) 登记 WikiFile + WikiFilePage(状态 Indexed,与摄入产物同构)
content_bytes = (note.content or "").encode("utf-8")
session.add(WikiFile(
id=file_id,
name=f"{title}.md",
format="MD",
size=len(content_bytes),
word_count=len(note.content or ""),
status="Indexed",
kb_id=kb.id,
uploaded_by=me.id,
raw_path=raw_path,
ingest_time=datetime.now(),
))
session.add(WikiFilePage(file_id=file_id, page_path=page_path))
# 4) 全量重建索引
try:
rebuild_index(kb_wiki_dir(kb))
except Exception:
pass
# 5) 回填笔记去向
note.promoted_kb_id = kb.id
note.promoted_file_id = file_id
note.status = "archived"
await session.commit()
await log_oper(
operator=me, request=request, module="note", action="promote",
target_type="note", target_id=note_id,
detail={"kbId": target, "fileId": file_id},
)
return {"success": True, "kbId": target, "fileId": file_id, "pagePath": page_path}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!