758 lines
28 KiB
Python
758 lines
28 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
from pathlib import Path
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy import func, or_
|
|
from sqlalchemy.orm import Session, joinedload
|
|
|
|
from app.config import get_settings
|
|
from app.database import get_db
|
|
from app.deps import (
|
|
accessible_department_ids,
|
|
accessible_group_ids,
|
|
ensure_department_access,
|
|
ensure_group_access,
|
|
get_current_user,
|
|
require_admin,
|
|
)
|
|
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, SystemSetting, User
|
|
from app.schemas import DifyImportRequest, GroupCreateRequest, GroupUpdateRequest
|
|
from app.serializers import current_version, serialize_document, serialize_group
|
|
from app.services.dify_service import DifyError, DifyService
|
|
from app.services.storage_service import public_storage_url, remove_path_if_exists, sha256_file, version_dir
|
|
from app.time_utils import utc_now
|
|
import requests
|
|
|
|
|
|
router = APIRouter(prefix="/groups", tags=["groups"])
|
|
settings = get_settings()
|
|
|
|
|
|
def _scoped_group_ids(db: Session, user: User) -> list[int] | None:
|
|
return accessible_group_ids(db, user)
|
|
|
|
|
|
def _scoped_department_ids(db: Session, user: User) -> list[int] | None:
|
|
return accessible_department_ids(db, user)
|
|
|
|
|
|
def _scoped_groups_query(db: Session, user: User, *, department_id: int | None = None):
|
|
query = db.query(Group)
|
|
group_ids = _scoped_group_ids(db, user)
|
|
if group_ids is not None:
|
|
query = query.filter(Group.id.in_(group_ids or [-1]))
|
|
if department_id is not None:
|
|
query = query.filter(Group.department_id == department_id)
|
|
return query
|
|
|
|
|
|
def _document_name_key(name: str) -> str:
|
|
trimmed = (name or "").strip().lower()
|
|
candidate = Path(trimmed)
|
|
return candidate.stem if candidate.suffix else trimmed
|
|
|
|
|
|
def _normalized_document_title(name: str) -> str:
|
|
candidate = Path((name or "").strip())
|
|
return candidate.stem if candidate.suffix else candidate.name
|
|
|
|
|
|
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
|
|
if not path_value:
|
|
return None
|
|
raw_target = Path(path_value)
|
|
data_root = settings.data_root.resolve(strict=False)
|
|
if raw_target.is_absolute():
|
|
target = raw_target
|
|
else:
|
|
resolved_raw = raw_target.resolve(strict=False)
|
|
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
|
|
if parent:
|
|
target = target.parent
|
|
resolved = target.resolve(strict=False)
|
|
if not resolved.is_relative_to(data_root):
|
|
return None
|
|
return resolved
|
|
|
|
|
|
def _cleanup_document_storage(document: Document) -> None:
|
|
targets: set[Path] = set()
|
|
for version in document.versions:
|
|
for candidate in (
|
|
_resolve_storage_target(version.source_path, parent=True),
|
|
_resolve_storage_target(version.md_path, parent=True),
|
|
_resolve_storage_target(version.asset_dir),
|
|
):
|
|
if candidate is not None:
|
|
targets.add(candidate)
|
|
|
|
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
|
|
remove_path_if_exists(target)
|
|
|
|
|
|
def _local_documents_for_group(group: Group) -> dict[str, list[dict]]:
|
|
local_docs: dict[str, list[dict]] = {}
|
|
for document in group.documents:
|
|
if document.is_deleted:
|
|
continue
|
|
version = current_version(document)
|
|
if version is None:
|
|
continue
|
|
local_docs.setdefault(_document_name_key(document.title), []).append(
|
|
{
|
|
"document_id": document.id,
|
|
"title": document.title,
|
|
"source_ext": version.source_ext,
|
|
"convert_status": version.convert_status,
|
|
"sync_status": version.sync_status,
|
|
"remote_document_id": version.sync_records[0].remote_document_id if version.sync_records else None,
|
|
}
|
|
)
|
|
return local_docs
|
|
|
|
|
|
def _remote_documents_for_dataset(dify: DifyService, dataset_id: str | None) -> dict[str, list[dict]]:
|
|
if not dataset_id:
|
|
return {}
|
|
remote_docs: dict[str, list[dict]] = {}
|
|
for remote in dify.list_documents(dataset_id=dataset_id):
|
|
remote_docs.setdefault(_document_name_key(remote.name), []).append(
|
|
{
|
|
"document_id": remote.id,
|
|
"name": remote.name,
|
|
"indexing_status": remote.indexing_status,
|
|
"display_status": remote.display_status,
|
|
"enabled": remote.enabled,
|
|
}
|
|
)
|
|
return remote_docs
|
|
|
|
|
|
def _diff_status(local_entry: dict | None, remote_entry: dict | None) -> str:
|
|
if local_entry and not remote_entry:
|
|
return "local_only"
|
|
if remote_entry and not local_entry:
|
|
return "dify_only"
|
|
if (
|
|
(local_entry or {}).get("sync_status") != "synced"
|
|
or (remote_entry or {}).get("indexing_status") not in {"completed", "completed_with_warning"}
|
|
):
|
|
return "attention"
|
|
return "matched"
|
|
|
|
|
|
def _build_diff_rows(
|
|
*,
|
|
knowledge_base_name: str,
|
|
dataset_id: str | None,
|
|
local_docs: dict[str, list[dict]],
|
|
remote_docs: dict[str, list[dict]],
|
|
group: Group | None = None,
|
|
term: str = "",
|
|
include_knowledge_base: bool = False,
|
|
) -> list[dict]:
|
|
rows: list[dict] = []
|
|
for key in sorted(set(local_docs) | set(remote_docs)):
|
|
local_entries = list(local_docs.get(key, []))
|
|
remote_entries = list(remote_docs.get(key, []))
|
|
|
|
local_entries.sort(
|
|
key=lambda item: (
|
|
f"{item.get('title') or ''}{item.get('source_ext') or ''}".lower(),
|
|
int(item.get("document_id") or 0),
|
|
)
|
|
)
|
|
remote_entries.sort(
|
|
key=lambda item: (
|
|
(item.get("name") or "").lower(),
|
|
str(item.get("document_id") or ""),
|
|
)
|
|
)
|
|
|
|
paired_rows: list[tuple[dict | None, dict | None]] = []
|
|
remaining_remote = remote_entries.copy()
|
|
|
|
for local_entry in local_entries:
|
|
local_full_name = f"{local_entry.get('title') or ''}{local_entry.get('source_ext') or ''}".lower()
|
|
match_index = next(
|
|
(
|
|
index
|
|
for index, remote_entry in enumerate(remaining_remote)
|
|
if (remote_entry.get("name") or "").strip().lower() == local_full_name
|
|
),
|
|
None,
|
|
)
|
|
if match_index is None and remaining_remote:
|
|
match_index = 0
|
|
|
|
if match_index is None:
|
|
paired_rows.append((local_entry, None))
|
|
else:
|
|
paired_rows.append((local_entry, remaining_remote.pop(match_index)))
|
|
|
|
paired_rows.extend((None, remote_entry) for remote_entry in remaining_remote)
|
|
|
|
for index, (local_entry, remote_entry) in enumerate(paired_rows, start=1):
|
|
display_name = (local_entry or {}).get("title") or (remote_entry or {}).get("name") or key
|
|
haystacks = [display_name.lower(), knowledge_base_name.lower()]
|
|
if term and not any(term in item for item in haystacks):
|
|
continue
|
|
|
|
row = {
|
|
"key": f"{knowledge_base_name}:{key}:{index}" if include_knowledge_base else f"{key}:{index}",
|
|
"status": _diff_status(local_entry, remote_entry),
|
|
"local": local_entry,
|
|
"remote": remote_entry,
|
|
"display_name": display_name,
|
|
}
|
|
if include_knowledge_base:
|
|
row["knowledge_base"] = {
|
|
"group_id": group.id if group else None,
|
|
"name": knowledge_base_name,
|
|
"dataset_id": dataset_id,
|
|
}
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
def _summarize_diff_rows(rows: list[dict]) -> dict[str, int]:
|
|
return {
|
|
"matched": sum(1 for row in rows if row["status"] == "matched"),
|
|
"local_only": sum(1 for row in rows if row["status"] == "local_only"),
|
|
"dify_only": sum(1 for row in rows if row["status"] == "dify_only"),
|
|
"attention": sum(1 for row in rows if row["status"] == "attention"),
|
|
}
|
|
|
|
|
|
def _create_group_from_remote_name(*, db: Session, admin: User, group_name: str) -> Group:
|
|
if admin.primary_department_id is None:
|
|
raise HTTPException(status_code=400, detail="Admin must belong to a department before importing Dify documents.")
|
|
return _create_group_from_remote_name_in_department(
|
|
db=db,
|
|
admin=admin,
|
|
group_name=group_name,
|
|
department_id=admin.primary_department_id,
|
|
)
|
|
|
|
|
|
def _create_group_from_remote_name_in_department(
|
|
*,
|
|
db: Session,
|
|
admin: User,
|
|
group_name: str,
|
|
department_id: int,
|
|
) -> Group:
|
|
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
|
existing = (
|
|
db.query(Group)
|
|
.filter(Group.department_id == department_id, Group.name == group_name)
|
|
.first()
|
|
)
|
|
if existing:
|
|
return existing
|
|
group = Group(
|
|
name=group_name,
|
|
description=None,
|
|
department_id=department_id,
|
|
created_by_id=admin.id,
|
|
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
|
|
search_method=defaults.search_method if defaults else "hybrid_search",
|
|
doc_form=defaults.doc_form if defaults else "text_model",
|
|
top_k=defaults.top_k if defaults else 5,
|
|
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
|
|
score_threshold=defaults.score_threshold if defaults else "0.35",
|
|
)
|
|
db.add(group)
|
|
db.commit()
|
|
db.refresh(group)
|
|
return group
|
|
|
|
|
|
def _download_remote_upload(upload_file: dict | None) -> tuple[str, bytes] | None:
|
|
if not upload_file:
|
|
return None
|
|
download_url = upload_file.get("download_url") or upload_file.get("url")
|
|
if not download_url:
|
|
return None
|
|
response = requests.get(download_url, timeout=60)
|
|
response.raise_for_status()
|
|
filename = upload_file.get("name") or "remote-file"
|
|
return filename, response.content
|
|
|
|
|
|
def _import_dify_document_to_local(
|
|
*,
|
|
db: Session,
|
|
user: User,
|
|
dataset_id: str,
|
|
remote_document_id: str,
|
|
group: Group,
|
|
) -> Document:
|
|
dify = DifyService()
|
|
detail = dify.get_document_detail(dataset_id=dataset_id, document_id=remote_document_id)
|
|
remote_name = (detail.get("name") or "").strip() or remote_document_id
|
|
title = _normalized_document_title(remote_name)
|
|
|
|
existing = (
|
|
db.query(Document)
|
|
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
|
.filter(
|
|
Document.group_id == group.id,
|
|
func.lower(Document.title) == title.lower(),
|
|
Document.is_deleted.is_(False),
|
|
)
|
|
.first()
|
|
)
|
|
if existing:
|
|
raise HTTPException(status_code=409, detail="Document already exists locally. Refresh diff and retry.")
|
|
|
|
segments = dify.list_document_segments(dataset_id=dataset_id, document_id=remote_document_id)
|
|
markdown_text = "\n\n".join(item.content.strip() for item in segments if item.content and item.content.strip()).strip()
|
|
if not markdown_text:
|
|
raise HTTPException(status_code=409, detail="Remote Dify document has no importable content.")
|
|
|
|
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
|
|
db.add(document)
|
|
db.commit()
|
|
db.refresh(document)
|
|
|
|
version_no = 1
|
|
source_dir = version_dir("original", group.id, document.id, version_no)
|
|
markdown_dir = version_dir("markdown", group.id, document.id, version_no)
|
|
source_dir.mkdir(parents=True, exist_ok=True)
|
|
markdown_dir.mkdir(parents=True, exist_ok=True)
|
|
markdown_target = markdown_dir / "document.md"
|
|
markdown_target.write_text(markdown_text, encoding="utf-8")
|
|
|
|
source_filename = remote_name if Path(remote_name).suffix else f"{remote_name}.md"
|
|
source_ext = Path(source_filename).suffix.lower() or ".md"
|
|
source_target = source_dir / source_filename
|
|
|
|
upload_file = None
|
|
try:
|
|
upload_file = dify.get_upload_file(dataset_id=dataset_id, document_id=remote_document_id)
|
|
except DifyError:
|
|
upload_file = None
|
|
|
|
downloaded = None
|
|
if upload_file:
|
|
try:
|
|
downloaded = _download_remote_upload(upload_file)
|
|
except Exception:
|
|
downloaded = None
|
|
|
|
if downloaded:
|
|
source_filename, source_bytes = downloaded
|
|
source_ext = Path(source_filename).suffix.lower() or ".bin"
|
|
source_target = source_dir / source_filename
|
|
source_target.write_bytes(source_bytes)
|
|
else:
|
|
source_target.write_text(markdown_text, encoding="utf-8")
|
|
source_filename = source_target.name
|
|
source_ext = ".md"
|
|
|
|
version = DocumentVersion(
|
|
document_id=document.id,
|
|
version_no=version_no,
|
|
is_current=True,
|
|
source_filename=source_filename,
|
|
source_ext=source_ext,
|
|
source_path=str(source_target),
|
|
source_sha256=sha256_file(source_target),
|
|
md_path=str(markdown_target),
|
|
md_public_url=public_storage_url(markdown_target),
|
|
asset_dir=None,
|
|
file_size=source_target.stat().st_size,
|
|
word_count=len(markdown_text.split()),
|
|
convert_status="success",
|
|
sync_status="synced",
|
|
uploader_id=user.id,
|
|
uploaded_at=utc_now(),
|
|
converted_at=utc_now(),
|
|
warnings_json=[{"message": "imported_from_dify"}],
|
|
)
|
|
db.add(version)
|
|
db.commit()
|
|
db.refresh(version)
|
|
|
|
sync_record = DifySyncRecord(
|
|
version_id=version.id,
|
|
dataset_id=dataset_id,
|
|
remote_document_id=remote_document_id,
|
|
status="synced",
|
|
last_indexing_status=detail.get("indexing_status"),
|
|
last_synced_at=utc_now(),
|
|
error=None,
|
|
)
|
|
db.add(sync_record)
|
|
if group.dify_dataset_id != dataset_id:
|
|
group.dify_dataset_id = dataset_id
|
|
db.commit()
|
|
db.refresh(document)
|
|
return document
|
|
|
|
|
|
def _group_name_conflict(
|
|
db: Session,
|
|
*,
|
|
department_id: int | None,
|
|
name: str,
|
|
exclude_group_id: int | None = None,
|
|
) -> bool:
|
|
query = db.query(Group).filter(Group.department_id == department_id, Group.name == name)
|
|
if exclude_group_id is not None:
|
|
query = query.filter(Group.id != exclude_group_id)
|
|
return db.query(query.exists()).scalar()
|
|
|
|
|
|
@router.get("")
|
|
def list_groups(
|
|
department_id: int | None = Query(None),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
if department_id is not None:
|
|
ensure_department_access(db, user, department_id)
|
|
group_ids = _scoped_group_ids(db, user)
|
|
document_counts_query = (
|
|
db.query(
|
|
Document.group_id.label("group_id"),
|
|
func.count(Document.id).label("document_count"),
|
|
)
|
|
.filter(Document.is_deleted.is_(False))
|
|
.group_by(Document.group_id)
|
|
)
|
|
if group_ids is not None:
|
|
document_counts_query = document_counts_query.filter(Document.group_id.in_(group_ids or [-1]))
|
|
document_counts = document_counts_query.subquery()
|
|
query = db.query(
|
|
Group,
|
|
func.coalesce(document_counts.c.document_count, 0).label("document_count"),
|
|
).options(joinedload(Group.department)).outerjoin(document_counts, document_counts.c.group_id == Group.id)
|
|
if group_ids is not None:
|
|
query = query.filter(Group.id.in_(group_ids or [-1]))
|
|
if department_id is not None:
|
|
query = query.filter(Group.department_id == department_id)
|
|
groups = query.order_by(Group.name.asc()).all()
|
|
return {
|
|
"data": [serialize_group(group, document_count=document_count) for group, document_count in groups]
|
|
}
|
|
|
|
|
|
@router.get("/summary")
|
|
def get_dashboard_summary(
|
|
department_id: int | None = Query(None),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
if department_id is not None:
|
|
ensure_department_access(db, user, department_id)
|
|
group_ids = _scoped_group_ids(db, user)
|
|
knowledge_base_query = db.query(Group)
|
|
file_query = db.query(Document).filter(Document.is_deleted.is_(False))
|
|
if group_ids is not None:
|
|
scoped_filter = group_ids or [-1]
|
|
knowledge_base_query = knowledge_base_query.filter(Group.id.in_(scoped_filter))
|
|
file_query = file_query.filter(Document.group_id.in_(scoped_filter))
|
|
if department_id is not None:
|
|
knowledge_base_query = knowledge_base_query.filter(Group.department_id == department_id)
|
|
file_query = file_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
|
knowledge_base_count = knowledge_base_query.count()
|
|
file_count = file_query.count()
|
|
running_query = (
|
|
db.query(DocumentVersion)
|
|
.join(Document, Document.id == DocumentVersion.document_id)
|
|
.filter(Document.is_deleted.is_(False), DocumentVersion.is_current.is_(True))
|
|
.filter(
|
|
or_(
|
|
DocumentVersion.convert_status.in_(["queued", "running"]),
|
|
DocumentVersion.sync_status == "syncing",
|
|
)
|
|
)
|
|
)
|
|
if group_ids is not None:
|
|
running_query = running_query.filter(Document.group_id.in_(group_ids or [-1]))
|
|
if department_id is not None:
|
|
running_query = running_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
|
running_count = running_query.count()
|
|
return {
|
|
"knowledge_base_count": knowledge_base_count,
|
|
"file_count": file_count,
|
|
"running_count": running_count,
|
|
}
|
|
|
|
|
|
@router.get("/dify-diff-global")
|
|
def get_global_dify_diff(
|
|
q: str | None = Query(None),
|
|
department_id: int | None = Query(None),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
if department_id is not None:
|
|
ensure_department_access(db, user, department_id)
|
|
groups_query = (
|
|
db.query(Group)
|
|
.options(joinedload(Group.department))
|
|
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
|
)
|
|
group_ids = _scoped_group_ids(db, user)
|
|
if group_ids is not None:
|
|
groups_query = groups_query.filter(Group.id.in_(group_ids or [-1]))
|
|
if department_id is not None:
|
|
groups_query = groups_query.filter(Group.department_id == department_id)
|
|
groups = groups_query.order_by(Group.name.asc()).all()
|
|
dify = DifyService()
|
|
datasets = dify.list_datasets()
|
|
datasets_by_id = {item.id: item for item in datasets}
|
|
datasets_by_name = {item.name: item for item in datasets}
|
|
used_dataset_ids: set[str] = set()
|
|
term = (q or "").strip().lower()
|
|
rows: list[dict] = []
|
|
|
|
for group in groups:
|
|
dataset = datasets_by_id.get(group.dify_dataset_id or "") or datasets_by_name.get(group.name)
|
|
dataset_id = dataset.id if dataset else group.dify_dataset_id
|
|
if dataset:
|
|
used_dataset_ids.add(dataset.id)
|
|
rows.extend(
|
|
_build_diff_rows(
|
|
knowledge_base_name=group.name,
|
|
dataset_id=dataset_id,
|
|
local_docs=_local_documents_for_group(group),
|
|
remote_docs=_remote_documents_for_dataset(dify, dataset.id if dataset else group.dify_dataset_id),
|
|
group=group,
|
|
term=term,
|
|
include_knowledge_base=True,
|
|
)
|
|
)
|
|
|
|
return {"summary": _summarize_diff_rows(rows), "rows": rows}
|
|
|
|
|
|
@router.post("/import-dify-document")
|
|
def import_dify_document(
|
|
payload: DifyImportRequest,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
target_group: Group | None = None
|
|
if payload.group_id is not None:
|
|
ensure_group_access(db, user, payload.group_id)
|
|
target_group = db.query(Group).filter(Group.id == payload.group_id).first()
|
|
if not target_group:
|
|
raise HTTPException(status_code=404, detail="Knowledge base not found.")
|
|
else:
|
|
if user.role not in {"admin", "super_admin"}:
|
|
raise HTTPException(status_code=403, detail="Admin permission required.")
|
|
knowledge_base_name = (payload.knowledge_base_name or "").strip()
|
|
if not knowledge_base_name:
|
|
raise HTTPException(status_code=400, detail="Knowledge base name is required for Dify import.")
|
|
department_id = payload.department_id or user.primary_department_id
|
|
if department_id is None:
|
|
raise HTTPException(status_code=400, detail="Department is required for Dify import.")
|
|
ensure_department_access(db, user, department_id)
|
|
target_group = _create_group_from_remote_name_in_department(
|
|
db=db,
|
|
admin=user,
|
|
group_name=knowledge_base_name,
|
|
department_id=department_id,
|
|
)
|
|
|
|
document = _import_dify_document_to_local(
|
|
db=db,
|
|
user=user,
|
|
dataset_id=payload.dataset_id,
|
|
remote_document_id=payload.remote_document_id,
|
|
group=target_group,
|
|
)
|
|
return {
|
|
"group_id": target_group.id,
|
|
"group_name": target_group.name,
|
|
"document": serialize_document(document),
|
|
}
|
|
|
|
|
|
@router.post("")
|
|
def create_group(
|
|
payload: GroupCreateRequest,
|
|
db: Session = Depends(get_db),
|
|
admin: User = Depends(require_admin),
|
|
):
|
|
ensure_department_access(db, admin, payload.department_id)
|
|
if _group_name_conflict(db, department_id=payload.department_id, name=payload.name):
|
|
raise HTTPException(status_code=409, detail="Group already exists.")
|
|
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
|
group = Group(
|
|
name=payload.name,
|
|
description=payload.description,
|
|
department_id=payload.department_id,
|
|
created_by_id=admin.id,
|
|
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
|
|
search_method=defaults.search_method if defaults else "hybrid_search",
|
|
doc_form=defaults.doc_form if defaults else "text_model",
|
|
top_k=defaults.top_k if defaults else 5,
|
|
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
|
|
score_threshold=defaults.score_threshold if defaults else "0.35",
|
|
)
|
|
db.add(group)
|
|
db.commit()
|
|
db.refresh(group)
|
|
return serialize_group(group)
|
|
|
|
|
|
@router.patch("/{group_id}")
|
|
def update_group(
|
|
group_id: int,
|
|
payload: GroupUpdateRequest,
|
|
db: Session = Depends(get_db),
|
|
admin: User = Depends(require_admin),
|
|
):
|
|
ensure_group_access(db, admin, group_id)
|
|
group = db.query(Group).filter(Group.id == group_id).first()
|
|
if not group:
|
|
raise HTTPException(status_code=404, detail="Group not found.")
|
|
old_name = group.name
|
|
target_name = payload.name or group.name
|
|
target_department_id = payload.department_id if payload.department_id is not None else group.department_id
|
|
if payload.department_id is not None and payload.department_id != group.department_id:
|
|
ensure_department_access(db, admin, payload.department_id)
|
|
if payload.name or payload.department_id is not None:
|
|
if _group_name_conflict(
|
|
db,
|
|
department_id=target_department_id,
|
|
name=target_name,
|
|
exclude_group_id=group.id,
|
|
):
|
|
raise HTTPException(status_code=409, detail="Group already exists.")
|
|
if payload.name:
|
|
group.name = payload.name
|
|
if payload.description is not None:
|
|
group.description = payload.description
|
|
if payload.department_id is not None and payload.department_id != group.department_id:
|
|
group.department_id = payload.department_id
|
|
db.commit()
|
|
if payload.rename_dify and group.dify_dataset_id and payload.name and payload.name != old_name:
|
|
dify = DifyService()
|
|
dify.update_dataset(dataset_id=group.dify_dataset_id, name=payload.name)
|
|
db.refresh(group)
|
|
return serialize_group(group)
|
|
|
|
|
|
@router.delete("/{group_id}")
|
|
def delete_group(
|
|
group_id: int,
|
|
delete_dify: bool = Query(False),
|
|
db: Session = Depends(get_db),
|
|
admin: User = Depends(require_admin),
|
|
):
|
|
ensure_group_access(db, admin, group_id)
|
|
group = (
|
|
db.query(Group)
|
|
.options(joinedload(Group.department))
|
|
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
|
.filter(Group.id == group_id)
|
|
.first()
|
|
)
|
|
if not group:
|
|
raise HTTPException(status_code=404, detail="Group not found.")
|
|
|
|
running_job = (
|
|
db.query(Job)
|
|
.filter(Job.group_id == group.id, Job.status.in_(["queued", "running"]))
|
|
.first()
|
|
)
|
|
if running_job:
|
|
raise HTTPException(status_code=409, detail="Group has running jobs and cannot be deleted.")
|
|
|
|
if delete_dify and group.dify_dataset_id:
|
|
dify = DifyService()
|
|
dify.delete_dataset(dataset_id=group.dify_dataset_id)
|
|
|
|
for document in group.documents:
|
|
_cleanup_document_storage(document)
|
|
|
|
db.query(Job).filter(Job.group_id == group.id).delete(synchronize_session=False)
|
|
for document in list(group.documents):
|
|
db.delete(document)
|
|
db.delete(group)
|
|
db.commit()
|
|
return {"deleted": True}
|
|
|
|
|
|
@router.get("/{group_id}/files")
|
|
def list_group_files(
|
|
group_id: int,
|
|
q: str | None = Query(None),
|
|
status: str | None = Query(None),
|
|
sync_status: str | None = Query(None),
|
|
file_type: str | None = Query(None),
|
|
uploaded_from: str | None = Query(None),
|
|
uploaded_to: str | None = Query(None),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
ensure_group_access(db, user, group_id)
|
|
query = (
|
|
db.query(Document)
|
|
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
|
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
|
|
.order_by(Document.updated_at.desc())
|
|
)
|
|
documents = query.all()
|
|
filtered: list[Document] = []
|
|
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
|
|
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
|
|
for document in documents:
|
|
version = current_version(document)
|
|
if version is None:
|
|
continue
|
|
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
|
|
if q and q.lower() not in document.title.lower():
|
|
continue
|
|
if status and version.convert_status != status:
|
|
continue
|
|
if sync_status and version.sync_status != sync_status:
|
|
continue
|
|
if file_type and version.source_ext != file_type:
|
|
continue
|
|
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
|
|
continue
|
|
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
|
|
continue
|
|
filtered.append(document)
|
|
return {"data": [serialize_document(document) for document in filtered]}
|
|
|
|
|
|
@router.get("/{group_id}/dify-diff")
|
|
def get_group_dify_diff(
|
|
group_id: int,
|
|
q: str | None = Query(None),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
ensure_group_access(db, user, group_id)
|
|
group = (
|
|
db.query(Group)
|
|
.options(joinedload(Group.department))
|
|
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
|
.filter(Group.id == group_id)
|
|
.first()
|
|
)
|
|
if not group:
|
|
raise HTTPException(status_code=404, detail="Group not found.")
|
|
|
|
term = (q or "").strip().lower()
|
|
dify = DifyService() if group.dify_dataset_id else None
|
|
rows = _build_diff_rows(
|
|
knowledge_base_name=group.name,
|
|
dataset_id=group.dify_dataset_id,
|
|
local_docs=_local_documents_for_group(group),
|
|
remote_docs=_remote_documents_for_dataset(dify, group.dify_dataset_id) if dify else {},
|
|
group=group,
|
|
term=term,
|
|
)
|
|
return {"group": serialize_group(group), "summary": _summarize_diff_rows(rows), "rows": rows}
|