notes.py 11.7 KB
"""采集/速记笔记路由(前缀 /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}