from __future__ import annotations from datetime import date, timedelta from app.database import SessionLocal from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess def _token(client): response = client.post("/api/auth/login", json={"username": "admin", "password": "admin123456"}) return response.json()["access_token"] def _headers(client): return {"Authorization": f"Bearer {_token(client)}"} def test_duplicate_upload_is_detected(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) client.post("/api/groups", json={"name": "quality", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] first = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) assert len(first.json()["created"]) == 1 second = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) assert len(second.json()["duplicates"]) == 1 def test_upload_rejects_more_than_500_files(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) client.post("/api/groups", json={"name": "bulk-limit", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} files = [("files", (f"sample-{index}.pdf", b"pdf", "application/pdf")) for index in range(501)] response = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) assert response.status_code == 400 assert response.json()["detail"] == "Batch upload accepts at most 500 files at a time." def test_same_title_creates_new_version(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) client.post("/api/groups", json={"name": "risk", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} first_file = [("files", ("policy.docx", b"abc", "application/octet-stream"))] second_file = [("files", ("policy.docx", b"abcd", "application/octet-stream"))] client.post("/api/files/upload", data=payload, files=first_file, headers=_headers(client)) client.post("/api/files/upload", data=payload, files=second_file, headers=_headers(client)) db = SessionLocal() try: document = db.query(Document).filter(Document.group_id == 1, Document.title == "policy").first() assert document is not None versions = db.query(DocumentVersion).filter(DocumentVersion.document_id == document.id).all() assert len(versions) == 2 finally: db.close() def test_group_rename_endpoint(client): client.post("/api/groups", json={"name": "safety", "description": "", "department_id": 1}, headers=_headers(client)) response = client.patch("/api/groups/1", json={"name": "EHS", "rename_dify": False}, headers=_headers(client)) assert response.status_code == 200 assert response.json()["name"] == "EHS" def test_group_name_can_repeat_in_different_departments(client): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None department = Department(name="second-dept", description="secondary") db.add(department) db.commit() db.refresh(department) db.add(UserDepartmentAccess(user_id=admin.id, department_id=department.id)) db.commit() finally: db.close() first = client.post( "/api/groups", json={"name": "shared-name", "description": "", "department_id": 1}, headers=_headers(client), ) assert first.status_code == 200 second = client.post( "/api/groups", json={"name": "shared-name", "description": "", "department_id": 2}, headers=_headers(client), ) assert second.status_code == 200 assert second.json()["department_id"] == 2 def test_group_rename_returns_conflict_within_same_department(client): first = client.post("/api/groups", json={"name": "dept-a", "description": "", "department_id": 1}, headers=_headers(client)) second = client.post("/api/groups", json={"name": "dept-b", "description": "", "department_id": 1}, headers=_headers(client)) assert first.status_code == 200 assert second.status_code == 200 response = client.patch("/api/groups/2", json={"name": "dept-a", "rename_dify": False}, headers=_headers(client)) assert response.status_code == 409 assert response.json()["detail"] == "Group already exists." def test_group_delete_endpoint(client): client.post("/api/groups", json={"name": "archive", "description": "", "department_id": 1}, headers=_headers(client)) response = client.delete("/api/groups/1", headers=_headers(client)) assert response.status_code == 200 listed = client.get("/api/groups", headers=_headers(client)) assert listed.status_code == 200 assert listed.json()["data"] == [] def test_group_delete_with_documents_and_dify(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) deleted = {} def fake_delete_dataset(self, *, dataset_id: str): deleted["dataset_id"] = dataset_id monkeypatch.setattr("app.api.groups.DifyService.delete_dataset", fake_delete_dataset) client.post("/api/groups", json={"name": "cleanup", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) db = SessionLocal() try: group = db.query(Document).filter(Document.group_id == 1).first().group group.dify_dataset_id = "dataset-123" job = db.query(Job).filter(Job.group_id == 1).first() job.status = "success" db.commit() finally: db.close() response = client.delete("/api/groups/1?delete_dify=true", headers=_headers(client)) assert response.status_code == 200 assert deleted["dataset_id"] == "dataset-123" db = SessionLocal() try: assert db.query(Document).count() == 0 finally: db.close() def test_group_delete_rejects_running_jobs(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) client.post("/api/groups", json={"name": "active", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) response = client.delete("/api/groups/1", headers=_headers(client)) assert response.status_code == 409 def test_group_list_includes_document_count(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) client.post("/api/groups", json={"name": "filled", "description": "", "department_id": 1}, headers=_headers(client)) client.post("/api/groups", json={"name": "empty", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) response = client.get("/api/groups", headers=_headers(client)) assert response.status_code == 200 counts = {item["name"]: item["document_count"] for item in response.json()["data"]} assert counts["filled"] == 1 assert counts["empty"] == 0 def test_group_dify_diff_reports_local_remote_and_attention(client, monkeypatch): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None group = Group(name="diff-group", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-123") db.add(group) db.commit() db.refresh(group) local_only = Document(group_id=group.id, title="local only", created_by_id=admin.id, is_deleted=False) attention = Document(group_id=group.id, title="attention", created_by_id=admin.id, is_deleted=False) synced = Document(group_id=group.id, title="matched", created_by_id=admin.id, is_deleted=False) db.add_all([local_only, attention, synced]) db.commit() db.refresh(local_only) db.refresh(attention) db.refresh(synced) local_only_version = DocumentVersion( document_id=local_only.id, version_no=1, is_current=True, source_filename="local only.docx", source_ext=".docx", source_path="local-only.docx", source_sha256="hash-local", file_size=1, uploader_id=admin.id, convert_status="success", sync_status="unsynced", ) attention_version = DocumentVersion( document_id=attention.id, version_no=1, is_current=True, source_filename="attention.docx", source_ext=".docx", source_path="attention.docx", source_sha256="hash-attention", file_size=1, uploader_id=admin.id, convert_status="success", sync_status="sync_failed", ) synced_version = DocumentVersion( document_id=synced.id, version_no=1, is_current=True, source_filename="matched.docx", source_ext=".docx", source_path="matched.docx", source_sha256="hash-matched", file_size=1, uploader_id=admin.id, convert_status="success", sync_status="synced", ) db.add_all([local_only_version, attention_version, synced_version]) db.commit() db.refresh(attention_version) db.refresh(synced_version) db.add_all( [ DifySyncRecord( version_id=attention_version.id, dataset_id="dataset-123", remote_document_id="remote-attention", status="sync_failed", ), DifySyncRecord( version_id=synced_version.id, dataset_id="dataset-123", remote_document_id="remote-matched", status="synced", ), ] ) db.commit() finally: db.close() class FakeRemote: def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True): self.id = document_id self.name = name self.indexing_status = indexing_status self.display_status = display_status self.enabled = enabled class FakeDifyService: def list_documents(self, *, dataset_id: str, limit: int = 100): assert dataset_id == "dataset-123" assert limit == 100 return [ FakeRemote("remote-attention", "attention", "indexing"), FakeRemote("remote-matched", "matched", "completed"), FakeRemote("remote-only", "remote only", "completed"), ] monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) response = client.get("/api/groups/1/dify-diff", headers=_headers(client)) assert response.status_code == 200 payload = response.json() assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 1, "attention": 1} rows = {row["display_name"]: row for row in payload["rows"]} assert rows["local only"]["status"] == "local_only" assert rows["remote only"]["status"] == "dify_only" assert rows["attention"]["status"] == "attention" assert rows["matched"]["status"] == "matched" def test_group_dify_diff_keeps_multiple_remote_documents_with_same_stem(client, monkeypatch): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None group = Group(name="duplicate-stem", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-stem") db.add(group) db.commit() db.refresh(group) document = Document(group_id=group.id, title="policy", created_by_id=admin.id, is_deleted=False) db.add(document) db.commit() db.refresh(document) version = DocumentVersion( document_id=document.id, version_no=1, is_current=True, source_filename="policy.docx", source_ext=".docx", source_path="policy.docx", source_sha256="hash-policy", file_size=1, uploader_id=admin.id, convert_status="success", sync_status="synced", ) db.add(version) db.commit() db.refresh(version) db.add( DifySyncRecord( version_id=version.id, dataset_id="dataset-stem", remote_document_id="remote-policy-docx", status="synced", ) ) db.commit() finally: db.close() class FakeRemote: def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True): self.id = document_id self.name = name self.indexing_status = indexing_status self.display_status = display_status self.enabled = enabled class FakeDifyService: def list_documents(self, *, dataset_id: str, limit: int = 100): assert dataset_id == "dataset-stem" return [ FakeRemote("remote-policy-docx", "policy.docx", "completed"), FakeRemote("remote-policy-pdf", "policy.pdf", "completed"), ] monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) response = client.get("/api/groups/1/dify-diff", headers=_headers(client)) assert response.status_code == 200 payload = response.json() assert payload["summary"] == {"matched": 1, "local_only": 0, "dify_only": 1, "attention": 0} assert len(payload["rows"]) == 2 rows = {(row["display_name"], row["status"]) for row in payload["rows"]} assert ("policy", "matched") in rows assert ("policy.pdf", "dify_only") in rows def test_global_dashboard_summary_and_dify_diff(client, monkeypatch): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None blocked_department = Department(name="blocked-global", description="hidden") db.add(blocked_department) db.commit() db.refresh(blocked_department) linked_group = Group(name="kb-linked", description="", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-linked") local_only_group = Group(name="kb-local", description="", created_by_id=admin.id, department_id=1) hidden_group = Group( name="kb-hidden", description="", created_by_id=admin.id, department_id=blocked_department.id, dify_dataset_id="dataset-hidden", ) db.add_all([linked_group, local_only_group, hidden_group]) db.commit() db.refresh(linked_group) db.refresh(local_only_group) db.refresh(hidden_group) linked_document = Document(group_id=linked_group.id, title="alpha", created_by_id=admin.id, is_deleted=False) running_document = Document(group_id=local_only_group.id, title="beta", created_by_id=admin.id, is_deleted=False) hidden_document = Document(group_id=hidden_group.id, title="secret", created_by_id=admin.id, is_deleted=False) db.add_all([linked_document, running_document, hidden_document]) db.commit() db.refresh(linked_document) db.refresh(running_document) db.refresh(hidden_document) linked_version = DocumentVersion( document_id=linked_document.id, version_no=1, is_current=True, source_filename="alpha.docx", source_ext=".docx", source_path="alpha.docx", source_sha256="hash-alpha", file_size=1, uploader_id=admin.id, convert_status="success", sync_status="synced", ) running_version = DocumentVersion( document_id=running_document.id, version_no=1, is_current=True, source_filename="beta.docx", source_ext=".docx", source_path="beta.docx", source_sha256="hash-beta", file_size=1, uploader_id=admin.id, convert_status="running", sync_status="unsynced", ) hidden_version = DocumentVersion( document_id=hidden_document.id, version_no=1, is_current=True, source_filename="secret.docx", source_ext=".docx", source_path="secret.docx", source_sha256="hash-secret", file_size=1, uploader_id=admin.id, convert_status="success", sync_status="synced", ) db.add_all([linked_version, running_version, hidden_version]) db.commit() db.refresh(linked_version) db.refresh(hidden_version) db.add_all( [ DifySyncRecord( version_id=linked_version.id, dataset_id="dataset-linked", remote_document_id="remote-alpha", status="synced", ), DifySyncRecord( version_id=hidden_version.id, dataset_id="dataset-hidden", remote_document_id="remote-secret", status="synced", ), ] ) db.commit() finally: db.close() class FakeDataset: def __init__(self, dataset_id: str, name: str): self.id = dataset_id self.name = name class FakeRemote: def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True): self.id = document_id self.name = name self.indexing_status = indexing_status self.display_status = display_status self.enabled = enabled class FakeDifyService: def list_datasets(self): return [ FakeDataset("dataset-linked", "kb-linked"), FakeDataset("dataset-hidden", "kb-hidden"), FakeDataset("dataset-remote", "kb-remote"), ] def list_documents(self, *, dataset_id: str, limit: int = 100): if dataset_id == "dataset-linked": return [FakeRemote("remote-alpha", "alpha", "completed")] if dataset_id == "dataset-hidden": return [FakeRemote("remote-secret", "secret", "completed")] if dataset_id == "dataset-remote": return [FakeRemote("remote-gamma", "gamma", "completed")] return [] monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) summary_response = client.get("/api/groups/summary", headers=_headers(client)) assert summary_response.status_code == 200 assert summary_response.json() == { "knowledge_base_count": 2, "file_count": 2, "running_count": 1, } diff_response = client.get("/api/groups/dify-diff-global", headers=_headers(client)) assert diff_response.status_code == 200 payload = diff_response.json() assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 0, "attention": 0} rows = {(row["knowledge_base"]["name"], row["display_name"]): row for row in payload["rows"]} assert rows[("kb-linked", "alpha")]["status"] == "matched" assert rows[("kb-local", "beta")]["status"] == "local_only" assert ("kb-remote", "gamma") not in rows assert ("kb-hidden", "secret") not in rows def test_import_dify_document_into_existing_group(client, monkeypatch): client.post("/api/groups", json={"name": "imports", "description": "", "department_id": 1}, headers=_headers(client)) class FakeSegment: def __init__(self, content: str, position: int): self.content = content self.position = position class FakeDifyService: def get_document_detail(self, *, dataset_id: str, document_id: str): assert dataset_id == "dataset-import" assert document_id == "remote-1" return {"name": "policy.docx", "indexing_status": "completed"} def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100): assert limit == 100 return [FakeSegment("hello world", 1), FakeSegment("from dify", 2)] def get_upload_file(self, *, dataset_id: str, document_id: str): return None monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) response = client.post( "/api/groups/import-dify-document", json={ "group_id": 1, "dataset_id": "dataset-import", "remote_document_id": "remote-1", "knowledge_base_name": "imports", }, headers=_headers(client), ) assert response.status_code == 200 payload = response.json() assert payload["group_id"] == 1 assert payload["document"]["title"] == "policy" assert payload["document"]["current_version"]["sync_status"] == "synced" assert payload["document"]["current_version"]["convert_status"] == "success" assert payload["document"]["current_version"]["source_ext"] == ".md" db = SessionLocal() try: group = db.query(Group).filter(Group.id == 1).first() assert group is not None assert group.dify_dataset_id == "dataset-import" sync_record = db.query(DifySyncRecord).first() assert sync_record is not None assert sync_record.remote_document_id == "remote-1" assert sync_record.status == "synced" finally: db.close() def test_import_dify_document_creates_group_for_remote_only_dataset(client, monkeypatch): class FakeSegment: def __init__(self, content: str, position: int): self.content = content self.position = position class FakeDifyService: def get_document_detail(self, *, dataset_id: str, document_id: str): assert dataset_id == "dataset-remote-only" return {"name": "remote-only.md", "indexing_status": "completed"} def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100): return [FakeSegment("# Remote\n\nbody", 1)] def get_upload_file(self, *, dataset_id: str, document_id: str): return None monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) response = client.post( "/api/groups/import-dify-document", json={ "dataset_id": "dataset-remote-only", "remote_document_id": "remote-doc", "knowledge_base_name": "remote-only-kb", }, headers=_headers(client), ) assert response.status_code == 200 payload = response.json() assert payload["group_name"] == "remote-only-kb" assert payload["document"]["title"] == "remote-only" db = SessionLocal() try: group = db.query(Group).filter(Group.name == "remote-only-kb").first() assert group is not None document = db.query(Document).filter(Document.group_id == group.id, Document.title == "remote-only").first() assert document is not None finally: db.close() def test_import_dify_document_requires_department_when_admin_has_no_primary_department(client): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None admin.primary_department_id = None db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id).delete() db.commit() finally: db.close() response = client.post( "/api/groups/import-dify-document", json={ "dataset_id": "dataset-remote-only", "remote_document_id": "remote-doc", "knowledge_base_name": "remote-only-kb", }, headers=_headers(client), ) assert response.status_code == 400 assert response.json()["detail"] == "Department is required for Dify import." def test_group_files_include_uploader_and_date_filter(client, monkeypatch): monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) client.post("/api/groups", json={"name": "ops", "description": "", "department_id": 1}, headers=_headers(client)) payload = {"group_id": "1"} files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) baseline = client.get("/api/groups/1/files", headers=_headers(client)) assert baseline.status_code == 200 uploaded_at = baseline.json()["data"][0]["current_version"]["uploaded_at"] actual_date = uploaded_at.split("T")[0] tomorrow = (date.fromisoformat(actual_date) + timedelta(days=1)).isoformat() listed = client.get( f"/api/groups/1/files?uploaded_from={actual_date}&uploaded_to={actual_date}&file_type=.docx", headers=_headers(client), ) assert listed.status_code == 200 row = listed.json()["data"][0] assert row["current_version"]["uploaded_by"]["username"] == "admin" future = client.get(f"/api/groups/1/files?uploaded_from={tomorrow}", headers=_headers(client)) assert future.status_code == 200 assert future.json()["data"] == []