import { createUuid } from '../lib/uuid' import { useCallback, useEffect, useRef, useState } from 'react' import { Link, useSearchParams } from 'react-router' import { Search, Star, Sparkles, Building2, ArrowRight, ExternalLink, Layers, SlidersHorizontal, Play, Pencil, Trash2 } from 'lucide-react' import { api, ApiError } from '../lib/api' import { useStore } from '../lib/store' import { useTaskEvents } from '../hooks/useTaskEvents' import type { AgentTask } from '../hooks/useTaskEvents' import type { SearchQuery, SearchReport, SearchHistory, SearchScheme } from '../lib/day2' import { initialQuery, beijingDate, registrationDate, inputClass, words, message, time } from '../lib/day2' import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton' import { BEE_IMG } from '../lib/assets' import { PrototypeDialog } from '../components/PrototypeDialog' import { MatchWeightsDialog } from '../components/MatchWeightsDialog' import { OpportunityTable } from '../components/OpportunityTable' import type { AnalysisPanelState } from '../components/AiPanel' import type { WatchItem } from '../lib/day2' import { taskStates } from '../lib/day3' import { RESULT_STATUSES } from '../types' /** D2 页面只读服务端事实和匹配度;切换历史 Tab 不执行供应商请求。 */ export function DiscoverPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPanelState) => void }) { const { profile, watch } = useStore() const [params, setParams] = useSearchParams() const [query, setQuery] = useState(() => ({ ...initialQuery(), beginDate: beijingDate(29) })) const [keyword, setKeyword] = useState('') const [range, setRange] = useState('30') const [regionText, setRegionText] = useState('') const [limits, setLimits] = useState({ maxCalls: 5, maxCostUnits: 10 }) const [budget, setBudget] = useState({ maxCalls: 2, maxCostUnits: 2 }) const [schemes, setSchemes] = useState([]) const [history, setHistory] = useState([]) const selected = params.get('batch') ?? history.find(run => run.schemeId)?.id ?? null const [schemeName, setSchemeName] = useState('') const [editing, setEditing] = useState(null) const [revision, setRevision] = useState(0) const { task, error: streamError } = useTaskEvents(selected, revision) const [busy, setBusy] = useState(false) const [error, setError] = useState('') const [showSchemes, setShowSchemes] = useState(false) const [showWeights, setShowWeights] = useState(false) const [showSchemeForm, setShowSchemeForm] = useState(false) const [watchPreview, setWatchPreview] = useState([]) const [deleteScheme, setDeleteScheme] = useState(null) // 收费请求失败且结果未知时保留原键;用户显式修改请求才创建新键。 const pending = useRef<{ fingerprint: string; key: string } | null>(null) const keyFor = (value: unknown) => { const fingerprint = JSON.stringify(value) if (pending.current?.fingerprint !== fingerprint) pending.current = { fingerprint, key: createUuid() } return pending.current.key } const reload = useCallback(async () => { const [saved, runs, allowed] = await Promise.all([api('/search-schemes'), api('/searches'), api<{ maxCalls: number; maxCostUnits: number }>('/system/limits')]) setSchemes(saved); setHistory(runs); setLimits(allowed) setBudget(current => ({ maxCalls: Math.min(current.maxCalls, allowed.maxCalls), maxCostUnits: Math.min(current.maxCostUnits, allowed.maxCostUnits) })) }, []) useEffect(() => { void reload().catch(e => setError(message(e))) }, [reload]) const update = (key: K, value: SearchQuery[K]) => setQuery(current => ({ ...current, [key]: value })) const runAction = async (action: () => Promise) => { if (busy) return setBusy(true); setError('') try { await action() } catch (e) { setError(message(e)); if (e instanceof ApiError && e.status === 409) await reload().catch(() => {}) } finally { setBusy(false) } } const choose = (id: string) => { setParams({ batch: id }); setError('') } const submit = () => runAction(async () => { const conditions = { ...query, keywords: keyword.split(/[\s、,,;;]+/).filter(Boolean) } if (conditions.keywords.length === 0 && conditions.mode !== 'MARKET') throw new Error('请填写关键词,使用逗号分隔') if (conditions.beginDate > conditions.endDate) throw new Error('开始日期不能晚于结束日期') const payload = { conditions, ...budget } const next = await api('/searches', { method: 'POST', headers: { 'Idempotency-Key': keyFor(payload) }, body: JSON.stringify(payload) }) pending.current = null; choose(next.id); setRevision(v => v + 1); await reload() }) // 保存仅登记方案;执行按钮才发起收费检索,编辑方案不触碰旧任务。 const saveScheme = () => runAction(async () => { if (!schemeName.trim()) throw new Error('请填写方案名称') if (!keyword.trim() && query.mode !== 'MARKET') throw new Error('请填写方案关键词') if (query.beginDate > query.endDate) throw new Error('开始日期不能晚于结束日期') await api(`/search-schemes${editing ? `/${editing.id}` : ''}`, { method: editing ? 'PUT' : 'POST', body: JSON.stringify({ name: schemeName.trim(), version: editing?.version ?? 0, conditions: { ...query, keywords: keyword.split(/[\s、,,;;]+/).filter(Boolean) } }) }) setEditing(null); setSchemeName(''); setShowSchemeForm(false); await reload() }) // 原型只展示本次检索结果;服务端仍保留完整快照,不在页面另加审计与调试区域。 const report = task?.result as SearchReport | null const dirty = !!report && JSON.stringify({ ...query, keywords: keyword.split(/[\s、,,;;]+/).filter(Boolean) }) !== JSON.stringify(report.conditions) const active = task && !['SUCCEEDED', 'FAILED', 'PARTIAL', 'CANCELLED'].includes(task.status) && !task.status.startsWith('WAITING_') // 问候条使用北京时间;仅展示服务端已有关注,不以原型示例公司或示例项目填充。 const local = new Date(new Date().toLocaleString('en-US', { timeZone: 'Asia/Shanghai' })) const hour = local.getHours() const greeting = hour < 6 ? '夜深了' : hour < 9 ? '早上好' : hour < 12 ? '上午好' : hour < 14 ? '中午好' : hour < 18 ? '下午好' : '晚上好' const dateLabel = `${local.getMonth() + 1}月${local.getDate()}日 星期${'日一二三四五六'[local.getDay()]}` useEffect(() => { let active = true void api('/watch').then(rows => { if (active) setWatchPreview(rows) }).catch(e => { if (active) setError(message(e)) }) return () => { active = false } }, [watch]) const dueSoon = watchPreview.filter(row => { const date = registrationDate(row.summary?.schedule) return date !== null && date >= beijingDate() && date <= beijingDate(-7) }).length // 原型只为“当前结果”和每个已执行方案保留一个页签,不额外展示逐次运行的审计历史。 const schemeRuns = history.filter((run, index) => run.schemeId && history.findIndex(other => other.schemeId === run.schemeId) === index) const manualRun = history.find(run => !run.schemeId) const conditions = report?.conditions const conditionLabel = conditions ? [conditions.keywords.length ? `关键词「${conditions.keywords.join(' ')}」` : '', (conditions.mode === 'LEADS' ? conditions.preferredRegions : conditions.hardRegions).length ? `地区「${(conditions.mode === 'LEADS' ? conditions.preferredRegions : conditions.hardRegions).join('、')}」` : '', `发布于${Math.round((Date.parse(conditions.endDate) - Date.parse(conditions.beginDate)) / 86400000) + 1}天内`].filter(Boolean).join(' · ') : '' return
{profile.completed ?
如昼小助手

{greeting},{profile.companyName.replace(/(有限责任公司|有限公司)$/, '') || '朋友'}

{dateLabel}

AI 洞察

重点关注 {watch.length} 个项目, {dueSoon} 个临近报名截止,已有结果 {watch.filter(w => RESULT_STATUSES.includes(w.status)).length} 个

:

让 AI 像投标专员一样帮你筛项目

花 2 分钟填好资质、代表业绩和常做区域,之后每条项目都会自动给出贴合度打分和「先看哪条」的建议——不用再一条条读公告。

立即完善档案
} {(error || streamError) &&
{error || streamError}
}

项目检索

setShowWeights(true)} className="!px-3 !py-1.5 text-xs"> 匹配度权重 setShowSchemes(true)} className="!px-3 !py-1.5 text-xs"> 检索方案
{ e.preventDefault(); void submit() }}>
setKeyword(e.target.value)} placeholder="关键词(空格分隔多个,如:智慧水务 监测)" className={`${inputClass} col-span-12 lg:col-span-4`} /> { setRegionText(e.target.value); update(query.mode === 'LEADS' ? 'preferredRegions' : 'hardRegions', words(e.target.value)) }} placeholder="地区(如:浙江)" className={`${inputClass} col-span-6 lg:col-span-2`} />
{(['Min', 'Max'] as const).map((bound, i) => { const key = (query.mode === 'LEADS' ? `budget${bound}Wan` : `hard${bound}Wan`) as 'budgetMinWan' | 'budgetMaxWan' | 'hardMinWan' | 'hardMaxWan'; return
{i > 0 && ~} update(key, e.target.value === '' ? null : Number(e.target.value))} placeholder={i ? '上限(万元)' : '预算下限'} className={`${inputClass} min-w-0 font-num`} />
})}
检索
{dirty &&

检索条件已修改但尚未重新执行,下方结果仍对应上一次执行的条件({report?.conditions.keywords.join(' · ')})。

}
{showWeights && setShowWeights(false)} />} { if (!busy) setShowSchemes(false) }} title="检索方案" className="w-[720px]"> {schemes.length} 个已保存的方案 { setEditing(null); setSchemeName(`方案${schemes.length + 1}`); setShowSchemeForm(true) }} className="absolute right-14 top-4 !px-3 !py-1.5 text-xs">新建方案 {!schemes.length ?

还没有检索方案,点右上角「新建方案」,把常用的检索条件存下来一键复用

:
    {schemes.map(scheme =>
  • {scheme.name}{scheme.conditions.keywords.join(' ')} · {scheme.conditions.mode === 'LEADS' ? scheme.conditions.preferredRegions.join('、') : scheme.conditions.hardRegions.join('、')} {history.find(run => run.schemeId === scheme.id) ? `最近执行 ${time(history.find(run => run.schemeId === scheme.id)!.createdAt)}` : '尚未执行'}
  • )}
} {error &&

{error}

}
{ if (!busy) setShowSchemeForm(false) }} title={editing ? '编辑检索方案' : '新建检索方案'} className="w-[520px]">
{ e.preventDefault(); void saveScheme() }} className="mt-3 space-y-3">
检索条件
setKeyword(e.target.value)} className={`${inputClass} !py-1.5 text-[13px]`} /> { setRegionText(e.target.value); update(query.mode === 'LEADS' ? 'preferredRegions' : 'hardRegions', words(e.target.value)) }} className={`${inputClass} !py-1.5 text-[13px]`} /> {(['Min', 'Max'] as const).map((bound, i) => { const key = (query.mode === 'LEADS' ? `budget${bound}Wan` : `hard${bound}Wan`) as 'budgetMinWan' | 'budgetMaxWan' | 'hardMinWan' | 'hardMaxWan'; return update(key, e.target.value === '' ? null : Number(e.target.value))} className={`${inputClass} !py-1.5 font-num text-[13px]`} /> })}
{error &&

{error}

}
setShowSchemeForm(false)}>取消{editing ? '保存修改' : '保存方案'}
{(selected || history.some(run => run.schemeId)) ?
{schemeRuns.length > 0 && }

{schemeRuns.length ? '检索结果' : '全部结果'}

{schemeRuns.length ?
{schemeRuns.map(run => )}
: report && <>共 {report.items.length} 条{conditionLabel}}
{schemeRuns.length > 0 && report &&
{conditionLabel}·{history.find(run => run.id === selected)?.schemeId ? `最近执行 ${time(history.find(run => run.id === selected)!.createdAt)}` : '手动检索'}·共 {report.items.length} 条
} {!selected &&

选择历史快照回查,或在上方设置条件开始检索。

} {selected && !task &&

正在加载任务快照…

} {task && <> {task.status !== 'SUCCEEDED' &&
{taskStates[task.status] ?? task.status}{task.question}{active && void runAction(async () => { await api(`/agent/tasks/${task.id}/cancel`, { method: 'POST' }); setRevision(v => v + 1) })}>取消后续请求}{task.status.startsWith('WAITING_') && void runAction(async () => { const conditions = task.request.opportunity; if (!conditions) return; const payload = { conditions, ...limits }; await api(`/searches/${task.id}/continue`, { method: 'POST', headers: { 'Idempotency-Key': keyFor({ continue: task.id, ...payload }) }, body: JSON.stringify(payload) }); pending.current = null; setRevision(v => v + 1) })}>{task.status === 'WAITING_BUDGET' ? `确认提高至 ${limits.maxCalls} 次 / ${limits.maxCostUnits} 积分并继续` : '已补配置,继续原任务'}}
} {report && <>{active && !report.items.length ?

正在检索并整理公告…

: }} }
: watchPreview.length > 0 ?

你重点关注的项目

共 {watch.length} 条,展示前 {Math.min(watchPreview.length, 6)} 条在上方设置条件点击「检索」,发现更多商机
    {watchPreview.slice(0, 6).map(row =>
  • {row.project.title}

    {row.project.purchaser} · {row.project.region} · {row.project.budgetWan == null ? '预算未披露' : `${row.project.budgetWan} 万元`}

    {registrationDate(row.summary?.schedule) ? `报名截止 ${registrationDate(row.summary?.schedule)}` : '截止时间未披露'}
  • )}
:

设置检索条件后点击「检索」

点击任意一行查看 AI 分析

} {deleteScheme &&

删除方案「{deleteScheme.name}」?

历史执行快照和报告会保留。

setDeleteScheme(null)}>取消 void runAction(async () => { await api(`/search-schemes/${deleteScheme.id}`, { method: 'DELETE' }); setDeleteScheme(null); await reload() })}>确认删除
}
}