diff --git a/frontend-web/src/components/assistant-ui/document-upload-popup.tsx b/frontend-web/src/components/assistant-ui/document-upload-popup.tsx new file mode 100644 index 00000000..9b2d7b17 --- /dev/null +++ b/frontend-web/src/components/assistant-ui/document-upload-popup.tsx @@ -0,0 +1,880 @@ +"use client"; + +import { + createContext, + type FC, + type ReactNode, + useCallback, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogTitle, +} from "@/components/ui/dialog"; +import { Textarea } from "@/components/ui/textarea"; +import { + Search, + Sparkles, + Moon, + BookOpen, + Loader2, + Plus, + Trash2, +} from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { toast } from "sonner"; +import { getStoredAuth } from "@/core/auth"; +import Empty from "./empty"; +import { NetworkActor } from "./network-actor"; + +// ── 适配层 ───────────────────────────────────────────────── +const writeYLog = (..._args: unknown[]) => {}; + +function authenticatedFetch(url: string, init?: RequestInit) { + const token = getStoredAuth()?.access_token; + return fetch(url, { + ...init, + headers: { + ...(init?.headers ?? {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + }); +} + +function getYUserId(): string { + if (typeof window === "undefined") return "1157761008018653184"; + try { + const raw = localStorage.getItem("deerflow.external_user_info"); + if (raw) { + const obj = JSON.parse(raw) as { yUserId?: string }; + if (obj?.yUserId) return obj.yUserId; + } + } catch {} + return "1157761008018653184"; +} + +type SearchMode = "A" | "Y" | "knowledge"; + +const searchModes = [ + { value: "A", label: "A系统", icon: Sparkles }, + { value: "Y", label: "Y系统", icon: Moon }, + { value: "knowledge", label: "知识库", icon: BookOpen }, +] as const; + +const searchTypes = [ + { value: "human", label: "人物基因库" }, + { value: "organization", label: "组织基因库" }, + { value: "community", label: "群体基因库" }, + { value: "issue", label: "议题基因库" }, + { value: "event", label: "事件基因库" }, + { value: "threat", label: "风险与机会" }, +] as const; + +// ── Context ──────────────────────────────────────────────── +interface DocumentUploadDialogContextType { + openDialog: (initialSearchText?: string) => void; + closeDialog: ( + mode?: "search", + data?: { query: string; mode: string } + ) => Promise; +} + +interface listDataItem { + id?: string | number; + name?: string; + redisKey?: string; + abstractz?: string; + checked: boolean; + title: string; + content: string; + url: string; + country?: string; + dateOfBirth?: string; + occupationData?: string; + party?: string; + sexOrGender?: string; + imagePath?: string; + mongoId?: string; + countryData?: string; + countrySingle?: string; + subtype?: string; + text?: string; + twoLevel?: string; + account_ids?: unknown[]; + community_description?: string; + community_name?: string; + community_type?: string; + create_time?: string; + creator?: string; + groups?: string; + labels?: string; + nations?: string; + params?: string; + platforms?: string; + real_total?: number; + total?: number; + update_time?: string; + virtual_total?: number; + direction?: string; + hot_num?: number; + issue_hot?: number; + issue_name?: string; + issue_type?: string; + news_num?: number; + post_num?: number; + topic?: string; + abstract?: string; + allwords?: string[]; + category?: string; + controversy_num?: number; + date?: string; + discriminant_reason?: string; + discriminant_result?: string; + doc_author?: string; + doc_ids?: string[]; + emotion_info?: string; + first_publish_time?: string; + grade?: string; + human_id_list?: string; + human_list?: string[]; + if_artificial?: number; + if_follow?: number; + if_shehua?: number; + if_show?: number; + image_path?: string; + import_num?: number; + insert_time?: string; + jw?: string; + keywords?: string[]; + location?: string[]; + location_list?: unknown[]; + location_type?: number; + longitude?: number; + media_board?: string; + media_type?: string; + nowords?: unknown[]; + onewords?: unknown[]; + organization_id_list?: string; + organization_list?: unknown[]; + raw_id?: string; + report_num?: number; + site_name?: string; + source_type?: string; + sub_category?: string; + subject?: string; + super_category?: string; + surge_num?: number; + tone?: string; + topic_id?: string; + total_num?: number; + type?: string; + userid?: string; + wx_sub_score?: string; + wx_total_score?: string; +} + +const DocumentUploadDialogContext = + createContext(null); + +export const useDocumentUploadDialog = () => { + const context = useContext(DocumentUploadDialogContext); + if (!context) { + throw new Error( + "useDocumentUploadDialog must be used within DocumentUploadDialogProvider" + ); + } + return context; +}; + +// ── Provider ─────────────────────────────────────────────── +export const DocumentUploadDialogProvider: FC<{ + children: ReactNode; + onClose?: ( + mode?: "search", + data?: { query: string; mode: string } + ) => void | Promise; + searchSpace: { id: number | string; [key: string]: unknown }; + onUploadSuccess?: () => void; +}> = ({ children, onClose, searchSpace, onUploadSuccess }) => { + const [isOpen, setIsOpen] = useState(false); + const [initialSearchText, setInitialSearchText] = useState(""); + const isClosingRef = useRef(false); + + const openDialog = useCallback((initialSearchText?: string) => { + if (isClosingRef.current) return; + setInitialSearchText(initialSearchText || ""); + setIsOpen(true); + }, []); + + const closeDialog = useCallback( + async (mode?: "search", data?: { query: string; mode: string }) => { + isClosingRef.current = true; + if (onClose) { + try { + await onClose(mode, data); + } catch (error) { + console.error("Error in Provider onClose:", error); + } + } + setIsOpen(false); + setTimeout(() => { + isClosingRef.current = false; + }, 300); + }, + [onClose] + ); + + const handleOpenChange = useCallback( + (open: boolean) => { + if (!open) { + if (!isClosingRef.current) { + void closeDialog("search", { query: "", mode: "" }); + void closeDialog(); + } + } else { + if (!isClosingRef.current) { + setIsOpen(true); + } + } + }, + [closeDialog] + ); + + return ( + + {children} + + + ); +}; + +// ── Popup content ────────────────────────────────────────── +const UPLOAD_ACCEPT = + ".pdf,.docx,.xlsx,.pptx,.html,.csv,.md,.txt,.jpg,.jpeg,.png,.bmp,.webp,.tiff,.mp3,.mp4,.wav,.webm"; + +const DocumentUploadPopupContent: FC<{ + isOpen: boolean; + onOpenChange: (open: boolean) => void; + searchSpace: { id: number | string; [key: string]: unknown }; + onUploadSuccess?: () => void; + closeDialog: ( + mode?: "search", + data?: { query: string; mode: string } + ) => Promise; + initialSearchText?: string; +}> = ({ isOpen, onOpenChange, searchSpace, onUploadSuccess, closeDialog, initialSearchText }) => { + const searchSpaceId = String(searchSpace?.id); + const backendUrl = + typeof window !== "undefined" + ? (import.meta.env.VITE_BACKEND_BASE_URL || "http://localhost:8001") + : "http://localhost:8001"; + const consumerUrl = "http://ch1.b.uat.4.cn/consumer"; + + const [searchText, setSearchText] = useState(""); + const [searchValue, setSearchValue] = useState(""); + const [activeTab, setActiveTab] = useState<"search" | "Y" | "upload" | "A" | "actor">("search"); + const [isSearching, setIsSearching] = useState(false); + const [importSources, setImportSources] = useState([]); + const [isImporting, setIsImporting] = useState(false); + const [listData, setListData] = useState([]); + const [searchType, setSearchType] = useState("human"); + const [selectedSearchSources, setSelectedSearchSources] = useState([]); + // upload tab state + const fileInputRef = useRef(null); + const [uploading, setUploading] = useState(false); + + useEffect(() => { + if (isOpen && initialSearchText) { + setSearchText(initialSearchText); + setSearchValue(initialSearchText); + } + }, [isOpen, initialSearchText]); + + if (!searchSpaceId) return null; + + const handleSuccess = () => { + onUploadSuccess?.(); + onOpenChange(false); + }; + + const searchActiveChange = async (type: "search" | "Y" | "upload" | "A" | "actor") => { + setActiveTab(type); + if (type === "A") { + await searchAChange(searchType); + } + }; + + const handleFileUpload = async (files: File[]) => { + if (!files.length) return; + setUploading(true); + try { + const token = getStoredAuth()?.access_token ?? ""; + const formData = new FormData(); + formData.append("search_space_id", searchSpaceId); + for (const file of files) { + formData.append("files", file); + } + const res = await fetch(`${backendUrl}/api/v1/documents/fileupload`, { + method: "POST", + headers: { Authorization: `Bearer ${token}` }, + body: formData, + }); + if (res.ok) { + toast.success("上传成功"); + handleSuccess(); + } else { + toast.error("上传失败,请重试"); + } + } catch { + toast.error("上传失败,请重试"); + } finally { + setUploading(false); + if (fileInputRef.current) fileInputRef.current.value = ""; + } + }; + + const handleImport = async () => { + if (selectedSearchSources.length === 0) { + toast.warning("没有可导入的来源"); + return; + } + setIsImporting(true); + const dataList = selectedSearchSources.map((item) => ({ + title: item.title, + content: item.content, + url: item.url, + })); + try { + const response = await authenticatedFetch(`${backendUrl}/api/v1/source/import`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + search_space_id: Number(searchSpaceId), + source_list: dataList, + }), + }); + if (response.ok) { + const data = await response.json() as { imported_count?: number }; + toast.success(`成功导入 ${data.imported_count || dataList.length} 个来源`); + setListData([]); + handleBatchDelete(); + } else { + const errorData = await response.json() as { detail?: string }; + toast.error(errorData.detail || "导入失败,请重试"); + } + } catch { + toast.error("导入失败,请重试"); + } finally { + setIsImporting(false); + } + }; + + const listDataCheckedChange = (index: number, checked: boolean) => { + setListData((prevSources) => { + const newSources = prevSources.map((item, aIndex) => + aIndex === index ? { ...item, checked } : item + ); + setSelectedSearchSources(newSources.filter((item) => item.checked)); + return newSources; + }); + }; + + const handleBatchDelete = () => { + setListData((prev) => prev.map((item) => ({ ...item, checked: false }))); + setSelectedSearchSources([]); + }; + + const handleAllSearch = async (searchMode: SearchMode, text: string) => { + if (isSearching || !text.trim()) return; + setIsSearching(true); + const reqBody = { + query: text, + search_space_id: searchSpaceId, + search_mode: searchMode, + }; + const reqUrl = `${backendUrl}/api/v1/source/new`; + try { + const response = await authenticatedFetch(reqUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(reqBody), + }); + if (response.ok) { + const data = await response.json() as { result: unknown[] }; + writeYLog({ optDetail: "笔记检索数据", optType: 3, reqParam: reqBody, url: reqUrl, returnParam: JSON.stringify({ data }), optResult: "0" }); + const results = data.result as listDataItem[]; + results.forEach((item) => { item.checked = false; }); + setImportSources(results); + } + } catch (error) { + writeYLog({ optDetail: "笔记检索数据", optType: 3, reqParam: reqBody, url: reqUrl, returnParam: JSON.stringify({ data: error }), optResult: "1" }); + } finally { + setIsSearching(false); + } + }; + + function urlSafeBtoa(str: string): string { + const encoder = new TextEncoder(); + const uint8Array = encoder.encode(str); + const binaryString = Array.prototype.map + .call(uint8Array, (byte: number) => String.fromCharCode(byte)) + .join(""); + return btoa(binaryString).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); + } + + const linkToA = (url: string) => { window.open(url); }; + + const queryTopicTargetHumanList = async () => { + setIsSearching(true); + const response = await authenticatedFetch(`${consumerUrl}/topicQuery/queryTopicTargetHumanList`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: "Bearer admin" }, + body: JSON.stringify({ name: searchText, page: 1, size: 50 }), + }); + if (response.ok) { + const data = await response.json() as { data: listDataItem[] }; + setIsSearching(false); + const result = data.data; + result.forEach((item) => { + item.checked = false; + item.title = item.name || ""; + item.content = item.abstractz || ""; + const redirect = urlSafeBtoa(`/gene/#/human/basic?mid=${item.id}`); + item.url = `http://present.a.uat.4.cn/present/domain?inredirect=${redirect}`; + }); + setListData(result); + } + setIsSearching(false); + }; + + const organizationSearch = async () => { + setIsSearching(true); + const response = await authenticatedFetch(`${consumerUrl}/topicQuery/queryCommunity`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: "Bearer admin" }, + body: JSON.stringify({ name: searchText, page: 1, size: 50 }), + }); + if (response.ok) { + const data = await response.json() as { data: listDataItem[] }; + setIsSearching(false); + const result = data.data; + result.forEach((item) => { + item.checked = false; + item.title = item.name || ""; + item.content = item.abstractz || ""; + const redirect = urlSafeBtoa(`/gene/#/organization/basicAttr?mid=${item.mongoId}`); + item.url = `http://present.a.uat.4.cn/present/domain?inredirect=${redirect}`; + }); + setListData(result); + } + setIsSearching(false); + }; + + const queryCommunityList = async () => { + setIsSearching(true); + const params = { keyword: searchText, page: 1, size: 50 }; + const queryString = Object.entries(params).map(([k, v]) => `${k}=${v}`).join("&"); + const response = await authenticatedFetch(`${consumerUrl}/topicQuery/queryCommunityList?${queryString}`, { + method: "GET", + headers: { "Content-Type": "application/json", Authorization: "Bearer admin" }, + }); + if (response.ok) { + const data = await response.json() as { data: listDataItem[] }; + setIsSearching(false); + const result = data.data; + result.forEach((item) => { + item.checked = false; + item.title = item.community_name || ""; + item.content = item.community_description || ""; + const redirect = urlSafeBtoa(`/gene/#/commune/basicCommune?cid=${item.id}`); + item.url = `http://present.a.uat.4.cn/present/domain?inredirect=${redirect}`; + }); + setListData(result); + } + setIsSearching(false); + }; + + const issueSearch = async () => { + setIsSearching(true); + const response = await authenticatedFetch(`${consumerUrl}/issue/list?keyword=${searchText}`, { + method: "GET", + headers: { "Content-Type": "application/json", Authorization: "Bearer admin" }, + }); + if (response.ok) { + const data = await response.json() as { data: listDataItem[] }; + setIsSearching(false); + const result = data.data; + result.forEach((item) => { + item.checked = false; + item.title = item.issue_name || ""; + item.content = item.issue_type || ""; + const redirect = encodeURIComponent(`/gene/#/issue/zzyyIssue?mid=${item.id}&event_type=issue`); + item.url = `http://present.a.uat.4.cn/present/domain?inredirect=${redirect}`; + }); + setListData(result); + } + setIsSearching(false); + }; + + const eventSearch = async () => { + setIsSearching(true); + const response = await authenticatedFetch(`${consumerUrl}/event/queryEvents`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: "Bearer admin" }, + body: JSON.stringify({ word: searchText, page: 1, size: 50, type: "hot", timeRange: "" }), + }); + if (response.ok) { + const data = await response.json() as { data: listDataItem[] }; + setIsSearching(false); + const result = data.data; + result.forEach((item) => { + item.checked = false; + const redirect = urlSafeBtoa(`/gene/#/event/basicEvent?event_type=hot&mid=${item.id}`); + item.url = `http://present.a.uat.4.cn/present/domain?inredirect=${redirect}`; + }); + setListData(result); + } + setIsSearching(false); + }; + + const topicQuery = async () => { + setIsSearching(true); + let result: listDataItem[] = []; + for (const discriminant of ["威胁", "ZJ机"]) { + const queryString = `keyword=${searchText}&discriminant=${discriminant}`; + const response = await authenticatedFetch(`${consumerUrl}/topicQuery/queryEventFromA?${queryString}`, { + method: "GET", + headers: { "Content-Type": "application/json", Authorization: "Bearer admin" }, + }); + if (response.ok) { + const data = await response.json() as { data: listDataItem[] }; + const results = data.data; + results.forEach((item) => { + item.checked = false; + const redirect = urlSafeBtoa(`/gene/#/event/basicEvent?event_type=hot&mid=${item.id}`); + item.url = `http://present.a.uat.4.cn/present/domain?inredirect=${redirect}`; + }); + result = [...result, ...results]; + } + } + setIsSearching(false); + setListData(result); + }; + + const searchAChange = async (type: string) => { + if (type === "human") await queryTopicTargetHumanList(); + else if (type === "organization") await organizationSearch(); + else if (type === "community") await queryCommunityList(); + else if (type === "issue") await issueSearch(); + else if (type === "event") await eventSearch(); + else if (type === "threat") await topicQuery(); + }; + + const searchTypeChange = (value: string) => { + setSearchType(value); + setListData([]); + void searchAChange(value); + }; + + const searchDataChange = () => { + setIsSearching(true); + setSearchValue(searchText); + setTimeout(() => setIsSearching(false), 500); + if (activeTab === "A") void searchAChange(searchType); + }; + + const yUserId = getYUserId(); + + return ( + + + 添加来源 + 从外部系统搜索并导入来源 +
+
+
+ {/* 搜索框 */} +
+