Commit 6b7eef03 authored by 王蔡翾's avatar 王蔡翾
Browse files

按照原型还原

parent 12121653
import { Check, CircuitBoard, Loader2 } from 'lucide-react'
import { useRef, useState } from 'react'
import { api } from '../lib/api'
import { useTaskEvents } from '../hooks/useTaskEvents'
import type { AgentTask } from '../hooks/useTaskEvents'
import type { ResearchReport } from '../lib/day3'
import { toolNames } from '../lib/day3'
import { inputClass, message } from '../lib/day2'
import { GhostButton, PrimaryButton } from './ui-ext/AiButton'
const labels: Record<string, string> = { fullname: '企业全称', name: '名称', title: '标题', province: '省份', city: '城市', county: '区县', industry: '行业', capital: '注册资本', size: '企业规模', business_status: '经营状态', establishment_date: '成立日期', business_scope: '经营范围', caller_count: '招标次数', winner_count: '中标次数', company_name: '企业', company_id: '主体编号', cooperation_count: '合作次数', cooperation_amount: '合作金额(元)', cooperation_amount_wan: '合作金额(万元)', last_cooperation_time: '最近合作时间', products: '合作品类', keywords: '业务词', partners: '合作伙伴', items: '公告记录', total: '平台总数', bid_id: '公告编号', pub_time: '发布时间', money: '金额(元)', money_wan: '金额(万元)', caller_name: '采购方', winner_names: '中标方', sm_names: '标的物', fulltext: '正文', competitors: '竞争者', co_bid_count: '共同投标次数', top_co_bid_products: '交锋品类', top_co_bid_callers: '共同客户', top_co_bid_provinces: '交锋区域', keyword: '关键词', count: '次数', amount: '金额(元)', buckets: '聚合结果', key: '分组', sum_amount: '金额合计(元)', total_count: '记录总数', total_amount: '金额合计(元)', content: '正文', results: '公开资料', snippet: '摘录', url: '原始来源', filename: '文件名', segments: '定位段落', locator: '位置', text: '正文', needsVision: '需视觉识别', price_stats: '价格统计', bidders: '潜在投标者', service_end_date: '服务截止时间', agency_name: '代理机构' }
function sectionTitle(section: ResearchReport['sections'][number]) {
if (section.key.endsWith(':customers')) return '历史客户'
if (section.key.endsWith(':suppliers')) return '历史供应商'
if (section.key.includes(':light:')) return `Top 竞对 ${Number(section.key.split(':').at(-1)) + 1} 基础画像`
return toolNames[section.tool] ?? section.tool
}
/** React 仅渲染文字节点,不解析供应商 HTML;外链再次限制 HTTP(S),保留签名参数。 */
function Facts({ value }: { value: unknown }) {
if (value == null || value === '') return <span className="text-ink-400">未提供</span>
if (typeof value === 'string') return /^https?:\/\//i.test(value) ? <a href={value} target="_blank" rel="noopener noreferrer" className="break-all text-brand-500 underline">查看原始来源</a> : <span className="whitespace-pre-wrap break-words">{value}</span>
if (typeof value === 'boolean') return <span>{value ? '是' : '否'}</span>
if (typeof value === 'number') return <span>{String(value)}</span>
if (Array.isArray(value)) return value.length ? <ul className="space-y-3">{value.map((item, i) => <li key={i} className="border-l-2 border-line-soft pl-3"><Facts value={item} /></li>)}</ul> : <span className="text-ink-400">本次未查到记录</span>
return <dl className="space-y-2">{Object.entries(value).map(([key, item]) => <div key={key}><dt className="text-xs text-ink-400">{labels[key] ?? key}</dt><dd className="mt-1"><Facts value={item} /></dd></div>)}</dl>
}
/** 四个调研入口共用真实 SSE、确认、取消、报告与费用组件,页面刷新只读取任务。 */
export function ResearchTask({ id, onTask }: { id: string; onTask?: (task: AgentTask) => void }) {
const [revision, setRevision] = useState(0)
const { task, error: streamError } = useTaskEvents(id, revision)
const [busy, setBusy] = useState(false), [error, setError] = useState('')
const pending = useRef<{ signature: string; key: string } | null>(null)
const report = task?.result as ResearchReport | null
const command = async (cancel: boolean, form?: HTMLFormElement) => {
if (!task || busy) return
setBusy(true); setError('')
try {
if (cancel) await api(`/agent/tasks/${id}/cancel`, { method: 'POST' })
else {
const data = new FormData(form)
const selections = { ...task.request.research?.selections }
for (const choice of report?.choices ?? []) {
const selected = data.get(choice.key)
if (selected) selections[choice.key] = String(selected)
}
const body = { ...task.request, input: String(data.get('input') ?? task.request.input), maxCalls: Number(data.get('maxCalls') ?? task.request.maxCalls), maxCostUnits: Number(data.get('maxCostUnits') ?? task.request.maxCostUnits),
...(task.request.research ? { research: { ...task.request.research, selections, acknowledgedCalls: task.status === 'WAITING_BUDGET' ? task.calls.filter(c => c.provider !== 'LOCAL').length : task.request.research.acknowledgedCalls } } : {}) }
const signature = `${id}:${JSON.stringify(body)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
await api(`/agent/tasks/${id}/continue`, { method: 'POST', body: JSON.stringify(body), headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null
}
setRevision(x => x + 1)
onTask?.(await api<AgentTask>(`/agent/tasks/${id}`))
} catch (e) { setError(message(e)) } finally { setBusy(false) }
}
if (!task) return <p role="status">{streamError || '正在读取任务…'}</p>
const complete = ['SUCCEEDED', 'FAILED', 'PARTIAL', 'CANCELLED'].includes(task.status)
// 原型的回复由“Skill 调用进展 + 正文”组成,只把真实执行和报告映射到这两个区域。
// 调用账本、模型参数和刷新按钮不属于原型,不再额外插入消息内容。
return <section className="rounded-card border border-line-soft bg-white px-4 py-3 shadow-card">
<div className="mb-2 rounded-ctrl border border-line-soft bg-canvas px-3 py-2">
<div className="flex items-center gap-2 text-[12px] font-semibold text-brand-500">{complete ? <CircuitBoard size={13} /> : <Loader2 size={13} className="animate-spin" />} Skill 调用进展</div>
<ul className="mt-1 space-y-1">{task.calls.map(call => <li key={String(call.id)} className="flex items-center gap-1.5 text-[12px] text-ink-600">{call.status === 'SUCCEEDED' ? <Check size={12} className="text-ok-500" /> : <span className="h-3 w-3" />}{toolNames[String(call.tool_name)] ?? String(call.tool_name)}</li>)}</ul>
</div>
{(error || streamError) && <p role="alert" className="mb-2 text-xs text-bad-500">{error || streamError}</p>}
{(task.status.startsWith('WAITING_') || task.status === 'FAILED') && task.question && <p className="mb-3 text-[13px] text-ink-600">{task.question}</p>}
{task.status.startsWith('WAITING_') && <form key={`${id}:${revision}:${task.status}`} onSubmit={e => { e.preventDefault(); void command(false, e.currentTarget) }} className="space-y-3 rounded-ctrl bg-canvas p-4">
{task.status === 'WAITING_ENTITY' && report?.choices?.map(choice => <label key={choice.key} className="block text-sm">{choice.key.startsWith('entity:') ? `企业 ${Number(choice.key.split(':')[1]) + 1}` : choice.key === 'buyer:entity' ? '采购方主体' : '项目公告'}
<select name={choice.key} required defaultValue={choice.selected} className={`${inputClass} mt-1`}><option value="">选择本次明确主体</option>{choice.options.map(option => <option key={option.id} value={option.id}>{option.name} · {option.region || '地区未知'} · {option.id}</option>)}</select>
</label>)}
{task.status === 'WAITING_INPUT' && task.operation === 'BID_RESEARCH' && <label className="block text-sm">完整公开项目标题<input name="input" defaultValue={task.request.input} maxLength={2000} className={inputClass} /></label>}
{task.status === 'WAITING_BUDGET' && <><p className="text-xs text-ink-600">已发生费用保留。继续从下一步执行;未知积分需先核对账单,首个未知单价请求可能超出积分上限。</p><div className="grid grid-cols-2 gap-3"><label className="text-sm">累计调用上限<input name="maxCalls" type="number" min={1} max={task.request.research?.companies.length === 1 && task.operation === 'COMPANY_RESEARCH' ? 18 : 25} defaultValue={task.request.maxCalls} required className={inputClass} /></label><label className="text-sm">累计积分上限<input name="maxCostUnits" type="number" min="0.01" max="1000" step="0.01" defaultValue={task.request.maxCostUnits} required className={inputClass} /></label></div><label className="flex gap-2 text-sm"><input type="checkbox" required />我已核对现有调用与费用,确认继续后续请求</label></>}
<div className="flex gap-2"><GhostButton disabled={busy} onClick={() => void command(true)}>取消</GhostButton><PrimaryButton disabled={busy} type="submit">确认并继续</PrimaryButton></div>
</form>}
{report && <div className="space-y-4 text-sm leading-7 text-ink-600">
{report.observations?.map((item, index) => <p key={index}>{item.text}</p>)}
{report.ownFit && <div><h3 className="font-semibold text-ink-900">结合公司档案对照</h3><p>贴合度参考:{report.ownFit.match.score ?? '资料不足'} 分</p>{Object.entries(report.ownFit.match.dimensions).map(([key, dimension]) => <p key={key} className="text-[13px]">{dimension.basis}</p>)}</div>}
{report.commonCustomers && <div><h3 className="font-semibold text-ink-900">共同客户</h3><p>{report.commonCustomers.join('、') || '当前样本未检出共同客户'}</p></div>}
{report.sections?.map(section => <div key={section.key}><h3 className="mb-2 font-semibold text-ink-900">{sectionTitle(section)}</h3><Facts value={section.data} /></div>)}
{report.gaps?.length > 0 && <ul className="list-disc space-y-1 pl-5 text-[13px]">{report.gaps.map(gap => <li key={gap}>{gap}</li>)}</ul>}
</div>}
</section>
}
......@@ -4,6 +4,8 @@ import { Compass, Star, MessagesSquare, Building2, Plus, Pencil, Trash2, Search,
import { motion, AnimatePresence } from 'framer-motion'
import { cn } from '@/lib/utils'
import { useStore } from '@/lib/store'
import { api } from '../lib/api'
import { conversationsChanged, useConversations } from '../lib/conversations'
import Pill from '@/components/ui-ext/Pill'
import { GhostButton, PrimaryButton } from '@/components/ui-ext/AiButton'
......@@ -15,20 +17,26 @@ const NAV = [
]
export default function Sidebar({ onLogout }: { onLogout: () => void }) {
const { profile, watch, research, saveConversation, deleteConversation } = useStore()
const { profile, watch } = useStore()
const location = useLocation()
const navigate = useNavigate()
const [renaming, setRenaming] = useState<string | null>(null)
const [renameText, setRenameText] = useState('')
const [histQuery, setHistQuery] = useState('')
const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
const { items: research, error: historyError, more, load } = useConversations(histQuery)
const [actionError, setActionError] = useState('')
const researchOpen = location.pathname === '/research'
const filtered = research.filter(c => !histQuery.trim() || c.title.includes(histQuery.trim()))
const filtered = research
const submitRename = (id: string) => {
const submitRename = async (id: string) => {
const c = research.find(x => x.id === id)
if (c && renameText.trim()) saveConversation({ ...c, title: renameText.trim() })
setRenaming(null)
if (!c || !renameText.trim() || renameText.trim() === c.title) return
try {
await api(`/conversations/${id}`, { method: 'PATCH', body: JSON.stringify({ title: renameText.trim(), version: c.version }) })
setActionError(''); conversationsChanged()
} catch (e) { setActionError(e instanceof Error ? e.message : '重命名失败') }
}
return (
......@@ -77,7 +85,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
<div className="flex min-h-0 flex-1 flex-col border-t border-line-soft/60 fade-up">
<div className="flex items-center justify-between px-4 pt-3">
<span className="text-xs font-medium text-ink-900">最近对话</span>
<button onClick={() => navigate('/research?new=1')}
<button onClick={() => navigate(`/research?new=${crypto.randomUUID()}`)}
className="inline-flex items-center gap-1 rounded-full border border-line-soft px-2.5 py-1 text-[11px] text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500">
<Plus size={11} /> 新建对话
</button>
......@@ -90,6 +98,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
</div>
</div>
<div className="mt-1 flex-1 space-y-0.5 overflow-y-auto px-2 pb-2 scrollbar-thin">
{(historyError || actionError) && <p role="alert" className="p-2 text-xs text-red-700">{historyError || actionError}</p>}
{more && <button className="p-2 text-xs text-brand-500" onClick={() => void load(research.length).catch(e => setActionError(e.message))}>加载更多会话</button>}
{filtered.length === 0 ? (
<p className="px-3 py-6 text-center text-[11px] leading-relaxed text-ink-400">
{histQuery ? '没有匹配的对话' : '开始一次探索,对话会保存在这里'}
......@@ -101,8 +111,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
{renaming === c.id ? (
<input autoFocus value={renameText} onChange={e => setRenameText(e.target.value)}
onClick={e => e.stopPropagation()}
onKeyDown={e => { if (e.key === 'Enter') submitRename(c.id); if (e.key === 'Escape') setRenaming(null) }}
onBlur={() => submitRename(c.id)}
onKeyDown={e => { if (e.key === 'Enter') void submitRename(c.id); if (e.key === 'Escape') setRenaming(null) }}
maxLength={128} onBlur={() => void submitRename(c.id)}
className="min-w-0 flex-1 rounded border border-brand-500 px-1.5 py-0.5 text-[12px] outline-none" />
) : (
<>
......@@ -128,8 +138,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
<div className="flex items-center gap-3">
<img src="/avatar-user.png" alt="用户头像" className="h-9 w-9 rounded-full ring-2 ring-brand-50" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-ink-900">张晨</div>
<div className="text-xs text-ink-400">商务拓展</div>
<div className="truncate text-sm font-medium text-ink-900">admin</div>
<div className="text-xs text-ink-400">管理员</div>
</div>
<button onClick={onLogout} title="退出登录"
className="rounded-full p-1.5 text-ink-400 transition-colors hover:bg-bad-500/10 hover:text-bad-500">
......@@ -156,7 +166,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
<p className="mt-0.5 text-[13px] text-ink-400">删除后将无法恢复。</p>
<div className="mt-4 flex justify-center gap-2">
<GhostButton onClick={() => setConfirmDelete(null)}>再想想</GhostButton>
<PrimaryButton onClick={() => { deleteConversation(confirmDelete); setConfirmDelete(null) }}
<PrimaryButton onClick={() => { void api(`/conversations/${confirmDelete}`, { method: 'DELETE' }).then(() => { setConfirmDelete(null); conversationsChanged(); navigate('/research') }).catch(e => setActionError(e.message)) }}
className="!bg-bad-500 hover:!bg-bad-500/90 !shadow-[0_2px_8px_rgba(244,63,94,.25)]">确认删除</PrimaryButton>
</div>
</motion.div>
......
......@@ -18,10 +18,11 @@ export default function Topbar() {
return () => window.clearInterval(t)
}, [])
const p = (n: number) => String(n).padStart(2, '0')
// 页面标注北京时间,不能直接使用访问者设备的本地时区。
const clock = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).format(now)
return (
<header className="sticky top-0 z-40 flex h-16 items-center gap-5 border-b border-line-soft/50 bg-white/80 px-4 backdrop-blur-md sm:px-6 xl:px-8">
<header className="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-5 border-b border-line-soft/50 bg-white/80 px-4 backdrop-blur-md sm:px-6 xl:px-8">
<div className="min-w-0">
<h1 className="text-xl font-semibold leading-tight text-ink-900">{meta.title}</h1>
<p className="text-xs text-ink-400 max-sm:hidden">{meta.sub}</p>
......@@ -29,7 +30,7 @@ export default function Topbar() {
<div className="flex-1" />
<div className="hidden items-center gap-2 text-xs text-ink-400 sm:flex">
<span className="font-num">
北京时间 {now.getFullYear()}-{p(now.getMonth() + 1)}-{p(now.getDate())} {p(now.getHours())}:{p(now.getMinutes())}
北京时间 {clock}
</span>
</div>
</header>
......
......@@ -16,6 +16,7 @@ const AiButton = forwardRef<HTMLButtonElement, AiButtonProps>(
({ children, loading, noIcon, className, ...props }, ref) => {
return (
<motion.button
type="button"
ref={ref}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
......@@ -50,6 +51,7 @@ export function PrimaryButton({
}: ButtonHTMLAttributes<HTMLButtonElement> & { loading?: boolean }) {
return (
<motion.button
type="button"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
{...(props as object)}
......@@ -66,7 +68,7 @@ export function PrimaryButton({
)
}
/** 幽灵按钮:白底 1px 灰边 */
/** 幽灵按钮:白底 1px 灰边;默认普通按钮,避免弹窗“取消”触发表单提交。 */
export function GhostButton({
children,
className,
......@@ -74,6 +76,7 @@ export function GhostButton({
}: ButtonHTMLAttributes<HTMLButtonElement>) {
return (
<motion.button
type="button"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
{...(props as object)}
......
import { useCallback, useEffect, useRef } from 'react'
// 流式输出 hook:把完整文本按字符逐步吐出,模拟 AI 生成过程
export function useStreaming() {
const timerRef = useRef<number | null>(null)
// 必须用 useCallback 固定引用:否则每次渲染都会生成新 stop,
// 使依赖 [stop] 的卸载 effect 在每次渲染时触发清理,把进行中的 trace 定时器一并清掉
const stop = useCallback(() => {
if (timerRef.current) window.clearInterval(timerRef.current)
timerRef.current = null
}, [])
useEffect(() => () => {
if (timerRef.current) window.clearInterval(timerRef.current)
}, [])
const stream = (
full: string,
onTick: (partial: string, done: boolean) => void,
speed = 12,
) => {
if (timerRef.current) window.clearInterval(timerRef.current)
let pos = 0
timerRef.current = window.setInterval(() => {
pos = Math.min(full.length, pos + 3)
onTick(full.slice(0, pos), pos >= full.length)
if (pos >= full.length && timerRef.current) {
window.clearInterval(timerRef.current)
timerRef.current = null
}
}, speed)
}
return { stream, stop }
}
// 逐条展示 Skill 调用步骤,全部完成后回调
export function runSkillTrace(
steps: string[],
onStep: (done: string[]) => void,
onComplete: () => void,
interval = 700,
): () => void {
let idx = 0
const done: string[] = []
const timer = window.setInterval(() => {
if (idx < steps.length) {
done.push(steps[idx++])
onStep([...done])
} else {
window.clearInterval(timer)
onComplete()
}
}, interval)
return () => window.clearInterval(timer)
}
import { useEffect, useRef, useState } from 'react'
import type { ResearchRequest } from '../lib/day3'
import type { SearchQuery } from '../lib/day2'
import type { QaScope } from '../lib/conversations'
import { api, ApiError } from '../lib/api'
export interface TaskEvent {
id: number
type: string
payload: { message?: string; text?: string; status?: string; [key: string]: unknown }
}
export interface AgentTask {
id: string
status: string
operation: string
question: string | null
result: unknown
usage?: { external_calls: number; zlbx_calls: number; known_cost_units: number; unknown_cost_calls: number; model_web_calls: number; input_tokens: number; output_tokens: number; unknown_token_calls: number }
request: { operation: string; workflow: string; input: string; entityConfirmed: boolean; maxCalls: number; maxCostUnits: number; opportunity?: SearchQuery; research?: ResearchRequest; qa?: QaScope }
children?: { id: string; status: string; operation: string; target?: { research?: ResearchRequest; qa?: QaScope } }[]
calls: Record<string, unknown>[]
evidence: { id: string; url: string | null; locator: string; excerpt: string; title?: string; verified?: boolean }[]
}
/** 原生 EventSource 用 Cookie 鉴权;游标只重放事件,不重复 POST 收费任务。 */
export function useTaskEvents(taskId: string | null, revision = 0) {
const [events, setEvents] = useState<TaskEvent[]>([])
const [task, setTask] = useState<AgentTask | null>(null)
const [error, setError] = useState('')
const cursor = useRef(0)
useEffect(() => {
if (!taskId) return
let active = true
let source: EventSource | null = null
let timer: ReturnType<typeof setTimeout> | undefined
let initial = true
let refreshVersion = 0
let retries = 0
cursor.current = 0
const refresh = async () => {
const version = ++refreshVersion
const next = await api<AgentTask>(`/agent/tasks/${taskId}`)
// 多页进度与终态可能相邻到达,只接受最近一次读取,防止慢响应覆盖最终报告。
if (active && version === refreshVersion) {
if (initial) { setEvents([]); setError(''); initial = false }
setTask(next)
}
return next
}
// 后端暂时不可达时持续只读恢复,延迟最多 15 秒;认证失效后停止,交给登录页处理。
const retry = (error?: unknown) => {
if (!active || (error instanceof ApiError && [401, 403, 404].includes(error.status))) {
if (active && error instanceof Error) setError(error.message)
return
}
setError('连接已中断,正在恢复事件与已有结果;不会重新发起收费请求')
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
void refresh().then(() => { if (active) connect() }).catch(retry)
}, Math.min(15000, 1000 * 2 ** Math.min(retries++, 4)))
}
const connect = () => {
if (!active) return
source = new EventSource(`/api/agent/tasks/${taskId}/events?after=${cursor.current}`)
source.addEventListener('task-event', event => {
const entry: TaskEvent = JSON.parse((event as MessageEvent).data)
if (!active || entry.id <= cursor.current) return
cursor.current = entry.id
setEvents(items => [...items, entry])
setError(''); retries = 0
if (['PAGE_COLLECTED', 'MARKET_COLLECTED', 'RESEARCH_STEP'].includes(entry.type)) void refresh().catch(error => { if (active) setError(error.message) })
})
source.addEventListener('idle', () => {
source?.close()
void refresh().catch(error => { if (active) setError(error.message) })
})
source.onerror = () => {
source?.close()
// 无论任务是否刚好完成,都重新订阅并追完游标之后的最终事件,直到收到 idle。
retry()
}
}
void refresh().then(() => { if (active) connect() }).catch(retry)
return () => { active = false; source?.close(); if (timer) clearTimeout(timer) }
}, [taskId, revision])
return { events, task: task?.id === taskId ? task : null, error }
}
import type { CompanyProfile, Project, SearchBatch } from '../types'
import { defaultMatchWeights, defaultMatchDimNames } from '../types'
import { projectById } from '../data/projects'
import { conditionsText } from './store'
function fmtBudget(p: Project): string {
return p.budget === null ? '公告未披露预算' : `${p.budget} 万元`
}
function daysLeft(date: string | null): string {
if (!date) return '未披露'
const diff = Math.ceil((new Date(date).getTime() - Date.now()) / 86400000)
if (diff < 0) return `${date}(已截止)`
if (diff === 0) return `${date}(今天截止)`
return `${date}(剩余 ${diff} 天)`
}
// ---------- AI 提取每条项目最关键的参与门槛(列表直接展示,不用点开公告) ----------
export function keyRequirement(p: Project): { label: string; tone: 'block' | 'note' | 'ok' } {
const reqs = p.requirements.join(';')
if (/不接受联合体|不接受合同分包/.test(reqs)) return { label: '不接受联合体', tone: 'block' }
if (/专门面向中小微企业/.test(reqs)) return { label: '面向中小微企业', tone: 'note' }
const perf = p.requirements.find(r => /业绩/.test(r))
if (perf) {
const m = perf.match(/(\d+)\s*个/)
return { label: m ? `需 ${m[1]} 个同类业绩` : '需同类业绩', tone: 'block' }
}
const qual = p.requirements.find(r => /资质/.test(r))
if (qual) return { label: '有资质门槛', tone: 'note' }
if (/授权/.test(reqs)) return { label: '需制造商授权', tone: 'note' }
return { label: '无特殊门槛', tone: 'ok' }
}
// ---------- 整批 AI 结论:维度来自用户访谈(贴合度 > 地区 > 金额 > 时间) ----------
export interface BatchConclusion {
/** 一句话行动建议(最重要,大字号展示) */
headline: string
/** 贴合度:商务标核心就是资质 + 业绩,打分帮用户从海量结果里聚焦 */
fit: string
/** 地区:长三角内外的项目“完全是两个概念” */
region: string
/** 金额区间 */
budget: string
/** 准备时间:来不来得及做标书 */
timing: string
}
// 访谈中用户的主战场:华东长三角
const CORE_REGIONS = ['浙江', '江苏', '上海', '安徽', '杭州', '南京', '苏州', '宁波', '合肥', '无锡', '常州']
export function batchConclusion(projects: Project[], profile: CompanyProfile): BatchConclusion {
const now = Date.now()
const day = 86400000
const regDaysOf = (p: Project) => p.regDeadline ? Math.ceil((new Date(p.regDeadline).getTime() - now) / day) : null
// 时间:以“来不来得及准备标书”为口径
const urgent = projects.filter(p => { const d = regDaysOf(p); return d !== null && d >= 0 && d <= 3 })
const tight = projects.filter(p => { const d = regDaysOf(p); return d !== null && d > 3 && d <= 7 })
const ended = projects.filter(p => { const d = regDaysOf(p); return d !== null && d < 0 })
const timing = ended.length === projects.length
? '报名均已截止,可作研究样本'
: urgent.length
? `${urgent.length} 条 3 天内截止(来不及做标书慎投)${tight.length ? ` · ${tight.length} 条一周内` : ''}`
: tight.length
? `${tight.length} 条一周内截止 · 其余时间宽裕`
: '准备时间基本宽裕'
// 地区
const inRegion = projects.filter(p => CORE_REGIONS.some(r => p.region.includes(r)))
const region = inRegion.length === projects.length
? `全部在长三角内`
: `长三角 ${inRegion.length} 条 · 区域外 ${projects.length - inRegion.length} 条`
// 金额
const disclosed = projects.filter(p => p.budget !== null).map(p => p.budget as number)
const budget = disclosed.length === 0
? '均未披露预算'
: (() => {
const max = Math.max(...disclosed); const min = Math.min(...disclosed)
const hidden = projects.length - disclosed.length
return `${min.toLocaleString()}~${max.toLocaleString()} 万元${hidden ? ` · ${hidden} 条未披露` : ''}`
})()
// 贴合度:访谈确认的核心诉求——打分聚焦(先看 90+,再看 80+)
const scored = profile.completed
? projects.map(p => ({ p, m: matchScore(p, profile)! })).sort((a, b) => b.m.score - a.m.score)
: []
const high = scored.filter(x => x.m.score >= 80)
const mid = scored.filter(x => x.m.score >= 60 && x.m.score < 80)
const fit = profile.completed
? `${high.length} 条 ≥80 分${mid.length ? ` · ${mid.length} 条 60~79 分` : ''} · 最高 ${scored[0]?.m.score ?? 0} 分`
: '完善档案后生成贴合度打分'
let headline: string
if (profile.completed && scored.length) {
const top = scored[0]
const open = regDaysOf(top.p)
const timeNote = open !== null && open >= 0 ? (open <= 7 ? `,报名还剩 ${open} 天要抓紧` : ',时间来得及') : ''
headline = high.length
? `建议先评估「${top.p.name}」——贴合度 ${top.m.score} 分${timeNote};${high.length > 1 ? `另有 ${high.length - 1} 条 80 分以上` : '其余项目贴合度一般'}`
: `本批没有 80 分以上的项目,最高的「${top.p.name}」${top.m.score} 分,建议作为市场信息留存`
} else {
headline = urgent.length
? `「${urgent[0].name}」报名 3 天内截止,先确认来不来得及;完善档案后即可按贴合度打分排序优先级`
: `本批${inRegion.length ? `长三角内 ${inRegion.length} 条` : '项目已列出'},完善公司档案后即可按「资质 + 业绩贴合度」打分,从海量结果里直接锁定该看的几条`
}
return { headline, fit, region, budget, timing }
}
// ---------- 匹配度(仅在档案已完善时生成,需展示维度、权重与依据;不参与筛选排序) ----------
export interface MatchDim {
name: string
/** 权重(%) */
weight: number
/** 该维度得分 0-100 */
score: number
note: string
}
export interface MatchResult {
score: number
dims: MatchDim[]
basis: string[]
}
export function matchScore(p: Project, profile: CompanyProfile): MatchResult | null {
if (!profile.completed) return null
const dims: MatchDim[] = []
// 权重与维度名来自检索页的用户配置;合计不为 100 时按比例归一
const w = profile.matchWeights ?? defaultMatchWeights
const names = profile.matchDimNames ?? defaultMatchDimNames
const wSum = Math.max(1, w.business + w.region + w.amount + w.track)
const W = {
business: Math.round(w.business / wSum * 100),
region: Math.round(w.region / wSum * 100),
amount: Math.round(w.amount / wSum * 100),
track: Math.round(w.track / wSum * 100),
}
// 业务贴合:项目关键词与公司业务/产品/优势的重合
const profileText = [profile.mainBusiness, profile.products, profile.advantages, profile.projectTypes].join(' ')
const kwHits = p.keywords.filter(k =>
profileText.includes(k.replace(/\s|\/ /g, '')) || profileText.split(/[,,、;;\s]+/).some(wd => wd && k.includes(wd)))
dims.push({
name: names.business, weight: W.business,
score: kwHits.length > 0 ? Math.min(95, 45 + kwHits.length * 25) : 35,
note: kwHits.length > 0 ? `关键词重合:${kwHits.join('、')}` : '项目关键词与档案业务重合较少',
})
// 服务地区
const regions = profile.serviceRegions.split(/[,,、;;\s]+/).filter(Boolean)
const inRegion = regions.some(r => r !== '全国' && p.region.includes(r))
dims.push({
name: names.region, weight: W.region,
score: inRegion ? 90 : regions.includes('全国') ? 70 : 40,
note: inRegion ? `位于目标服务地区(${p.region})` : regions.includes('全国') ? '服务范围覆盖全国' : `${p.region} 不在档案服务地区内`,
})
// 金额匹配
const amountMatch = profile.amountPreference.match(/(\d+)\s*[-~至]\s*(\d+)/)
if (p.budget === null) {
dims.push({ name: names.amount, weight: W.amount, score: 50, note: '公告未披露预算,无法对照金额偏好' })
} else if (amountMatch) {
const lo = Number(amountMatch[1]); const hi = Number(amountMatch[2])
const inRange = p.budget >= lo && p.budget <= hi
dims.push({
name: names.amount, weight: W.amount, score: inRange ? 85 : 45,
note: inRange ? `预算 ${p.budget} 万元在偏好区间 ${lo}~${hi} 万元内` : `预算 ${p.budget} 万元不在偏好区间 ${lo}~${hi} 万元内`,
})
} else {
dims.push({ name: names.amount, weight: W.amount, score: 60, note: '档案未填金额偏好,按中性计' })
}
// 业绩与资质:商务标核心;材料缺失不等于不符合,标记为待核对
const needPerf = p.requirements.some(r => /业绩/.test(r))
const needQual = p.requirements.some(r => /资质/.test(r))
if (needPerf && !profile.trackRecord.trim()) {
dims.push({ name: names.track, weight: W.track, score: 30, note: '公告要求同类业绩,档案“代表业绩”未填写,无法核对(待补充,不代表不符合)' })
} else if (needQual && !profile.qualifications.trim()) {
dims.push({ name: names.track, weight: W.track, score: 35, note: '公告涉及资质要求,档案“资质与认证”未填写,无法核对(待补充,不代表不符合)' })
} else if (profile.trackRecord.trim() || profile.qualifications.trim()) {
dims.push({ name: names.track, weight: W.track, score: 75, note: '档案已填业绩/资质,硬性条款仍需以证书与合同原件逐条核对' })
} else {
dims.push({ name: names.track, weight: W.track, score: 50, note: '档案未填业绩与资质,建议补充后再评估' })
}
const score = Math.round(dims.reduce((s, d) => s + d.score * d.weight / 100, 0))
return { score, dims, basis: dims.map(d => `${d.name}:${d.note}`) }
}
// ---------- AI 时间解读:把原始日期翻译成用户视角的紧迫度判断 ----------
export interface TimeDigest {
/** 主提示,如「报名仅剩 3 天」 */
label: string
/** 次级信息,如「之后投标还剩 12 天」 */
sub: string
/** 一句话行动建议 */
hint: string
tone: 'urgent' | 'warn' | 'ok' | 'muted'
}
export function timeDigest(p: Project): TimeDigest {
const now = Date.now()
const day = 86400000
const regDays = p.regDeadline ? Math.ceil((new Date(p.regDeadline).getTime() - now) / day) : null
const bidDays = p.bidDeadline ? Math.ceil((new Date(p.bidDeadline).getTime() - now) / day) : null
// 报名窗口仍开放:以报名为主线
if (regDays !== null && regDays >= 0) {
const sub = bidDays !== null && bidDays >= 0 ? `投标截止 ${p.bidDeadline}` : '投标截止时间未披露'
if (regDays === 0) return { label: '今天报名截止', sub, hint: '今天截止,若考虑参与需立即报名', tone: 'urgent' }
if (regDays <= 3) return { label: `报名仅剩 ${regDays} 天`, sub, hint: '时间很紧,需立即决定是否报名', tone: 'urgent' }
if (regDays <= 7) return { label: `报名还剩 ${regDays} 天`, sub, hint: '时间偏紧,建议尽快准备报名材料', tone: 'warn' }
return { label: `报名还剩 ${regDays} 天`, sub, hint: '时间充裕,可从容评估是否参与', tone: 'ok' }
}
// 报名已过或未披露,看投标
if (regDays !== null && regDays < 0 && bidDays !== null && bidDays >= 0) {
return { label: '报名已截止', sub: `投标还剩 ${bidDays} 天`, hint: '报名窗口已过,可关注开标结果作研究参考', tone: 'muted' }
}
if (regDays === null && bidDays !== null && bidDays >= 0) {
if (bidDays <= 3) return { label: `投标仅剩 ${bidDays} 天`, sub: '报名截止时间未披露', hint: '投标临近,报名安排需以公告原文为准', tone: 'urgent' }
return { label: `投标还剩 ${bidDays} 天`, sub: '报名截止时间未披露', hint: '建议打开公告原文确认报名方式', tone: 'warn' }
}
if ((regDays !== null && regDays < 0) || (bidDays !== null && bidDays < 0)) {
return { label: '报名与投标均已截止', sub: `发布于 ${p.publishDate}`, hint: '项目已结束,可作采购方与竞对研究样本', tone: 'muted' }
}
return { label: '截止时间未披露', sub: `发布于 ${p.publishDate}`, hint: '公告未给出明确节点,建议查看原文确认', tone: 'muted' }
}
// ---------- 单项目 AI 分析 ----------
export function projectAnalysis(p: Project, profile: CompanyProfile): string {
const hasProfile = profile.completed
const match = matchScore(p, profile)
const parts: string[] = []
parts.push(`### 项目分析:${p.name}`)
parts.push(`**公告事实**(来源:${p.sourceName}${p.sourceUrl ? '' : ',来源链接暂未收录'})`)
parts.push(`- 采购单位:${p.purchaser}`)
parts.push(`- 地区:${p.region}|公告类型:${p.noticeType}`)
parts.push(`- 预算:${fmtBudget(p)}`)
parts.push(`- 发布日期:${p.publishDate}|报名截止:${daysLeft(p.regDeadline)}|投标截止:${daysLeft(p.bidDeadline)}`)
parts.push(`\n**项目内容**\n${p.detail}`)
parts.push(`\n**公告参与条件**\n${p.requirements.map(r => `- ${r}`).join('\n')}`)
if (hasProfile) {
parts.push(`\n**结合公司档案对照**(档案版本 v${profile.version},${profile.updatedAt})`)
if (match) {
parts.push(`- 贴合度参考:**${match.score} 分**(仅辅助参考,不用于筛选或排序)`)
parts.push(`\n**贴合度打分报告**\n\n| 维度 | 权重 | 得分 | 依据 |\n| --- | --- | --- | --- |`)
match.dims.forEach(d => parts.push(`| ${d.name} | ${d.weight}% | ${d.score} | ${d.note} |`))
const sorted = [...match.dims].sort((a, b) => b.score - a.score)
const strongest = sorted[0]
const weakest = sorted[sorted.length - 1]
const verdict = match.score >= 80
? '整体贴合度高,建议优先评估并尽快确认报名时间'
: match.score >= 60
? '具备一定贴合度,建议先核对短板维度再决定是否投入'
: '贴合度偏低,建议作为市场信息留存,暂不投入标书资源'
parts.push(`\n**综合判断**:${match.score} 分——最强项「${strongest.name}」${strongest.score} 分;主要短板「${weakest.name}」${weakest.score} 分(${weakest.note})。${verdict}。`)
// 结合公司档案的优劣势分析
const strengths = match.dims.filter(d => d.score >= 75)
const weaknessDims = match.dims.filter(d => d.score < 60)
parts.push(`\n**结合公司档案的优劣势**`)
if (strengths.length) {
parts.push(`优势:`)
strengths.forEach(d => parts.push(`- ${d.name}(${d.score} 分):${d.note}`))
}
if (weaknessDims.length) {
parts.push(`短板:`)
weaknessDims.forEach(d => parts.push(`- ${d.name}(${d.score} 分):${d.note}`))
}
if (!strengths.length && !weaknessDims.length) {
parts.push('- 各维度表现均衡,无明显长板或短板,建议按综合得分与时间安排决定优先级')
}
if (profile.advantages.trim()) {
parts.push(`- 可在标书中突出档案记载的竞争优势:${profile.advantages}`)
}
}
const reqs = p.requirements
const track = profile.trackRecord || ''
const quals = profile.qualifications || ''
const hints: string[] = []
if (reqs.some(r => r.includes('业绩')) && !track) hints.push('公告要求同类业绩,但档案中“代表业绩”尚未填写,建议补充后再判断')
if (reqs.some(r => r.includes('资质')) && !quals) hints.push('公告涉及资质要求,档案中“资质与认证”尚未填写,无法核对')
if (profile.boundaries) hints.push(`参与边界提示:${profile.boundaries}`)
if (hints.length) parts.push(hints.map(h => `- ${h}`).join('\n'))
else parts.push('- 档案信息已覆盖业绩与资质维度,建议逐条核对公告原件要求')
} else {
parts.push(`\n> **提示:公司档案未完善**,暂无法生成匹配度与针对性对照。以上为公告事实概括,不包含针对贵公司的结论。完善档案后可获得有依据的匹配建议。`)
}
parts.push(`\n**风险与未知项**`)
parts.push(`- ${p.budget === null ? '公告未披露预算,缺少价格基准,不能直接给出报价建议' : '预算不等于建议报价;缺少工程量、成本与历史成交依据时,不能直接给出可靠报价'}`)
if (p.regDeadline && new Date(p.regDeadline).getTime() - Date.now() < 5 * 86400000 && new Date(p.regDeadline).getTime() > Date.now()) {
parts.push(`- 报名截止距今不足 5 天,如考虑参与需尽快准备报名材料`)
}
parts.push(`- 评分办法、付款方式等细节需以招标文件原文为准,本次分析未覆盖`)
parts.push(`\n*是否跟进、报名或投标由你自行决定;以上为辅助分析,重要事实请核对公告原文。*`)
return parts.join('\n')
}
// ---------- 项目追问 ----------
export function projectFollowUp(p: Project, q: string, profile: CompanyProfile): string {
const lower = q.toLowerCase()
if (lower.includes('截止') || lower.includes('时间') || lower.includes('报名')) {
return `**该项目的时间节点**\n- 公告发布:${p.publishDate}\n- 报名截止:${daysLeft(p.regDeadline)}\n- 投标截止:${daysLeft(p.bidDeadline)}\n\n报名截止与投标截止需分别判断;如考虑参与,建议以公告原文时间为准并预留材料准备时间。${profile.completed && profile.bidPreparation ? `\n\n按档案中填写的投标准备周期(${profile.bidPreparation}),请核对时间是否紧张。` : ''}`
}
if (lower.includes('预算') || lower.includes('报价') || lower.includes('金额') || lower.includes('价格')) {
return `**预算口径说明**\n- 公告预算:${fmtBudget(p)}\n\n预算不等于建议报价。缺少工程量清单、成本构成与同类项目历史成交依据时,不能直接给出可靠报价。如需报价参考,可在“对话调研”中查询同类项目的历史中标价格。`
}
if (lower.includes('资质') || lower.includes('条件') || lower.includes('要求') || lower.includes('门槛')) {
const base = `**公告参与条件**\n${p.requirements.map(r => `- ${r}`).join('\n')}`
if (profile.completed) {
return `${base}\n\n**对照公司档案**:请逐条核对档案中的资质(${profile.qualifications || '未填写'})与业绩(${profile.trackRecord || '未填写'})是否满足。材料缺失不等于不符合,建议以证书原件与业绩合同为准。`
}
return `${base}\n\n公司档案未完善,暂无法做针对性对照。`
}
if (lower.includes('风险') || lower.includes('注意')) {
return `**需要关注的风险点**\n- ${p.budget === null ? '预算未披露,价格与竞争强度缺少判断依据' : '预算规模较大时通常竞争更强,建议查询采购方历史中标供应商'}\n- 评分办法、资格条款细节以招标文件原文为准\n- 注意更正公告:同一项目可能发布更正,需确认当前看到的是最新版本\n\n以上为通用提示,不构成投标决定建议。`
}
return `已收到关于「${p.name}」的问题。可以进一步问我:\n- 报名和投标截止时间\n- 公告参与条件与资质要求\n- 预算口径与报价参考\n- 风险与需要注意的事项\n\n(当前为演示环境,回答基于已获取的公告数据生成。)`
}
// ---------- 基于本次搜索提问 ----------
export function searchQaAnswer(batch: SearchBatch, q: string, profile: CompanyProfile): string {
const projects = batch.projectIds.map(id => projectById(id)).filter(Boolean) as Project[]
const total = batch.total
const scope = `本次对话基于实际执行的检索:${conditionsText(batch.conditions)},共 ${total} 条结果。`
const lower = q.toLowerCase()
if (lower.includes('截止') || lower.includes('快')) {
const withDeadline = projects
.filter(p => p.regDeadline)
.sort((a, b) => new Date(a.regDeadline!).getTime() - new Date(b.regDeadline!).getTime())
if (!withDeadline.length) return `${scope}\n\n本次结果中的项目均未披露报名截止时间。`
const urgent = withDeadline.filter(p => {
const d = (new Date(p.regDeadline!).getTime() - Date.now()) / 86400000
return d >= 0 && d <= 7
})
const lines = (urgent.length ? urgent : withDeadline.slice(0, 5)).map(p =>
`- **${p.name}**:报名截止 ${daysLeft(p.regDeadline)}(${p.region})`)
return `${scope}\n\n### 报名截止较近的项目\n${lines.join('\n')}\n\n${urgent.length ? `共 ${urgent.length} 个项目报名截止距今不足 7 天。` : '本次结果中没有 7 天内截止报名的项目,以上为截止最近的 5 个。'}时间以公告原文为准。`
}
if (lower.includes('预算') || lower.includes('金额') || lower.includes('披露')) {
const disclosed = projects.filter(p => p.budget !== null)
const hidden = projects.filter(p => p.budget === null)
const sum = disclosed.reduce((s, p) => s + (p.budget ?? 0), 0)
return `${scope}\n\n### 预算披露情况\n- 披露预算:${disclosed.length} 条,合计约 ${sum.toLocaleString()} 万元\n- 未披露预算:${hidden.length} 条(未披露不等于预算为 0)\n\n预算最高的三条:\n${disclosed.sort((a, b) => (b.budget ?? 0) - (a.budget ?? 0)).slice(0, 3).map(p => `- ${p.name}:${p.budget} 万元(${p.region})`).join('\n') || '- 无'}`
}
if (lower.includes('共同') || lower.includes('要求') || lower.includes('条件')) {
const all = projects.flatMap(p => p.requirements)
const needTrack = all.filter(r => r.includes('业绩')).length
const noJoint = all.filter(r => r.includes('不接受联合体')).length
const yesJoint = all.filter(r => r.includes('接受联合体')).length
const needQual = all.filter(r => r.includes('资质')).length
return `${scope}\n\n### 本次结果的共同要求(基于已获取公告文本统计)\n- 要求同类业绩的项目:${needTrack} 个\n- 明确要求资质的项目:${needQual} 个\n- 不接受联合体投标:${noJoint} 个|接受联合体投标:${yesJoint} 个\n\n以上统计来自公告事实字段,个别项目的具体条款(如业绩个数、资质等级)需打开原文逐条核对。材料缺失不等于不符合。`
}
if (lower.includes('比较') || lower.includes('对比') || lower.includes('推荐') || lower.includes('优先')) {
const active = projects.filter(p => p.regDeadline && new Date(p.regDeadline).getTime() > Date.now())
const rows = (active.length ? active : projects).slice(0, 5).map(p => {
const m = matchScore(p, profile)
return `| ${p.name} | ${p.region} | ${fmtBudget(p)} | ${daysLeft(p.regDeadline)} | ${m ? m.score + ' 分' : '档案未完善'} |`
})
return `${scope}\n\n### 项目比较(展示前 ${Math.min(5, rows.length)} 条,共 ${total} 条)\n| 项目 | 地区 | 预算 | 报名截止 | 匹配度参考 |\n| --- | --- | --- | --- | --- |\n${rows.join('\n')}\n\n匹配度仅作辅助参考${profile.completed ? ',依据来自公司档案与公告字段的重合' : ',完善公司档案后生成'};不用于筛选或重排结果。是否跟进由你判断。`
}
return `${scope}\n\n可以围绕本次结果继续问我,例如:\n- 哪些项目报名快截止了\n- 这些项目的预算披露情况\n- 这些项目有哪些共同要求\n- 比较一下这些项目\n\n我只基于本次实际检索的结果回答,不会修改结果列表的范围或顺序。`
}
// ---------- 对话调研 ----------
export interface ResearchResult {
markdown: string
skillTrace: string[]
title: string
}
export function researchAnswer(query: string, entry: string | null): ResearchResult {
const q = query.trim()
const isCustomer = entry === 'customer' || /公司|企业|客户|水务集团|水务局/.test(q) && !/竞争|对手/.test(q)
const isCompetitor = entry === 'competitor' || /竞争|对手|竞对/.test(q)
const isMarket = entry === 'market' || /市场|区域|地区|需求/.test(q)
// 提取一个看起来像企业名的主体用于代入回答
const subject = q.replace(/[??。,,]/g, ' ').split(/\s+/).find(w => /公司|集团|局|院/.test(w))
?? q.slice(0, 12)
if (isCompetitor) {
return {
title: q.slice(0, 18),
skillTrace: ['企业情报 Skill · company-intel:识别企业主体', '企业情报 Skill · company-intel:查询中标记录与业务重合', '招投标检索 Skill · tender-search:核对同场投标记录'],
markdown: `### 竞争对手调研:${subject}
**主体确认**:已按工商主体与公告主体双重核对,以下数据来自公开中标记录与工商信息(演示数据)。
**主营业务结构**
| 业务方向 | 收入占比(估算) | 与我方重合度 |
| --- | --- | --- |
| 智慧水务平台建设 | 约 45% | 高 |
| 供水管网漏损控制 | 约 25% | 高 |
| 水质监测设备集成 | 约 20% | 中 |
| 运营托管服务 | 约 10% | 低 |
**近一年公开中标记录(节选)**
| 时间 | 项目 | 金额 | 采购单位 |
| --- | --- | --- | --- |
| 2026-08 | 某市供水管网分区计量项目 | 860 万 | 市水务集团 |
| 2026-05 | 某区智慧水务数据平台二期 | 1,420 万 | 区住建局 |
| 2025-12 | 某污水厂自控系统改造 | 530 万 | 园区管委会 |
**判断**
- 优势在平台类大项目,客单价高,但交付周期长;漏损类项目多用分包,自有算法能力一般
- 与我方正面冲突集中在**平台建设项目**;在**漏损治理、监测设备**项目上我方交付成本和本地化响应占优
- 其华东区域客户集中,华南、西南覆盖薄弱,可作为差异化切入方向
> 以上为模拟数据演示,正式接入后每条记录可点开公告来源核对。`,
}
}
if (isMarket) {
return {
title: q.slice(0, 18),
skillTrace: ['招投标检索 Skill · tender-search:检索区域采购公告', '招投标检索 Skill · tender-search:统计中标记录与时间变化', '市场聚合分析:买方与供应商集中度'],
markdown: `### 区域市场调研:${q}
**总体判断**(演示数据):该区域智慧水务采购处于**持续放量**阶段,近 90 天公告数量环比上升约 22%,值得加大投入。
**采购热度(近 6 个月,公告条数)**
| 月份 | 公告数 | 披露预算合计 |
| --- | --- | --- |
| 2026-05 | 31 | 1.9 亿 |
| 2026-06 | 28 | 1.6 亿 |
| 2026-07 | 35 | 2.2 亿 |
| 2026-08 | 42 | 2.8 亿 |
| 2026-09 | 47 | 3.1 亿 |
| 2026-10(至今) | 39 | 2.4 亿 |
**主要买方**:市水务集团及其下属供水公司(占公告量约 40%)、区县住建/水务局(约 35%)、园区管委会(约 15%)。
**竞争格局**:高频中标企业 6 家,集中度中等;平台类项目多被两家头部企业拿走,**监测与漏损类项目中标方分散,是新进入者的主要机会口**。
**建议**
- 优先盯区县水务局发布的漏损治理与监测类项目,门槛相对低、决策链短
- 平台类项目可关注二期/三期延续采购,一期供应商未必延续
> 以上为模拟数据演示;调研结果围绕研究问题查询,不代表全量检索结果。`,
}
}
if (isCustomer) {
return {
title: q.slice(0, 18),
skillTrace: ['企业情报 Skill · company-intel:确认企业主体', '企业情报 Skill · company-intel:查询采购与中标记录', '企业情报 Skill · company-intel:梳理客户与供应商关系'],
markdown: `### 目标客户调研:${subject}
**企业主体**(演示数据):已确认工商主体与公告发布主体一致,国有控股,承担辖区供水与排水运营。
**近一年采购画像**
| 维度 | 观察 |
| --- | --- |
| 采购频率 | 年均 12–15 个公开项目,Q3–Q4 为集中采购期 |
| 偏好类型 | 管网漏损治理、二次供水改造、数据平台建设 |
| 常见预算区间 | 500 万 – 2,000 万 |
| 决策特点 | 重业绩案例,常要求 2 个以上同类项目经验 |
**近期采购记录(节选)**
| 时间 | 项目 | 金额 |
| --- | --- | --- |
| 2026-09 | 分区计量与漏损分析平台建设 | 1,180 万 |
| 2026-06 | 二次供水设施改造(二期) | 940 万 |
| 2026-03 | 水质在线监测设备采购 | 420 万 |
**切入建议**
- 该客户**连续三个项目都涉及漏损方向**,说明漏损指标考核压力大,我方漏损控制方案正中其需求
- 历史合作供应商中暂无固定平台服务商,存在替换窗口
- 建议关注其 Q4 批次采购,提前准备同类业绩材料
> 以上为模拟数据演示,正式接入后每条事实均可点开来源。`,
}
}
return {
title: q.slice(0, 18) || '自由调研',
skillTrace: ['主 AI:理解研究问题并识别对象与范围', '招投标检索 Skill · tender-search:检索相关公告', '企业情报 Skill · company-intel:补充主体背景'],
markdown: `### 调研:${q}
已围绕你的问题完成一轮公开信息检索与整理(演示数据)。
**初步发现**
- 相关公开公告与记录共检索到 20 余条,时间集中在近半年,说明该方向处于活跃期
- 涉及主体以地方水务集团、区县住建/水务部门为主,项目金额多落在 500 万 – 2,000 万区间
- 从公告条款看,**同类业绩与本地化服务能力**是被提及最多的两项门槛
**可以继续追问**
- 「这些项目里哪些报名快截止了」
- 「主要中标企业都有谁」
- 「把采购单位按地区归一下类」
回答会区分来源事实与 AI 推断;未查到的内容会明确说明,不做断言。`,
}
}
/** 统一同源客户端。会话只放 HttpOnly Cookie;API Key 不进入前端环境或 localStorage。 */
export class ApiError extends Error {
readonly status: number
readonly code: string
constructor(status: number, code: string, message: string) {
super(message); this.status = status; this.code = code
}
}
let csrf: { token: string; headerName: string } | null = null
export async function refreshCsrf() {
const response = await fetch('/api/auth/csrf', { credentials: 'same-origin' })
if (!response.ok) throw new ApiError(response.status, 'CSRF_UNAVAILABLE', '无法连接登录服务,请检查后端是否启动')
csrf = await response.json()
}
/** 不自动重试写请求,尤其是可能收费的任务;幂等重试必须沿用调用方保留的键。 */
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
const method = (options.method ?? 'GET').toUpperCase()
const headers = new Headers(options.headers)
if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) {
if (!csrf) await refreshCsrf()
if (csrf) headers.set(csrf.headerName, csrf.token)
if (options.body && !(options.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
}
let response: Response
try { response = await fetch(`/api${path}`, { ...options, method, headers, credentials: 'same-origin' }) }
catch { throw new ApiError(0, 'NETWORK_ERROR', '网络连接失败,请检查后端;提交结果未知时请保留原任务键重试') }
const data = await response.json().catch(() => ({}))
if (!response.ok) {
if (response.status === 401 && path !== '/auth/login') window.dispatchEvent(new Event('session-expired'))
if (response.status === 403) csrf = null
throw new ApiError(response.status, data.code ?? 'REQUEST_FAILED', data.message ?? '服务请求失败,请稍后重试')
}
return data as T
}
export async function login(username: string, password: string) {
await refreshCsrf()
await api('/auth/login', {
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ username, password }),
})
// Spring Security 在认证成功后轮换会话与 CSRF token,必须重新获取。
csrf = null
await refreshCsrf()
}
export async function logout() {
await api('/auth/logout', { method: 'POST' })
csrf = null
}
import { useCallback, useEffect, useRef, useState } from 'react'
import { api } from './api'
export interface Conversation { id: string; title: string; version: number; created_at: string; updated_at: string }
export interface ConversationMessage { id: string; role: string; content: string; task_id: string | null; created_at: string }
export interface QaScope { batchId: string | null; projectId: string | null }
export const conversationsChanged = () => window.dispatchEvent(new Event('conversations-changed'))
/** 会话列表从服务器搜索并分页;刷新、跨页面新建或改名后均回读,浏览器不持久化账号资料。 */
export function useConversations(query = '') {
const [items, setItems] = useState<Conversation[]>([])
const [error, setError] = useState('')
const [more, setMore] = useState(false)
const requestVersion = useRef(0)
const invalidate = useCallback(() => { requestVersion.current++ }, [])
const load = useCallback(async (offset = 0) => {
const version = ++requestVersion.current
const rows = await api<Conversation[]>(`/conversations?q=${encodeURIComponent(query)}&offset=${offset}`)
if (version !== requestVersion.current) return
setItems(current => offset ? [...current, ...rows] : rows); setMore(rows.length === 50); setError('')
}, [query])
useEffect(() => {
let active = true
const refresh = () => { void load().catch(e => { if (active) setError(e.message) }) }
const timer = setTimeout(refresh, 200)
window.addEventListener('conversations-changed', refresh)
return () => { active = false; invalidate(); clearTimeout(timer); window.removeEventListener('conversations-changed', refresh) }
}, [load, invalidate])
return { items, error, more, load }
}
import type { WatchStatus, StatusChange } from '../types'
/** 后端权威契约:万元与缺失值保持原样;浏览器不重新计算匹配分或收费。 */
export interface SearchQuery {
keywords: string[]
beginDate: string
endDate: string
stages: number[]
preference: 'COMPREHENSIVE' | 'REGION' | 'BUSINESS' | 'AMOUNT'
preferredRegions: string[]
budgetMinWan: number | null
budgetMaxWan: number | null
mode: 'SEARCH' | 'LEADS' | 'MARKET'
keywordMode: 'ANY' | 'ALL'
hardRegions: string[]
hardMinWan: number | null
hardMaxWan: number | null
}
export interface Candidate {
id: string; sourceId: string; title: string; purchaser: string; region: string
budgetWan: number | null; publishDate: string; stage: number | null; url: string | null
userFileId?: string | null; products: string[]; evidenceId: string | null; gaps: string[]
}
export interface RankedItem {
facts: Candidate; relevance: number; preferenceBonus: number; reasoning: string[]
analysis: null | {
projectNumber: string
summary: { construction: string; region: string; schedule: string[]; qualifications: string[]; gaps: string[]; evidenceId: string; locator: string; method: string }
match: { score: number | null; completeness: number; profileVersion: number; version: string; limitation: string
weights: Record<string, number>; dimensions: Record<string, { score: number; known: boolean; basis: string }> }
}
}
export interface SearchReport {
conditions: SearchQuery; rankingVersion: string
scope: { platformTotal: number | null; fetchedCount: number; uniqueCount: number; displayCount: number; pagesRead: number; stopReason: string; complete: boolean }
stageChains: { projectNumber: string; purchaser: string; notices: Candidate[]; basis: string }[]
items: RankedItem[]; limitations: string[]; referencesVerified: boolean
summaryProgress: { completed: number; total: number; method: string }
market?: { basis: string; buyers: Record<string, number>; suppliers: Record<string, number>; monthlyNotices: Record<string, number>; platformAggregations: { tool: string; evidenceId: string; scope: string; rows: { name: string; count: number | null; amountWan: number | null; url: string | null }[] }[] }
}
export interface SearchHistory { id: string; status: string; createdAt: string; schemeId: string | null; schemeName: string | null; schemeVersion: number | null }
export interface SearchScheme { id: string; name: string; conditions: SearchQuery; version: number }
export interface WatchItem {
fileId?: string | null; summary?: NonNullable<RankedItem['analysis']>['summary']
projectId: string; status: WatchStatus; note: string; version: number; tags: string[]
createdAt: string; history: StatusChange[]; group: string; project: Candidate
}
export interface Tag { id: string; name: string }
export const inputClass = 'w-full rounded-ctrl border border-line-soft bg-white px-3 py-2 text-sm outline-none focus:border-brand-500'
export const stageNames: Record<number, string> = { 1: '采购意向', 2: '预招标', 4: '招标', 5: '更正', 6: '终止', 7: '中标', 8: '合同', 9: '其他', 10: '其他' }
export const preferenceNames = { COMPREHENSIVE: '综合推荐', REGION: '地域优先', BUSINESS: '业务优先', AMOUNT: '金额优先' }
/** 时间快捷选项统一使用北京时间,避免午夜时浏览器时区改变查询日期。 */
export function beijingDate(offset = 0) {
return new Date(Date.now() + (8 * 60 * 60 * 1000) - offset * 86400000).toISOString().slice(0, 10)
}
export function initialQuery(): SearchQuery {
return { keywords: [], beginDate: beijingDate(89), endDate: beijingDate(), stages: [1, 2, 4, 7, 8], preference: 'COMPREHENSIVE', preferredRegions: [], budgetMinWan: null, budgetMaxWan: null, mode: 'LEADS', keywordMode: 'ANY', hardRegions: [], hardMinWan: null, hardMaxWan: null }
}
export function words(value: string) { return value.split(/[、,,;;\n]+/).map(s => s.trim()).filter(Boolean) }
export function message(error: unknown) { return error instanceof Error ? error.message : '请求失败,请重试' }
export function time(value: string) { return new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) }
/** 仅格式化原文明确写出的报名截止日期;不拿投标日期代替,也不把无效日期自动顺延。 */
export function registrationDate(schedule: string[] = []): string | null {
const match = schedule.join(';').match(/报名(?:时间)?(?:截止|截至)(?:时间)?\s*[::]?\s*(\d{4})[-年/.](\d{1,2})[-月/.](\d{1,2})/)
if (!match) return null
const value = `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')}`
const date = new Date(`${value}T00:00:00Z`)
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value ? value : null
}
/** D3 请求只传业务参数;工具路径、主体事实与费用一律由后端确定。 */
export interface ResearchRequest {
companies: string[]
selections: Record<string, string>
mode: 'QUICK' | 'FULL'
fileId: string | null
parentId: string | null
targetProjectId: string | null
focus: string | null
acknowledgedCalls: number
}
export interface ResearchReport {
kind: 'COMPANY_RESEARCH' | 'BID_RESEARCH' | 'SNAPSHOT_QA'
choices: { key: string; options: { id: string; name: string; region: string }[]; selected: string }[]
sections: { key: string; tool: string; evidenceId: string; kind: string; data: unknown }[]
observations: { text: string; evidenceIds: string[] }[]
ownFit?: { summary: { construction: string; qualifications: string[]; gaps: string[] }; match: { score: number | null; completeness: number; profileVersion: number; limitation: string; dimensions: Record<string, { basis: string; score: number; known: boolean }> } }
commonCustomers?: string[]
comparisonBasis?: string
gaps: string[]
scope: { beginDate?: string; basis: string; stepCount?: number; answerCount?: number; candidateCount?: number; platform_total?: number | null; fetched_count?: number; conditions?: { beginDate: string; endDate: string; keywords: string[] } }
}
export const taskStates: Record<string, string> = { RECEIVED: '已接收', PLANNING: '规划中', RUNNING: '执行中', WAITING_ENTITY: '等待主体选择', WAITING_INPUT: '等待补充', WAITING_BUDGET: '预算暂停', SUCCEEDED: '步骤完成', PARTIAL: '部分完成', FAILED: '失败', CANCELLED: '已取消' }
export const toolNames: Record<string, string> = {
search_company: '定位企业主体', get_company_profile: '基础画像', get_company_business_keywords: '业务关键词',
get_company_partners: '客户与供应商', query_bids_advanced: '历史公告明细', aggregate_bids_advanced: '历史聚合统计',
find_competitors: '真实投标竞对', search_bids: '定位项目公告', get_bid_detail: '项目正文', find_potential_bidders: '潜在投标者', get_price_trends: '品牌型号历史单价',
web_search: '检索公开资料', web_fetch: '读取公开网页', model_json: '生成有据建议', vision: '识别文件页面', FILE_PARSE: '本地文件提取', ENTITY_CACHE: '读取已确认主体(缓存)',
}
import type { CompanyProfile } from '../types'
/**
* 沿用原型的本地文本字段识别,只返回可供人工核对的草稿。
* 公司名称单独识别,避免名称中的“验收”“中标”等字样被误当成代表业绩;
* 移除明确的字段前缀,不补全文件未提供的企业信息,也不改动已保存档案。
*/
export function extractProfileFromText(text: string): Partial<CompanyProfile> {
const lines = text.split(/\r?\n/).map(line => line.trim().replace(/^[-*•\d.、\s]+/, '')).filter(Boolean)
const company = lines.find(line => /^(企业名称|公司名称)\s*[::]/.test(line))
?? lines.find(line => /^.{2,100}(有限公司|股份公司|集团)$/.test(line))
const out: Partial<CompanyProfile> = {}
const clean = (line: string) => line.replace(/^(企业名称|公司名称|企业简介|主营业务|主营|产品与服务|产品|核心优势|优势|服务地区|地区|客户类型|客户|项目类型偏好|项目类型|金额偏好|资质与认证|资质|代表业绩|业绩|交付与售后|交付|投标准备|参与边界)\s*[::]\s*/, '').slice(0, 300)
if (company) out.companyName = clean(company).slice(0, 200)
const fields: [keyof CompanyProfile, RegExp][] = [
['intro', /简介|成立于|是一家/], ['mainBusiness', /主营|专注于|从事/],
['products', /产品|服务包括|解决方案/], ['advantages', /优势|擅长|自研/],
['serviceRegions', /地区|区域|覆盖|浙江|江苏|上海|安徽|华东|全国/], ['customerTypes', /客户/],
['projectTypes', /项目类型|项目偏好/], ['amountPreference', /\d+\s*[-~至]\s*\d+\s*万/],
['qualifications', /资质|认证|证书|软著|专利/], ['trackRecord', /业绩|案例|验收|中标/],
['delivery', /交付|售后|驻场|响应/], ['bidPreparation', /标书|准备周期|投标准备/],
['boundaries', /不参与|边界|谨慎/],
]
for (const [key, pattern] of fields) {
const line = lines.find(value => value !== company && pattern.test(value))
if (line) Object.assign(out, { [key]: clean(line) })
}
return out
}
/* 既有 Context 模块同时导出 Provider、useStore 和共享工具;保持调用方兼容,只豁免 Fast Refresh 的组件独占限制。 */
/* eslint-disable react-refresh/only-export-components */
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import type {
CompanyProfile, ResearchConversation, ScheduleTask, SearchBatch, SearchConditions,
CompanyProfile, ScheduleTask, SearchBatch, SearchConditions,
WatchRecord, WatchStatus,
} from '../types'
import { emptyProfile, demoProfile, HISTORY_STATUSES } from '../types'
import { emptyProfile, HISTORY_STATUSES } from '../types'
import { PROJECTS } from '../data/projects'
import type { Project } from '../types'
import { api } from './api'
// ---------- 本地持久化 ----------
const LS_KEY = 'ruzhou-store-v1'
// D1 档案与关注由后端保存;原型数据不自动迁移进真实数据库。
interface Persisted {
profile: CompanyProfile
watch: WatchRecord[]
tasks: ScheduleTask[]
research: ResearchConversation[]
batches: SearchBatch[]
customTags: string[]
customProjects: Project[]
}
/** 旧版状态名 → 新状态名(状态体系细化后的数据迁移) */
const STATUS_MIGRATION: Record<string, WatchStatus> = {
已提交: '已提交投标文件',
已结束: '未中标',
}
const migrateStatus = (s: WatchStatus): WatchStatus => STATUS_MIGRATION[s] ?? s
function loadPersisted(): Persisted {
try {
const raw = localStorage.getItem(LS_KEY)
if (raw) {
const parsed = JSON.parse(raw)
const savedProfile = { ...emptyProfile, ...parsed.profile }
return {
// 从未填写过档案时载入演示档案,便于直接演示匹配度打分;填过则尊重用户数据
profile: savedProfile.companyName.trim() ? savedProfile : { ...demoProfile },
watch: (parsed.watch ?? []).map((w: WatchRecord) => ({
...w,
tags: w.tags ?? [],
status: migrateStatus(w.status),
history: (w.history ?? []).map(h => ({ ...h, status: migrateStatus(h.status) })),
})),
tasks: parsed.tasks ?? [],
research: parsed.research ?? [],
batches: parsed.batches ?? [],
customTags: parsed.customTags ?? [],
customProjects: parsed.customProjects ?? [],
}
}
} catch { /* ignore */ }
return { profile: { ...demoProfile }, watch: [], tasks: [], research: [], batches: [], customTags: [], customProjects: [] }
// 不加载旧浏览器演示公司、账号私有数据或虚构关注。
return { profile: { ...emptyProfile }, watch: [], tasks: [], batches: [], customTags: [], customProjects: [] }
}
export function nowStr(): string {
......@@ -109,10 +81,11 @@ export function conditionsText(c: SearchConditions): string {
// ---------- Context ----------
interface Store {
profile: CompanyProfile
saveProfile: (p: CompanyProfile) => void
saveProfile: (p: CompanyProfile) => Promise<CompanyProfile>
watch: WatchRecord[]
addWatch: (projectId: string) => void
removeWatch: (projectId: string) => void
refreshWatch: () => Promise<void>
addWatch: (projectId: string) => Promise<void>
removeWatch: (projectId: string) => Promise<void>
setWatchStatus: (projectId: string, status: WatchStatus) => void
setWatchNote: (projectId: string, note: string) => void
isWatched: (projectId: string) => boolean
......@@ -127,9 +100,6 @@ interface Store {
saveTask: (t: ScheduleTask) => void
deleteTask: (id: string) => void
runTaskNow: (id: string) => void
research: ResearchConversation[]
saveConversation: (c: ResearchConversation) => void
deleteConversation: (id: string) => void
batches: SearchBatch[]
addBatch: (b: SearchBatch) => void
}
......@@ -139,32 +109,39 @@ const StoreContext = createContext<Store | null>(null)
export function StoreProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState<Persisted>(loadPersisted)
const [ready, setReady] = useState(false)
const [loadError, setLoadError] = useState('')
useEffect(() => {
try { localStorage.setItem(LS_KEY, JSON.stringify(state)) } catch { /* ignore */ }
}, [state])
const saveProfile = useCallback((p: CompanyProfile) => {
setState(s => ({
...s,
profile: { ...p, version: s.profile.version + 1, updatedAt: nowStr() },
}))
let active = true
Promise.all([api<CompanyProfile>('/company-profile'), api<WatchRecord[]>('/watch')])
.then(([profile, watch]) => {
if (!active) return
setState(s => ({ ...s, profile: { ...emptyProfile, ...profile }, watch }))
setReady(true)
}).catch(error => { if (active) setLoadError(error.message) })
return () => { active = false }
}, [])
const addWatch = useCallback((projectId: string) => {
setState(s => {
// 同一个项目只保留一条关注记录,不因重复来源产生多条
if (s.watch.some(w => w.projectId === projectId)) return s
const rec: WatchRecord = {
projectId, status: '已关注', note: '', tags: [], createdAt: nowStr(),
history: [{ status: '已关注', time: nowStr(), note: '' }],
}
return { ...s, watch: [rec, ...s.watch] }
})
const saveProfile = useCallback(async (p: CompanyProfile) => {
const saved = await api<CompanyProfile>('/company-profile', { method: 'PUT', body: JSON.stringify(p) })
const profile = { ...emptyProfile, ...saved }
setState(s => ({ ...s, profile }))
return profile
}, [])
const removeWatch = useCallback((projectId: string) => {
setState(s => ({ ...s, watch: s.watch.filter(w => w.projectId !== projectId) }))
// 服务器确认后再更新共享计数,保存失败时不显示虚假的关注成功。
const refreshWatch = useCallback(async () => {
const watch = await api<WatchRecord[]>('/watch')
setState(s => ({ ...s, watch }))
}, [])
const addWatch = useCallback(async (projectId: string) => {
await api(`/watch/${encodeURIComponent(projectId)}`, { method: 'POST' })
await refreshWatch()
}, [refreshWatch])
const removeWatch = useCallback(async (projectId: string) => {
await api(`/watch/${encodeURIComponent(projectId)}`, { method: 'DELETE' })
await refreshWatch()
}, [refreshWatch])
const setWatchStatus = useCallback((projectId: string, status: WatchStatus) => {
setState(s => ({
......@@ -207,7 +184,7 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
setState(s => {
if (s.customProjects.some(x => x.id === p.id) || PROJECTS.some(x => x.id === p.id)) return s
const rec: WatchRecord = {
projectId: p.id, status: '已关注', note: '', tags: [], createdAt: nowStr(),
version: 1, projectId: p.id, status: '已关注', note: '', tags: [], createdAt: nowStr(),
history: [{ status: '已关注', time: nowStr(), note: '' }],
}
const watch = s.watch.some(w => w.projectId === p.id) ? s.watch : [rec, ...s.watch]
......@@ -243,22 +220,6 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
}))
}, [])
const saveConversation = useCallback((c: ResearchConversation) => {
setState(s => {
const idx = s.research.findIndex(x => x.id === c.id)
if (idx >= 0) {
const next = [...s.research]
next[idx] = c
return { ...s, research: next }
}
return { ...s, research: [c, ...s.research] }
})
}, [])
const deleteConversation = useCallback((id: string) => {
setState(s => ({ ...s, research: s.research.filter(c => c.id !== id) }))
}, [])
const addBatch = useCallback((b: SearchBatch) => {
setState(s => ({ ...s, batches: [b, ...s.batches].slice(0, 30) }))
}, [])
......@@ -267,7 +228,7 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
profile: state.profile,
saveProfile,
watch: state.watch,
addWatch, removeWatch, setWatchStatus, setWatchNote,
refreshWatch, addWatch, removeWatch, setWatchStatus, setWatchNote,
isWatched: (pid: string) => state.watch.some(w => w.projectId === pid),
toggleWatchTag,
customTags: state.customTags,
......@@ -278,12 +239,13 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
findProject: (id: string) => state.customProjects.find(p => p.id === id) ?? PROJECTS.find(p => p.id === id),
tasks: state.tasks,
saveTask, deleteTask, runTaskNow,
research: state.research,
saveConversation, deleteConversation,
batches: state.batches,
addBatch,
}), [state, saveProfile, addWatch, removeWatch, setWatchStatus, setWatchNote, toggleWatchTag, addCustomTag, removeCustomTag, addCustomProject, saveTask, deleteTask, runTaskNow, saveConversation, deleteConversation, addBatch])
}), [state, saveProfile, refreshWatch, addWatch, removeWatch, setWatchStatus, setWatchNote, toggleWatchTag, addCustomTag, removeCustomTag, addCustomProject, saveTask, deleteTask, runTaskNow, addBatch])
// 必须等真实档案加载后再挂载表单,避免空值覆盖已保存数据。
if (loadError) return <div role="alert" className="p-8 text-sm">{loadError}<button className="ml-4 underline" onClick={() => window.location.reload()}>重新连接</button></div>
if (!ready) return <div role="status" className="p-8 text-sm">正在读取公司档案…</div>
return <StoreContext.Provider value={value}>{children}</StoreContext.Provider>
}
......
import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router'
import {
Search, Sparkles, Building2, ChevronLeft, ChevronRight, ExternalLink, Star,
ArrowRight, Layers, SlidersHorizontal, X,
} from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import type { AiPanelState, MatchWeights, Project, ScheduleTask, SearchConditions } from '../types'
import { RESULT_STATUSES } from '../types'
import { useStore, runSearch, conditionsText, uid, nowStr } from '../lib/store'
import { BEE_IMG } from '../lib/assets'
import { matchScore, timeDigest, keyRequirement } from '../lib/ai'
import { ScheduleTasks } from '../components/ScheduleTasks'
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 { cn } from '@/lib/utils'
const PAGE_SIZE = 8
const defaultConditions: SearchConditions = { keyword: '', region: '', budgetMin: '', budgetMax: '', publishRange: '30d' }
const inputCls =
'rounded-ctrl border border-line-soft bg-white px-3 py-2 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10'
const WEIGHT_FIELDS = ['business', 'region', 'amount', 'track'] as const
/** 匹配度维度:名称固定,不开放自定义 */
const DIM_NAMES: Record<(typeof WEIGHT_FIELDS)[number], string> = {
business: '业务贴合',
region: '服务地区',
amount: '金额匹配',
track: '业绩与资质',
}
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'
export function DiscoverPage({ onOpenPanel }: { onOpenPanel: (s: AiPanelState) => void }) {
const { profile, saveProfile, addBatch, tasks, watch, findProject } = useStore()
const navigate = useNavigate()
const [conditions, setConditions] = useState<SearchConditions>(defaultConditions)
const [executed, setExecuted] = useState<SearchConditions | null>(null)
const [resultIds, setResultIds] = useState<string[] | null>(null)
const [showSchedule, setShowSchedule] = useState(false)
/** D2 页面只读服务端事实和匹配度;切换历史 Tab 不执行供应商请求。 */
export function DiscoverPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPanelState) => void }) {
const { profile, watch } = useStore()
const [params, setParams] = useSearchParams()
const [query, setQuery] = useState<SearchQuery>(() => ({ ...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<SearchScheme[]>([])
const [history, setHistory] = useState<SearchHistory[]>([])
const selected = params.get('batch') ?? history.find(run => run.schemeId)?.id ?? null
const [schemeName, setSchemeName] = useState('')
const [editing, setEditing] = useState<SearchScheme | null>(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 [weightDraft, setWeightDraft] = useState<MatchWeights>(profile.matchWeights)
const doSearch = () => {
const ids = runSearch(conditions)
// 档案已完善时,结果按匹配度由高到低排序
if (profile.completed) {
ids.sort((a, b) =>
(matchScore(findProject(b)!, profile)?.score ?? -1) - (matchScore(findProject(a)!, profile)?.score ?? -1))
const [showSchemeForm, setShowSchemeForm] = useState(false)
const [watchPreview, setWatchPreview] = useState<WatchItem[]>([])
const [deleteScheme, setDeleteScheme] = useState<SearchScheme | null>(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: crypto.randomUUID() }
return pending.current.key
}
const batch = { id: uid('batch'), conditions: { ...conditions }, executedAt: nowStr(), projectIds: ids, total: ids.length }
addBatch(batch)
setExecuted({ ...conditions })
setResultIds(ids)
const reload = useCallback(async () => {
const [saved, runs, allowed] = await Promise.all([api<SearchScheme[]>('/search-schemes'), api<SearchHistory[]>('/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 = <K extends keyof SearchQuery>(key: K, value: SearchQuery[K]) => setQuery(current => ({ ...current, [key]: value }))
const runAction = async (action: () => Promise<void>) => {
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 total = resultIds?.length ?? 0
const dirty = executed !== null && JSON.stringify(conditions) !== JSON.stringify(executed)
// 有执行记录的检索方案:结果用与手动检索一致的整表展示,多方案可切换
const ranTasks = useMemo(
() => tasks.filter(t => t.runs.length > 0)
.sort((a, b) => (b.runs[0]?.time ?? '').localeCompare(a.runs[0]?.time ?? '')),
[tasks],
)
const watchPreview = useMemo(
() => watch.map(w => findProject(w.projectId)).filter(Boolean).slice(0, 6) as Project[],
[watch, findProject],
)
// 顶部问候条:按时段问候 + 日期 + 临近报名截止的关注项目数
const hour = new Date().getHours()
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<AgentTask>('/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 today = new Date()
const dateStr = `${today.getMonth() + 1}月${today.getDate()}日 星期${'日一二三四五六'[today.getDay()]}`
const dueSoon = useMemo(() => {
const now = Date.now()
return watch.filter(w => {
const p = findProject(w.projectId)
if (!p?.regDeadline) return false
const t = new Date(p.regDeadline).getTime()
return t >= now && t - now <= 7 * 86400000
const dateLabel = `${local.getMonth() + 1}月${local.getDate()}日 星期${'日一二三四五六'[local.getDay()]}`
useEffect(() => {
let active = true
void api<WatchItem[]>('/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
}, [watch, findProject])
// 问候条动态:不做数据罗列,直接给判断——优先提示各方案结果里的高匹配项目;
// 未配置方案时展示关注与结果进度
const insight = useMemo(() => {
const hits = ranTasks
.map(t => ({
name: t.name,
count: runSearch(t.conditions)
.filter(id => (matchScore(findProject(id)!, profile)?.score ?? 0) >= 90).length,
}))
.filter(h => h.count > 0)
if (hits.length > 0) {
return (
<>
{hits.map((h, i) => (
<span key={h.name}>{i > 0 && '、'}「{h.name}」有 <b className="font-num text-[#FDE68A]">{h.count}</b> 个</span>
))}
{' '}匹配度超过 90 分的项目,建议优先查看
</>
)
}
if (ranTasks.length > 0) {
return <>各检索方案暂无 90 分以上的高匹配项目,可在结果区切换标签查看明细</>
}
if (tasks.length > 0) {
return <>已保存 <b className="font-num text-[#FDE68A]">{tasks.length}</b> 个检索方案,执行后这里会提示高匹配项目</>
}
const resultCount = watch.filter(w => (RESULT_STATUSES as string[]).includes(w.status)).length
return (
<>
重点关注 <b className="font-num text-[#FDE68A]">{watch.length}</b> 个项目,
<b className="font-num text-[#FCA5A5]"> {dueSoon}</b> 个临近报名截止,
已有结果 <b className="font-num text-[#FDE68A]">{resultCount}</b> 个
</>
)
}, [ranTasks, tasks.length, watch, dueSoon, profile, findProject])
return (
<div className="mx-auto max-w-[1120px] px-4 py-4 sm:px-5 sm:py-5 xl:px-6">
{/* 档案已完善:顶部问候条(小巧思:GIF 小助手 + 一句话关键动态) */}
{profile.completed && (
<div className="relative overflow-hidden rounded-card p-6 shadow-card fade-up"
style={{ background: 'linear-gradient(115deg, #1D19DC 0%, #2E54E8 52%, #3F8BF0 100%)' }}>
{/* 装饰圆环与光斑,与品牌视觉一致 */}
<div className="pointer-events-none absolute -top-24 right-40 h-52 w-52 rounded-full border border-white/15" />
<div className="pointer-events-none absolute -top-12 right-52 h-28 w-28 rounded-full border border-white/10" />
<div className="pointer-events-none absolute -bottom-16 right-72 h-32 w-32 rounded-full bg-white/5" />
<div className="relative flex items-center gap-5">
<img src={BEE_IMG} alt="如昼小助手"
className="bee-float h-24 w-24 shrink-0 object-contain drop-shadow-[0_8px_16px_rgba(30,27,75,0.35)]" />
<div className="shrink-0">
<h2 className="text-[22px] font-bold tracking-wide text-white">
{greeting},{profile.companyName.replace(/(有限责任公司|有限公司)$/, '') || '朋友'}
</h2>
<p className="mt-1 text-xs tracking-[0.15em] text-[#BFDBFE]">{dateStr}</p>
</div>
<div className="mx-1 h-12 w-px shrink-0 bg-white/20" />
<div className="min-w-0">
<span className="mb-1.5 inline-flex items-center gap-1 rounded-full bg-white/15 px-2 py-0.5 text-[11px] font-semibold tracking-wide text-[#DBEAFE]">
<Sparkles size={11} /> AI 洞察
</span>
<p className="text-[13.5px] leading-relaxed text-[#DBEAFE]">{insight}</p>
</div>
</div>
</div>
)}
{/* 公司档案:仅在未完善时展示引导栏;已完善则不再占位 */}
{!profile.completed && (
<div className="flex items-center gap-4 rounded-card border-brand-gradient bg-white p-5 shadow-card fade-up">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl"
style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}>
<Building2 size={22} className="text-white" />
</div>
<div className="flex-1">
<h2 className="text-[15px] font-bold">让 AI 像投标专员一样帮你筛项目</h2>
<p className="mt-0.5 text-[13px] text-ink-400">
花 2 分钟填好资质、代表业绩和常做区域,之后每条项目都会自动给出贴合度打分和「先看哪条」的建议——不用再一条条读公告。
</p>
</div>
<PrimaryButton onClick={() => navigate('/profile')}>
立即完善档案 <ArrowRight size={14} />
</PrimaryButton>
</div>
)}
{/* 检索区 */}
// 原型只为“当前结果”和每个已执行方案保留一个页签,不额外展示逐次运行的审计历史。
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 <div className="mx-auto max-w-[1120px] px-4 py-4 sm:px-5 sm:py-5 xl:px-6">
{profile.completed ? <div className="relative overflow-hidden rounded-card p-6 shadow-card fade-up" style={{ background: 'linear-gradient(115deg, #1D19DC 0%, #2E54E8 52%, #3F8BF0 100%)' }}>
<div className="pointer-events-none absolute -top-24 right-40 h-52 w-52 rounded-full border border-white/15" /><div className="pointer-events-none absolute -top-12 right-52 h-28 w-28 rounded-full border border-white/10" /><div className="pointer-events-none absolute -bottom-16 right-72 h-32 w-32 rounded-full bg-white/5" />
<div className="relative flex flex-wrap items-center gap-5 sm:flex-nowrap"><img src={BEE_IMG} alt="如昼小助手" className="bee-float h-24 w-24 shrink-0 object-contain drop-shadow-[0_8px_16px_rgba(30,27,75,0.35)]" /><div className="shrink-0"><h2 className="text-[22px] font-bold tracking-wide text-white">{greeting},{profile.companyName.replace(/(有限责任公司|有限公司)$/, '') || '朋友'}</h2><p className="mt-1 text-xs tracking-[0.15em] text-[#BFDBFE]">{dateLabel}</p></div><div className="mx-1 hidden h-12 w-px shrink-0 bg-white/20 sm:block" /><div className="min-w-0"><span className="mb-1.5 inline-flex items-center gap-1 rounded-full bg-white/15 px-2 py-0.5 text-[11px] font-semibold tracking-wide text-[#DBEAFE]"><Sparkles size={11} /> AI 洞察</span><p className="text-[13.5px] leading-relaxed text-[#DBEAFE]">重点关注 <b className="font-num text-[#FDE68A]">{watch.length}</b> 个项目,<b className="font-num text-[#FCA5A5]"> {dueSoon}</b> 个临近报名截止,已有结果 <b className="font-num text-[#FDE68A]">{watch.filter(w => RESULT_STATUSES.includes(w.status)).length}</b> 个</p></div></div>
</div> : <div className="flex flex-wrap items-center gap-4 rounded-card border-brand-gradient bg-white p-5 shadow-card fade-up"><div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl" style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}><Building2 size={22} className="text-white" /></div><div className="min-w-[200px] flex-1"><h2 className="text-[15px] font-bold">让 AI 像投标专员一样帮你筛项目</h2><p className="mt-0.5 text-[13px] text-ink-400">花 2 分钟填好资质、代表业绩和常做区域,之后每条项目都会自动给出贴合度打分和「先看哪条」的建议——不用再一条条读公告。</p></div><Link to="/profile"><PrimaryButton>立即完善档案 <ArrowRight size={14} /></PrimaryButton></Link></div>}
{(error || streamError) && <div role="alert" className="mt-3 rounded-ctrl bg-red-50 p-3 text-sm text-red-700">{error || streamError}</div>}
<section className="mt-4 rounded-card border border-line-soft bg-white p-5 shadow-card">
<div className="mb-3 flex items-center gap-2">
<Search size={16} className="text-brand-500" />
<h2 className="text-[15px] font-bold">项目检索</h2>
<span className="flex-1" />
<GhostButton onClick={() => {
setWeightDraft({ ...profile.matchWeights })
setShowWeights(true)
}} className="!px-3 !py-1.5 text-xs">
<SlidersHorizontal size={14} /> 匹配度权重
</GhostButton>
<GhostButton onClick={() => setShowSchedule(true)} className="!px-3 !py-1.5 text-xs">
<Layers size={14} /> 检索方案
</GhostButton>
</div>
<div className="mb-3 flex flex-wrap items-center gap-2"><Search size={16} className="text-brand-500" /><h2 className="text-[15px] font-bold">项目检索</h2><span className="flex-1" /><GhostButton onClick={() => setShowWeights(true)} className="!px-3 !py-1.5 text-xs"><SlidersHorizontal size={14} /> 匹配度权重</GhostButton><GhostButton onClick={() => setShowSchemes(true)} className="!px-3 !py-1.5 text-xs"><Layers size={14} /> 检索方案</GhostButton></div>
<form onSubmit={e => { e.preventDefault(); void submit() }}>
<div className="grid grid-cols-12 gap-2.5">
<input value={conditions.keyword} onChange={e => setConditions(c => ({ ...c, keyword: e.target.value }))}
onKeyDown={e => { if (e.key === 'Enter') doSearch() }}
placeholder="关键词(空格分隔多个,如:智慧水务 监测)"
className={cn(inputCls, 'col-span-4')} />
<input value={conditions.region} onChange={e => setConditions(c => ({ ...c, region: e.target.value }))}
onKeyDown={e => { if (e.key === 'Enter') doSearch() }}
placeholder="地区(如:浙江)"
className={cn(inputCls, 'col-span-2')} />
<div className="col-span-3 flex items-center gap-1.5">
<input type="number" min={0} value={conditions.budgetMin} onChange={e => setConditions(c => ({ ...c, budgetMin: e.target.value }))}
placeholder="预算下限" className={cn(inputCls, 'w-full font-num')} />
<span className="text-ink-400">~</span>
<input type="number" min={0} value={conditions.budgetMax} onChange={e => setConditions(c => ({ ...c, budgetMax: e.target.value }))}
placeholder="上限(万元)" className={cn(inputCls, 'w-full font-num')} />
</div>
<select value={conditions.publishRange} onChange={e => setConditions(c => ({ ...c, publishRange: e.target.value as SearchConditions['publishRange'] }))}
className={cn(inputCls, 'col-span-2')}>
<option value="7d">发布于近 7 天</option>
<option value="30d">发布于近 30 天</option>
<option value="90d">发布于近 90 天</option>
<option value="all">全部时间</option>
</select>
<PrimaryButton onClick={doSearch} className="col-span-1 !px-2">
<Search size={15} /> 检索
</PrimaryButton>
</div>
{dirty && (
<div className="mt-2 text-xs text-warn-500">
检索条件已修改但尚未重新执行,下方结果仍对应上一次执行的条件({conditionsText(executed!)})。
</div>
)}
</section>
{/* 检索方案:方案列表收进弹窗,不在首页占位 */}
<ScheduleTasks currentConditions={conditions} open={showSchedule} onClose={() => setShowSchedule(false)} />
{/* 结果区:设置了检索方案时,结果区以标签页呈现(当前检索 + 各方案结果),随时切换 */}
{ranTasks.length > 0 ? (
<TaskResultsSection tasks={ranTasks} currentConditions={conditions}
manual={resultIds !== null && executed !== null ? { ids: resultIds, executed } : null}
onOpenPanel={onOpenPanel} />
) : resultIds === null ? (
watchPreview.length > 0 ? (
<section className="mt-4 overflow-hidden rounded-card border border-line-soft bg-white shadow-card fade-up">
<div className="flex flex-wrap items-center gap-2 border-b border-line-soft px-5 py-3">
<Star size={15} className="text-brand-500" />
<h2 className="text-[15px] font-bold">你重点关注的项目</h2>
<span className="text-xs text-ink-400">共 <span className="font-num">{watch.length}</span> 条,展示前 <span className="font-num">{watchPreview.length}</span> 条</span>
<span className="flex-1" />
<span className="text-xs text-ink-400">在上方设置条件点击「检索」,发现更多商机</span>
</div>
<ul className="divide-y divide-line-soft/70">
{watchPreview.map(p => <ProjectPreviewRow key={p.id} p={p} onOpenPanel={onOpenPanel} />)}
</ul>
</section>
) : (
<section className="mt-4 flex flex-col items-center justify-center rounded-card border border-dashed border-line-soft bg-white py-16 shadow-card">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-brand-50">
<Search size={24} className="text-brand-500" />
</div>
<p className="mt-4 text-sm font-medium text-ink-900">设置检索条件后点击「检索」</p>
<p className="mt-1 text-xs text-ink-400">结果按匹配度由高到低排列,点击任意一行查看 AI 分析</p>
<input aria-label="关键词" value={keyword} onChange={e => setKeyword(e.target.value)} placeholder="关键词(空格分隔多个,如:智慧水务 监测)" className={`${inputClass} col-span-12 lg:col-span-4`} />
<input aria-label="地区" value={regionText} onChange={e => { setRegionText(e.target.value); update(query.mode === 'LEADS' ? 'preferredRegions' : 'hardRegions', words(e.target.value)) }} placeholder="地区(如:浙江)" className={`${inputClass} col-span-6 lg:col-span-2`} />
<div className="col-span-6 flex items-center gap-1.5 lg:col-span-3">{(['Min', 'Max'] as const).map((bound, i) => { const key = (query.mode === 'LEADS' ? `budget${bound}Wan` : `hard${bound}Wan`) as 'budgetMinWan' | 'budgetMaxWan' | 'hardMinWan' | 'hardMaxWan'; return <div key={bound} className="flex min-w-0 items-center gap-1.5">{i > 0 && <span className="text-ink-400">~</span>}<input aria-label={i ? '预算上限' : '预算下限'} type="number" min={0} step="any" value={query[key] ?? ''} onChange={e => update(key, e.target.value === '' ? null : Number(e.target.value))} placeholder={i ? '上限(万元)' : '预算下限'} className={`${inputClass} min-w-0 font-num`} /></div> })}</div>
<select aria-label="发布时间" value={range} onChange={e => { setRange(e.target.value); if (e.target.value !== 'custom') setQuery(q => ({ ...q, beginDate: beijingDate(Number(e.target.value) - 1), endDate: beijingDate() })) }} className={`${inputClass} col-span-9 lg:col-span-2`}>{[['7','发布于近 7 天'], ['30','发布于近 30 天'], ['90','发布于近 90 天'], ['365','全部时间']].map(([v,n]) => <option key={v} value={v}>{n}</option>)}</select>
<PrimaryButton type="submit" disabled={busy} className="col-span-3 !px-2 lg:col-span-1"><Search size={15} /> 检索</PrimaryButton>
</div>
</form>
{dirty && <p className="mt-2 text-xs text-warn-500">检索条件已修改但尚未重新执行,下方结果仍对应上一次执行的条件({report?.conditions.keywords.join(' · ')})。</p>}
</section>
)
) : total === 0 ? (
<section className="mt-4 flex flex-col items-center justify-center rounded-card border border-line-soft bg-white py-16 shadow-card">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-[rgba(245,158,11,.1)]">
<Search size={24} className="text-warn-500" />
</div>
<p className="mt-4 text-sm font-medium text-ink-900">没有符合条件的项目</p>
<p className="mt-1 text-[13px] text-ink-400">可调整关键词、地区、预算或发布时间范围后重新检索(系统不会自动放宽你的条件)</p>
</section>
) : (
<>
<section className="mt-4 overflow-hidden rounded-card border border-line-soft bg-white shadow-card">
<div className="flex flex-wrap items-center gap-3 border-b border-line-soft px-5 py-3">
<h2 className="text-[15px] font-bold">全部结果</h2>
<span className="rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-num font-bold text-brand-500">共 {total} 条</span>
<span className="text-xs text-ink-400">
{conditionsText(executed!)}{profile.completed ? ' · 按匹配度由高到低排序' : ''}
</span>
</div>
{/* 与检索方案结果共用同一张结果表格 */}
<ResultTable key={resultIds.join(',')} ids={resultIds} onOpenPanel={onOpenPanel} />
</section>
</>
)}
{/* 匹配度权重配置 */}
<AnimatePresence>
{showWeights && (
<motion.div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-900/20 backdrop-blur-sm"
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}
onClick={e => { if (e.target === e.currentTarget) setShowWeights(false) }}>
<motion.div className="w-[400px] max-w-[92vw] rounded-card border border-line-soft bg-white p-5 shadow-card-hover"
initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }} transition={{ duration: 0.18 }}>
<div className="flex items-center justify-between">
<h3 className="text-[16px] font-bold">匹配度权重</h3>
<button onClick={() => setShowWeights(false)} className="rounded-full p-1.5 text-ink-400 hover:bg-[#F4F7FB]"><X size={16} /></button>
</div>
<p className="mt-1 text-[13px] text-ink-400">拖动滑块调整各维度权重;合计不为 100 时按比例折算。</p>
<div className="mt-3 space-y-2.5">
{WEIGHT_FIELDS.map(k => (
<div key={k} className="flex items-center gap-3">
<span className="w-20 shrink-0 text-[13px] font-medium text-ink-900">{DIM_NAMES[k]}</span>
<input type="range" min={0} max={100} step={5} value={weightDraft[k]}
onChange={e => setWeightDraft(d => ({ ...d, [k]: Number(e.target.value) }))}
className="flex-1 accent-brand-500" />
<span className="w-12 text-right font-num text-[13px] text-ink-900">{weightDraft[k]}%</span>
</div>
))}
</div>
{(() => {
const sum = weightDraft.business + weightDraft.region + weightDraft.amount + weightDraft.track
return sum !== 100 ? (
<p className="mt-2 text-xs text-warn-500">当前合计 <span className="font-num">{sum}</span>%,保存后按比例折算为 100% 参与计分</p>
) : null
})()}
<div className="mt-4 flex justify-end gap-2">
<GhostButton onClick={() => setShowWeights(false)}>取消</GhostButton>
<PrimaryButton onClick={() => {
saveProfile({ ...profile, matchWeights: weightDraft, matchDimNames: { ...DIM_NAMES } })
setShowWeights(false)
}}>保存权重</PrimaryButton>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
)
}
/** 结果表格:手动检索与检索方案结果共用(含匹配度悬停说明与分页) */
function ResultTable({ ids, onOpenPanel }: { ids: string[]; onOpenPanel: (s: AiPanelState) => void }) {
const { profile, findProject, addWatch, isWatched, watch, customTags, addCustomTag, toggleWatchTag } = useStore()
const [page, setPage] = useState(1)
// 关注后就地打标签的小弹窗:不用切到「重点关注」页再补标签
const [tagPickerFor, setTagPickerFor] = useState<string | null>(null)
const [newTag, setNewTag] = useState('')
const submitNewTag = (pid: string) => {
const t = newTag.trim()
if (!t) return
addCustomTag(t)
const w = watch.find(x => x.projectId === pid)
if (!w?.tags.includes(t)) toggleWatchTag(pid, t)
setNewTag('')
}
const total = ids.length
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const safePage = Math.min(page, pageCount)
const pageIds = useMemo(() => ids.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE), [ids, safePage])
return (
<>
<div>
<table className="w-full text-[13px]">
<thead>
<tr className="border-b border-line-soft bg-[#FAFBFD] text-left text-ink-400">
<th className="w-[30%] px-5 py-2.5 font-medium">项目名称</th>
<th className="px-3 py-2.5 font-medium">招标方</th>
<th className="px-3 py-2.5 font-medium">预算</th>
<th className="px-3 py-2.5 font-medium">时间节奏</th>
<th className="px-3 py-2.5 font-medium">参与门槛</th>
<th className="px-3 py-2.5 font-medium">匹配度</th>
<th className="px-3 py-2.5 font-medium">操作</th>
</tr>
</thead>
<tbody>
{pageIds.map((id, rowIdx) => {
const p = findProject(id)!
const m = matchScore(p, profile)
const t = timeDigest(p)
const k = keyRequirement(p)
const toneCls = { urgent: 'text-bad-500', warn: 'text-warn-500', ok: 'text-ok-500', muted: 'text-ink-400' }[t.tone]
const dotCls = { urgent: 'bg-bad-500', warn: 'bg-warn-500', ok: 'bg-ok-500', muted: 'bg-ink-400' }[t.tone]
const kTone = {
block: 'bg-bad-500/10 text-bad-500',
note: 'bg-[rgba(245,158,11,.1)] text-warn-500',
ok: 'bg-ok-500/10 text-ok-500',
}[k.tone]
return (
<tr key={p.id}
onClick={() => onOpenPanel({ kind: 'project', projectId: p.id })}
title="点击查看该项目的 AI 深入分析"
className="cursor-pointer border-b border-line-soft/70 transition-colors last:border-0 hover:bg-brand-50/40">
<td className="px-5 py-3">
{/* 项目名称直达招标源网页(新标签页打开,保留检索进度) */}
<a href={p.sourceUrl ?? undefined} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()}
className="inline-flex items-start gap-1 font-medium text-ink-900 hover:text-brand-500 hover:underline">
<span>{p.name}</span><ExternalLink size={12} className="mt-1 shrink-0 text-ink-400" />
</a>
<div className="mt-1 flex flex-wrap gap-1">
{p.keywords.slice(0, 2).map(kw => (
<span key={kw} className="rounded-full bg-[#F4F7FB] px-2 py-px text-[11px] text-ink-600">{kw}</span>
))}
</div>
</td>
<td className="px-3 py-3">
<div className="max-w-[150px] leading-snug text-ink-900">{p.purchaser}</div>
<div className="mt-0.5 text-xs text-ink-400">{p.region}</div>
</td>
<td className="whitespace-nowrap px-3 py-3">
{p.budget === null
? <span className="text-ink-400">未披露</span>
: <span className="font-num font-bold text-ink-900">{p.budget.toLocaleString()}<span className="text-xs font-medium text-ink-400"> 万元</span></span>}
</td>
<td className="whitespace-nowrap px-3 py-3" title={t.hint}>
<div className={`flex items-center gap-1.5 font-medium ${toneCls}`}>
<span className={`h-1.5 w-1.5 rounded-full ${dotCls}`} />
{t.label}
</div>
<div className="mt-0.5 font-num text-xs text-ink-400">{t.sub}</div>
</td>
<td className="whitespace-nowrap px-3 py-3">
<span className={cn('rounded-full px-2.5 py-0.5 text-xs font-medium', kTone)} title={p.requirements.join(';')}>
{k.label}
</span>
</td>
<td className="relative whitespace-nowrap px-3 py-3">
{m ? (
<div className="group inline-block cursor-help">
<span className="font-num text-[15px] font-bold text-brand-500">
{m.score}<span className="text-xs font-medium text-ink-400"> 分</span>
</span>
{/* 悬停展示打分维度与权重;完整报告在该行的「AI 分析」中 */}
<div className={cn(
'invisible absolute right-0 z-30 w-72 whitespace-normal break-words rounded-card border border-line-soft bg-white p-3 text-left opacity-0 shadow-card-hover transition-opacity group-hover:visible group-hover:opacity-100',
rowIdx >= pageIds.length - 3 ? 'bottom-full mb-1' : 'top-full mt-1',
)}>
<div className="text-xs font-medium leading-relaxed text-ink-900">贴合度打分构成 <span className="font-normal text-ink-400">(辅助参考,不参与筛选排序)</span></div>
<ul className="mt-1.5 space-y-1.5">
{m.dims.map(d => (
<li key={d.name}>
<div className="flex items-baseline gap-2 text-[12px]">
<span className="shrink-0 text-ink-600">{d.name}</span>
<span className="shrink-0 text-ink-400">权重 <span className="font-num">{d.weight}%</span></span>
<span className="flex-1" />
<span className="font-num font-medium text-ink-900">{d.score} 分</span>
</div>
<div className="mt-0.5 text-[11px] leading-snug text-ink-400">{d.note}</div>
</li>
))}
</ul>
<div className="mt-2 border-t border-line-soft pt-1.5 text-[11px] text-ink-400">点击本行「AI 分析」查看完整打分报告</div>
</div>
</div>
) : (
<span className="text-ink-400" title="完善公司档案后生成,不作为筛选或排序依据">—</span>
)}
</td>
<td className="relative whitespace-nowrap px-3 py-3">
<div className="flex items-center gap-1.5">
<button onClick={e => { e.stopPropagation(); onOpenPanel({ kind: 'project', projectId: p.id }) }}
className="inline-flex items-center gap-1 rounded-full border-brand-gradient px-2.5 py-1 text-[12px] font-medium shadow-card transition-shadow hover:shadow-card-hover">
<Sparkles size={12} className="text-brand-500" />
<span className="text-brand-gradient">AI 分析</span>
</button>
<button onClick={e => {
e.stopPropagation()
if (!isWatched(p.id)) addWatch(p.id)
setTagPickerFor(tagPickerFor === p.id ? null : p.id)
setNewTag('')
}}
title={isWatched(p.id) ? '已在重点关注中,点击管理标签' : '加入重点关注并打标签'}
className="rounded-full p-1.5 text-brand-500 transition-colors hover:bg-brand-50">
<Star size={15} fill={isWatched(p.id) ? 'currentColor' : 'none'} />
</button>
</div>
{/* 关注后的标签弹窗:选择已有标签或新建,不用切页 */}
{tagPickerFor === p.id && (
<>
<div className="fixed inset-0 z-20 cursor-default" onClick={e => { e.stopPropagation(); setTagPickerFor(null) }} />
<div onClick={e => e.stopPropagation()}
className={cn('absolute right-0 z-30 w-60 whitespace-normal rounded-card border border-line-soft bg-white p-3 text-left shadow-card-hover',
rowIdx >= pageIds.length - 2 ? 'bottom-full mb-1' : 'top-full mt-1')}>
<div className="text-xs font-medium text-ink-900">给这个项目打个标签</div>
{customTags.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{customTags.map(tag => {
const on = watch.find(x => x.projectId === p.id)?.tags.includes(tag) ?? false
return (
<button key={tag} onClick={() => toggleWatchTag(p.id, tag)}
className={cn('rounded-full border px-2.5 py-1 text-[12px] transition-colors',
on ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600 hover:border-brand-500/40 hover:text-brand-500')}>
{tag}
</button>
)
})}
</div>
)}
<div className="mt-2 flex gap-1.5">
<input value={newTag} onChange={e => setNewTag(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') submitNewTag(p.id) }}
placeholder="新建标签,回车添加"
className="w-full rounded-ctrl border border-line-soft px-2.5 py-1.5 text-[12px] outline-none placeholder:text-ink-400 focus:border-brand-500/60" />
<button onClick={() => submitNewTag(p.id)} disabled={!newTag.trim()}
className="shrink-0 rounded-ctrl bg-brand-500 px-2.5 text-[12px] text-white disabled:opacity-40">添加</button>
</div>
<button onClick={() => setTagPickerFor(null)}
className="mt-2 w-full rounded-ctrl border border-line-soft py-1 text-[12px] text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500">
完成
</button>
</div>
</>
)}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
{showWeights && <MatchWeightsDialog onClose={() => setShowWeights(false)} />}
<PrototypeDialog open={showSchemes} onClose={() => { if (!busy) setShowSchemes(false) }} title="检索方案" className="w-[720px]">
<span className="absolute left-28 top-5 text-xs text-ink-400">{schemes.length} 个已保存的方案</span>
<PrimaryButton onClick={() => { setEditing(null); setSchemeName(`方案${schemes.length + 1}`); setShowSchemeForm(true) }} className="absolute right-14 top-4 !px-3 !py-1.5 text-xs">新建方案</PrimaryButton>
{!schemes.length ? <p className="px-0 py-10 text-center text-[13px] text-ink-400">还没有检索方案,点右上角「新建方案」,把常用的检索条件存下来一键复用</p> : <ul className="-mx-5 mt-4 divide-y divide-line-soft/70">{schemes.map(scheme => <li key={scheme.id} className="flex items-center gap-3 px-5 py-2.5">
<span className="shrink-0 text-[13px] font-medium text-ink-900">{scheme.name}</span><span className="min-w-0 flex-1 truncate text-xs text-ink-400">{scheme.conditions.keywords.join(' ')} · {scheme.conditions.mode === 'LEADS' ? scheme.conditions.preferredRegions.join('、') : scheme.conditions.hardRegions.join('、')}</span>
<span className="shrink-0 whitespace-nowrap text-xs text-ink-400">{history.find(run => run.schemeId === scheme.id) ? `最近执行 ${time(history.find(run => run.schemeId === scheme.id)!.createdAt)}` : '尚未执行'}</span>
<button aria-label={`执行${scheme.name}`} disabled={busy} title="按这组条件立即执行一次" className="shrink-0 rounded-full p-1.5 text-brand-500 hover:bg-brand-50" onClick={() => void runAction(async () => { const next = await api<AgentTask>(`/search-schemes/${scheme.id}/runs`, { method: 'POST', headers: { 'Idempotency-Key': keyFor({ scheme: scheme.id }) } }); pending.current = null; choose(next.id); setRevision(v => v + 1); await reload(); setShowSchemes(false) })}><Play size={14} /></button>
<button aria-label={`编辑${scheme.name}`} title="编辑" className="shrink-0 rounded-full p-1.5 text-ink-400 hover:bg-canvas hover:text-brand-500" onClick={() => { setQuery(scheme.conditions); setRegionText((scheme.conditions.mode === 'LEADS' ? scheme.conditions.preferredRegions : scheme.conditions.hardRegions).join(',')); setKeyword(scheme.conditions.keywords.join(' ')); const days = Math.round((Date.parse(scheme.conditions.endDate) - Date.parse(scheme.conditions.beginDate)) / 86400000) + 1; setRange(['7', '30', '90'].includes(String(days)) ? String(days) : '365'); setSchemeName(scheme.name); setEditing(scheme); setShowSchemeForm(true) }}><Pencil size={14} /></button>
<button aria-label={`删除${scheme.name}`} title="删除" className="shrink-0 rounded-full p-1.5 text-ink-400 hover:bg-bad-500/10 hover:text-bad-500" onClick={() => setDeleteScheme(scheme)}><Trash2 size={14} /></button>
</li>)}</ul>}
{error && <p role="alert" className="mt-3 text-xs text-bad-500">{error}</p>}
</PrototypeDialog>
<PrototypeDialog open={showSchemeForm} onClose={() => { if (!busy) setShowSchemeForm(false) }} title={editing ? '编辑检索方案' : '新建检索方案'} className="w-[520px]">
<form onSubmit={e => { e.preventDefault(); void saveScheme() }} className="mt-3 space-y-3">
<label className="text-[13px] font-medium text-ink-900">方案名称<input aria-label="方案名称" required maxLength={128} value={schemeName} onChange={e => setSchemeName(e.target.value)} className={`${inputClass} mt-1`} /></label>
<div className="space-y-2 rounded-ctrl border border-line-soft bg-canvas p-3"><div className="text-[13px] font-semibold text-brand-500">检索条件</div><div className="grid grid-cols-2 gap-2">
<input aria-label="方案关键词" placeholder="关键词" value={keyword} onChange={e => setKeyword(e.target.value)} className={`${inputClass} !py-1.5 text-[13px]`} />
<input aria-label="方案地区" placeholder="地区(如:浙江)" value={regionText} onChange={e => { 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 <input key={bound} aria-label={i ? '方案预算上限' : '方案预算下限'} placeholder={i ? '预算上限(万元)' : '预算下限(万元)'} type="number" min={0} step="any" value={query[key] ?? ''} onChange={e => update(key, e.target.value === '' ? null : Number(e.target.value))} className={`${inputClass} !py-1.5 font-num text-[13px]`} /> })}
<select aria-label="方案发布时间" value={range} onChange={e => { setRange(e.target.value); setQuery(q => ({ ...q, beginDate: beijingDate(Number(e.target.value) - 1), endDate: beijingDate() })) }} className={`${inputClass} col-span-2 !py-1.5 text-[13px]`}>{[['7', '发布于近 7 天'], ['30', '发布于近 30 天'], ['90', '发布于近 90 天'], ['365', '全部时间']].map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select>
</div></div>
{error && <p role="alert" className="text-xs text-bad-500">{error}</p>}
<div className="!mt-4 flex justify-end gap-2"><GhostButton onClick={() => setShowSchemeForm(false)}>取消</GhostButton><PrimaryButton type="submit" disabled={busy}>{editing ? '保存修改' : '保存方案'}</PrimaryButton></div>
</form>
</PrototypeDialog>
{(selected || history.some(run => run.schemeId)) ? <section className="mt-4 overflow-hidden rounded-card border border-line-soft bg-white shadow-card">
<div className="flex flex-wrap items-center gap-2 border-b border-line-soft px-5 py-3">{schemeRuns.length > 0 && <Layers size={15} className="text-brand-500" />}<h2 className="text-[15px] font-bold">{schemeRuns.length ? '检索结果' : '全部结果'}</h2>{schemeRuns.length ? <div role="tablist" aria-label="检索结果" className="ml-1 flex gap-0.5 rounded-full bg-[#F4F7FB] p-0.5"><button role="tab" aria-selected={selected === manualRun?.id} disabled={!manualRun} onClick={() => { if (manualRun) choose(manualRun.id) }} className={`rounded-full px-3 py-1 text-xs ${selected === manualRun?.id ? 'bg-white font-medium text-brand-500 shadow-card' : 'text-ink-600 hover:text-brand-500'}`}>当前结果</button>{schemeRuns.map(run => <button key={run.id} role="tab" aria-selected={selected === run.id} onClick={() => choose(run.id)} className={`rounded-full px-3 py-1 text-xs ${selected === run.id ? 'bg-white font-medium text-brand-500 shadow-card' : 'text-ink-600 hover:text-brand-500'}`}>{run.schemeName}结果</button>)}</div> : report && <><span className="rounded-full bg-brand-50 px-2.5 py-0.5 font-num text-xs font-bold text-brand-500">共 {report.items.length} 条</span><span className="text-xs text-ink-400">{conditionLabel}</span></>}<span className="flex-1" /></div>
{schemeRuns.length > 0 && report && <div className="flex flex-wrap items-center gap-2 border-b border-line-soft px-5 py-2 text-xs text-ink-400"><span>{conditionLabel}</span><span>·</span><span>{history.find(run => run.id === selected)?.schemeId ? `最近执行 ${time(history.find(run => run.id === selected)!.createdAt)}` : '手动检索'}</span><span>·</span><span>共 <span className="font-num text-ink-900">{report.items.length}</span> 条</span></div>}
{!selected && <p className="py-16 text-center text-sm text-ink-400">选择历史快照回查,或在上方设置条件开始检索。</p>}
{selected && !task && <p className="p-6 text-sm" role="status">正在加载任务快照…</p>}
{task && <>
{task.status !== 'SUCCEEDED' && <div className="flex flex-wrap items-center gap-3 px-5 py-3 text-xs"><span className="rounded-full bg-brand-50 px-3 py-1 text-brand-500">{taskStates[task.status] ?? task.status}</span><span>{task.question}</span>{active && <GhostButton disabled={busy} onClick={() => void runAction(async () => { await api(`/agent/tasks/${task.id}/cancel`, { method: 'POST' }); setRevision(v => v + 1) })}>取消后续请求</GhostButton>}{task.status.startsWith('WAITING_') && <GhostButton disabled={busy} onClick={() => 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} 积分并继续` : '已补配置,继续原任务'}</GhostButton>}</div>}
{report && <>{active && !report.items.length ? <p role="status" className="p-12 text-center text-sm text-ink-400">正在检索并整理公告…</p> : <OpportunityTable key={selected} items={report.items} batchId={task.id} onOpenPanel={onOpenPanel} />}</>}
</>}
</section> : watchPreview.length > 0 ? <section className="mt-4 overflow-hidden rounded-card border border-line-soft bg-white shadow-card"><div className="flex flex-wrap items-center gap-2 border-b border-line-soft px-5 py-3"><Star size={15} className="text-brand-500" /><h2 className="text-[15px] font-bold">你重点关注的项目</h2><span className="text-xs text-ink-400">共 {watch.length} 条,展示前 {Math.min(watchPreview.length, 6)} 条</span><span className="flex-1" /><span className="text-xs text-ink-400">在上方设置条件点击「检索」,发现更多商机</span></div><ul className="divide-y divide-line-soft/70">{watchPreview.slice(0, 6).map(row => <li key={row.projectId} className="flex items-center gap-3 px-5 py-3 transition-colors hover:bg-brand-50/40"><div className="min-w-0 flex-1"><a href={row.project.url ?? undefined} target="_blank" rel="noreferrer" className="inline-flex max-w-full items-center gap-1 text-[13px] font-medium text-ink-900 hover:text-brand-500 hover:underline"><span className="truncate">{row.project.title}</span><ExternalLink size={11} className="shrink-0 text-ink-400" /></a><p className="mt-0.5 text-xs text-ink-400">{row.project.purchaser} · {row.project.region} · {row.project.budgetWan == null ? '预算未披露' : `${row.project.budgetWan} 万元`}</p></div><span className="shrink-0 text-xs font-medium text-ink-400">{registrationDate(row.summary?.schedule) ? `报名截止 ${registrationDate(row.summary?.schedule)}` : '截止时间未披露'}</span><button onClick={() => onOpenPanel({ kind: 'project', project: { ...row.project, userFileId: row.fileId }, summary: row.summary })} className="inline-flex shrink-0 items-center gap-1 rounded-full border-brand-gradient px-2.5 py-1 text-[12px] font-medium shadow-card hover:shadow-card-hover"><Sparkles size={12} className="text-brand-500" /><span className="text-brand-gradient">AI 分析</span></button></li>)}</ul></section> : <section className="mt-4 flex flex-col items-center justify-center rounded-card border border-dashed border-line-soft bg-white py-16 shadow-card"><div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-brand-50"><Search size={24} className="text-brand-500" /></div><p className="mt-4 text-sm font-medium">设置检索条件后点击「检索」</p><p className="mt-1 text-xs text-ink-400">点击任意一行查看 AI 分析</p></section>}
{deleteScheme && <div role="dialog" aria-modal="true" aria-labelledby="delete-scheme-title" className="fixed inset-0 z-50 flex items-center justify-center bg-black/20 p-4"><div className="w-full max-w-sm rounded-card bg-white p-5 shadow-card"><h3 id="delete-scheme-title" className="font-semibold">删除方案「{deleteScheme.name}」?</h3><p className="mt-2 text-sm text-ink-400">历史执行快照和报告会保留。</p><div className="mt-4 flex justify-end gap-2"><GhostButton onClick={() => setDeleteScheme(null)}>取消</GhostButton><PrimaryButton disabled={busy} onClick={() => void runAction(async () => { await api(`/search-schemes/${deleteScheme.id}`, { method: 'DELETE' }); setDeleteScheme(null); await reload() })}>确认删除</PrimaryButton></div></div></div>}
{/* 分页:说明当前展示范围,不把当前页当作全部 */}
<div className="flex items-center gap-3 px-5 py-3 text-[13px] text-ink-400">
<span>第 <span className="font-num text-ink-900">{(safePage - 1) * PAGE_SIZE + 1}–{Math.min(safePage * PAGE_SIZE, total)}</span> 条,共 <span className="font-num text-ink-900">{total}</span> 条</span>
<span className="flex-1" />
<GhostButton onClick={() => setPage(p => Math.max(1, p - 1))} disabled={safePage <= 1} className="!px-2.5 !py-1 text-xs">
<ChevronLeft size={14} /> 上一页
</GhostButton>
<span className="font-num">第 {safePage} / {pageCount} 页</span>
<GhostButton onClick={() => setPage(p => Math.min(pageCount, p + 1))} disabled={safePage >= pageCount} className="!px-2.5 !py-1 text-xs">
下一页 <ChevronRight size={14} />
</GhostButton>
</div>
</>
)
}
/** 结果区(有检索方案时):标签页切换「当前检索」与各方案结果,全部共用同一张结果表格 */
function TaskResultsSection({ tasks, currentConditions, manual, onOpenPanel }: {
tasks: ScheduleTask[]
currentConditions: SearchConditions
/** 手动检索的结果(未执行过手动检索时为 null,当前检索标签页展示实时结果) */
manual: { ids: string[]; executed: SearchConditions } | null
onOpenPanel: (s: AiPanelState) => void
}) {
const { profile, findProject } = useStore()
const [activeId, setActiveId] = useState<string>(manual ? 'current' : (tasks[0]?.id ?? 'current'))
// 每次手动检索执行后,自动切到「当前检索」标签页
const prevManual = useRef(manual)
useEffect(() => {
if (manual && manual !== prevManual.current) setActiveId('current')
prevManual.current = manual
}, [manual])
const isCurrent = activeId === 'current'
const active = tasks.find(t => t.id === activeId) ?? null
const ids = useMemo(() => {
const conds = isCurrent ? (manual?.executed ?? currentConditions) : active?.conditions
if (!conds) return [] as string[]
// 手动检索结果已按同一口径排序,直接复用;其余实时计算
if (isCurrent && manual) return manual.ids
const list = runSearch(conds)
if (profile.completed) {
list.sort((a, b) =>
(matchScore(findProject(b)!, profile)?.score ?? -1) - (matchScore(findProject(a)!, profile)?.score ?? -1))
}
return list
}, [isCurrent, manual, currentConditions, active, profile, findProject])
if (!active && !isCurrent) return null
const last = active?.runs[0]
const activeConds = isCurrent ? (manual?.executed ?? currentConditions) : active!.conditions
return (
<section className="mt-4 overflow-hidden rounded-card border border-line-soft bg-white shadow-card fade-up">
<div className="flex flex-wrap items-center gap-2 border-b border-line-soft px-5 py-3">
<Layers size={15} className="text-brand-500" />
<h2 className="text-[15px] font-bold">检索结果</h2>
<div className="ml-1 flex gap-0.5 rounded-full bg-[#F4F7FB] p-0.5">
<button onClick={() => setActiveId('current')}
className={cn('rounded-full px-3 py-1 text-xs transition-colors',
isCurrent ? 'bg-white font-medium text-brand-500 shadow-card' : 'text-ink-600 hover:text-brand-500')}>
当前结果
</button>
{tasks.map(t => (
<button key={t.id} onClick={() => setActiveId(t.id)}
className={cn('rounded-full px-3 py-1 text-xs transition-colors',
t.id === activeId ? 'bg-white font-medium text-brand-500 shadow-card' : 'text-ink-600 hover:text-brand-500')}>
{t.name}结果
</button>
))}
</div>
<span className="flex-1" />
</div>
<div className="flex flex-wrap items-center gap-2 border-b border-line-soft px-5 py-2 text-xs text-ink-400">
<span>{conditionsText(activeConds)}</span>
<span>·</span>
{isCurrent ? (
<span>{manual ? '手动检索' : '实时计算'}</span>
) : (
<span>最近执行 <span className="font-num">{last?.time}</span></span>
)}
<span>·</span>
<span>共 <span className="font-num text-ink-900">{ids.length}</span> 条{profile.completed ? ',按匹配度由高到低排序' : ''}</span>
</div>
{ids.length === 0 ? (
<div className="flex flex-col items-center justify-center py-14">
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[rgba(245,158,11,.1)]">
<Search size={20} className="text-warn-500" />
</div>
<p className="mt-3 text-sm font-medium text-ink-900">这组条件下没有符合条件的项目</p>
<p className="mt-1 text-[13px] text-ink-400">可在上方调整关键词、地区、预算或发布时间范围后重新检索</p>
</div>
) : (
<ResultTable key={`${activeId}|${ids.join(',')}`} ids={ids} onOpenPanel={onOpenPanel} />
)}
</section>
)
}
/** 空态填充用的紧凑项目行:名称直达公告源网页,右侧直接给时间判断与 AI 分析入口 */
function ProjectPreviewRow({ p, onOpenPanel }: { p: Project; onOpenPanel: (s: AiPanelState) => void }) {
const t = timeDigest(p)
const toneCls = { urgent: 'text-bad-500', warn: 'text-warn-500', ok: 'text-ok-500', muted: 'text-ink-400' }[t.tone]
return (
<li className="flex items-center gap-3 px-5 py-3 transition-colors hover:bg-brand-50/40">
<div className="min-w-0 flex-1">
<a href={p.sourceUrl ?? undefined} target="_blank" rel="noreferrer"
className="inline-flex max-w-full items-center gap-1 text-[13px] font-medium text-ink-900 hover:text-brand-500 hover:underline">
<span className="truncate">{p.name}</span><ExternalLink size={11} className="shrink-0 text-ink-400" />
</a>
<div className="mt-0.5 truncate text-xs text-ink-400">
{p.purchaser} · {p.region} · {p.budget === null ? '预算未披露' : <span className="font-num">{p.budget.toLocaleString()} 万元</span>}
</div>
</div>
<span className={cn('shrink-0 text-xs font-medium', toneCls)} title={t.hint}>{t.label}</span>
<button onClick={() => onOpenPanel({ kind: 'project', projectId: p.id })}
className="inline-flex shrink-0 items-center gap-1 rounded-full border-brand-gradient px-2.5 py-1 text-[12px] font-medium shadow-card transition-shadow hover:shadow-card-hover">
<Sparkles size={12} className="text-brand-500" /><span className="text-brand-gradient">AI 分析</span>
</button>
</li>
)
}
import { useState } from 'react'
import { login } from '../lib/api'
import { useNavigate } from 'react-router'
import { Compass, Sparkles, Bell, User, Lock, ArrowRight } from 'lucide-react'
import { PrimaryButton } from '../components/ui-ext/AiButton'
import { BEE_IMG } from '../lib/assets'
/** 登录页:演示环境任意账号密码可登录;登录态记录在本地 */
/** 仅服务端密码验证成功后进入工作台;失败保留表单并显示统一错误。 */
export function LoginPage({ onLogin }: { onLogin: () => void }) {
const navigate = useNavigate()
const [account, setAccount] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const submit = () => {
const submit = async () => {
if (busy) return
if (!account.trim()) { setError('请输入账号'); return }
if (!password.trim()) { setError('请输入密码'); return }
setBusy(true)
try {
await login(account.trim(), password)
onLogin()
navigate('/', { replace: true })
} catch (error) { setError(error instanceof Error ? error.message : '登录失败') }
finally { setBusy(false) }
}
return (
......@@ -58,34 +66,32 @@ export function LoginPage({ onLogin }: { onLogin: () => void }) {
<div className="mt-7 space-y-4">
<div>
<label className="text-[13px] font-medium text-ink-900">账号</label>
<label htmlFor="login-account" className="text-[13px] font-medium text-ink-900">账号</label>
<div className="relative mt-1.5">
<User size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400" />
<input value={account} onChange={e => { setAccount(e.target.value); setError('') }}
<input id="login-account" value={account} onChange={e => { setAccount(e.target.value); setError('') }}
onKeyDown={e => { if (e.key === 'Enter') submit() }}
placeholder="请输入手机号或邮箱"
placeholder="请输入手机号或邮箱" autoComplete="username"
className="w-full rounded-ctrl border border-line-soft bg-white py-2.5 pl-9 pr-3 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
</div>
<div>
<label className="text-[13px] font-medium text-ink-900">密码</label>
<label htmlFor="login-password" className="text-[13px] font-medium text-ink-900">密码</label>
<div className="relative mt-1.5">
<Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400" />
<input type="password" value={password} onChange={e => { setPassword(e.target.value); setError('') }}
<input id="login-password" type="password" value={password} onChange={e => { setPassword(e.target.value); setError('') }}
onKeyDown={e => { if (e.key === 'Enter') submit() }}
placeholder="请输入密码"
placeholder="请输入密码" autoComplete="current-password"
className="w-full rounded-ctrl border border-line-soft bg-white py-2.5 pl-9 pr-3 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
</div>
{error && <div className="text-xs text-bad-500">{error}</div>}
<PrimaryButton onClick={submit} className="w-full !py-2.5 text-sm">
<PrimaryButton onClick={() => void submit()} disabled={busy} loading={busy} className="w-full !py-2.5 text-sm">
登 录 <ArrowRight size={15} />
</PrimaryButton>
</div>
<div className="mt-6 text-center text-xs text-ink-400">
演示环境:输入任意账号密码即可登录
</div>
<div className="mt-6 h-4" aria-hidden="true" />
</div>
</div>
</div>
......
import { useRef, useState } from 'react'
import { Building2, Save, Upload, Sparkles } from 'lucide-react'
import type { CompanyProfile } from '../types'
import { extractProfileFromText } from '../lib/profileImport'
import { useStore } from '../lib/store'
import Pill from '../components/ui-ext/Pill'
import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton'
......@@ -71,36 +72,6 @@ const GROUPS: { title: string; desc: string; fields: FieldDef[] }[] = [
]
// 最低填写要求(演示口径):企业名称 + 主营业务
function meetsMinimum(p: CompanyProfile): boolean {
return p.companyName.trim() !== '' && p.mainBusiness.trim() !== ''
}
// 演示环境的 AI 导入抽取:基于关键词的启发式匹配,正式接入后由 AI 模型从文件中抽取
function extractProfileFromText(text: string): Partial<CompanyProfile> {
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean)
const pick = (re: RegExp) => {
const line = lines.find(l => re.test(l))
return line ? line.replace(/^[-*•\d.、\s]+/, '').slice(0, 300) : undefined
}
const out: Partial<CompanyProfile> = {}
const put = (key: keyof CompanyProfile, v?: string) => { if (v) (out as Record<string, string>)[key] = v }
put('companyName', pick(/有限公司|股份公司|集团/))
put('intro', pick(/简介|成立于|是一家/))
put('mainBusiness', pick(/主营|主营业务|专注于|从事/))
put('products', pick(/产品|服务包括|解决方案/))
put('advantages', pick(/优势|擅长|自研/))
put('serviceRegions', pick(/地区|区域|覆盖|浙江|江苏|上海|安徽|华东|全国/))
put('customerTypes', pick(/客户/))
put('projectTypes', pick(/项目类型|偏好/))
put('amountPreference', pick(/\d+\s*[-~至]\s*\d+\s*万/))
put('qualifications', pick(/资质|认证|证书|软著|专利/))
put('trackRecord', pick(/业绩|案例|验收|中标/))
put('delivery', pick(/交付|售后|驻场|响应/))
put('bidPreparation', pick(/标书|准备周期|投标准备/))
put('boundaries', pick(/不参与|边界|谨慎/))
return out
}
const FIELD_LABELS: Record<string, string> = Object.fromEntries(
GROUPS.flatMap(g => g.fields.map(f => [f.key, f.label])),
)
......@@ -110,6 +81,8 @@ const inputCls =
export function ProfilePage() {
const { profile, saveProfile } = useStore()
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [form, setForm] = useState<CompanyProfile>({ ...profile })
const [savedTip, setSavedTip] = useState<string | null>(null)
const fileRef = useRef<HTMLInputElement>(null)
......@@ -125,6 +98,8 @@ export function ProfilePage() {
const f = e.target.files?.[0]
e.target.value = ''
if (!f) return
if (f.size > 2 * 1024 * 1024) { setImportError('介绍文件不能超过 2 MB,请精简后导入'); return }
try {
const text = await f.text()
const extracted = extractProfileFromText(text)
if (Object.keys(extracted).length === 0) {
......@@ -132,8 +107,8 @@ export function ProfilePage() {
setImported(null)
return
}
setImportError('')
setImported(extracted)
setImportError(''); setImported(extracted)
} catch { setImportError('文件读取失败,请重新选择 TXT 或 Markdown 文件') }
}
const applyImport = () => {
......@@ -143,13 +118,16 @@ export function ProfilePage() {
setSavedTip(null)
}
const save = () => {
const completed = meetsMinimum(form)
saveProfile({ ...form, completed })
setForm(f => ({ ...f, completed }))
setSavedTip(completed
? '档案已保存并标记为「已完善」,项目分析将结合公司情况给出有依据的建议。'
: '已保存,但尚未达到「已完善」的最低要求(需填写企业名称与主营业务),匹配度暂不生成。')
const save = async () => {
if (busy) return
setBusy(true); setError(''); setSavedTip(null)
try {
// 完善状态和版本必须使用服务端结果;保存失败时不显示成功或递增本地版本。
const saved = await saveProfile(form)
setForm(saved)
setSavedTip(saved.completed ? '档案已保存,已达到企业名称与主营业务的最低要求。' : '档案已保存;补充企业名称与主营业务后才能生成匹配度。')
} catch (error) { setError(error instanceof Error ? error.message : '保存失败') }
finally { setBusy(false) }
}
return (
......@@ -159,18 +137,19 @@ export function ProfilePage() {
<h1 className="text-[17px] font-bold">公司档案</h1>
<Pill status={profile.completed ? '已完善' : '未完善'} />
{profile.completed && (
<span className="text-xs text-ink-400">v<span className="font-num">{profile.version}</span> · 更新于 <span className="font-num">{profile.updatedAt}</span></span>
<span className="text-xs text-ink-400">v<span className="font-num">{profile.version}</span> · 更新于 <span className="font-num">{profile.updatedAt ? new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', dateStyle: 'short', timeStyle: 'short', hour12: false }).format(new Date(profile.updatedAt)) : '尚未保存'}</span></span>
)}
<span className="flex-1" />
<input ref={fileRef} type="file" accept=".txt,.md,.text,.markdown" className="hidden" onChange={onImportFile} />
<GhostButton onClick={() => fileRef.current?.click()}>
<GhostButton onClick={() => fileRef.current?.click()} title="按关键词识别 TXT / Markdown 字段,核对后写入表单">
<Upload size={14} /> AI 导入
</GhostButton>
<PrimaryButton onClick={save}>
<PrimaryButton onClick={() => void save()} disabled={busy} loading={busy}>
<Save size={14} /> 保存档案
</PrimaryButton>
</div>
{error && <p role="alert" className="mt-3 text-sm text-bad-500">{error}</p>}
{importError && (
<div className="mt-3 rounded-ctrl border border-warn-500/30 bg-warn-500/5 px-3.5 py-2.5 text-[13px] text-warn-500 fade-up">
{importError}
......@@ -181,7 +160,7 @@ export function ProfilePage() {
<section className="mt-3 rounded-card border-brand-gradient bg-white p-4 shadow-card fade-up">
<div className="flex items-center gap-2">
<Sparkles size={14} className="shrink-0 text-brand-500" />
<span className="text-[13px] font-medium text-brand-500">AI 已从文件抽取以下内容</span>
<span className="text-[13px] font-medium text-brand-500">已从文件抽取以下内容</span>
<span className="text-xs text-ink-400">请核对后写入,写入前不会改动当前表单</span>
</div>
<ul className="mt-2.5 space-y-1.5">
......@@ -216,17 +195,17 @@ export function ProfilePage() {
<div className="mt-3 space-y-3">
{g.fields.map(f => (
<div key={f.key}>
<label className="text-[13px] font-medium text-ink-900">
<label htmlFor={`profile-${f.key}`} className="text-[13px] font-medium text-ink-900">
{f.label}
{(f.key === 'companyName' || f.key === 'mainBusiness') && (
<span className="ml-1 text-xs font-normal text-warn-500">(最低必填)</span>
)}
</label>
{f.textarea ? (
<textarea rows={2} value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder}
<textarea id={`profile-${f.key}`} rows={2} value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder}
className={cn(inputCls, 'mt-1 w-full resize-y scrollbar-thin')} />
) : (
<input value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder}
<input id={`profile-${f.key}`} value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder}
className={cn(inputCls, 'mt-1 w-full')} />
)}
</div>
......
import { useEffect, useRef, useState } from 'react'
import { useSearchParams } from 'react-router'
import {
MessagesSquare, UserSearch, GitCompareArrows, Map, Send,
X, Check, Loader2, CircuitBoard,
} from 'lucide-react'
import type { ChatMessage, ResearchConversation } from '../types'
import { useStore, uid, nowStr } from '../lib/store'
import { researchAnswer } from '../lib/ai'
import { Markdown } from '../components/Markdown'
import { useStreaming, runSkillTrace } from '../hooks/useStreaming'
import { useNavigate, useSearchParams } from 'react-router'
import { MessagesSquare, UserSearch, GitCompareArrows, Map, Send, X, Loader2 } from 'lucide-react'
import { api } from '../lib/api'
import { conversationsChanged } from '../lib/conversations'
import type { Conversation } from '../lib/conversations'
import type { AgentTask } from '../hooks/useTaskEvents'
import type { ResearchRequest } from '../lib/day3'
import { initialQuery, message, words } from '../lib/day2'
import { ConversationView } from '../components/ConversationView'
import { ResearchTask } from '../components/ResearchTask'
import { PrimaryButton } from '../components/ui-ext/AiButton'
type Entry = 'customer' | 'competitor' | 'market' | null
const ENTRIES = [
{ key: 'customer' as Entry, icon: UserSearch, title: '查目标客户', desc: '这家公司做什么,采购过什么?', placeholder: '输入完整企业名称,如:某某水务集团有限公司' },
{ key: 'competitor' as Entry, icon: GitCompareArrows, title: '查竞争对手', desc: '这家公司的业务和客户情况怎样?', placeholder: '输入竞争对手的完整名称,可补充关注业务' },
{ key: 'market' as Entry, icon: Map, title: '查区域市场', desc: '某地区智慧水务需求如何?', placeholder: '如:调研华东地区近一年的智慧水务市场' },
]
interface LocalMsg extends ChatMessage {
streaming?: boolean
pendingTrace?: boolean
}
{ key: 'customer', icon: UserSearch, title: '查目标客户', desc: '这家公司做什么,采购过什么?', placeholder: '输入完整企业名称,如:某某水务集团有限公司' },
{ key: 'competitor', icon: GitCompareArrows, title: '查竞争对手', desc: '这家公司的业务和客户情况怎样?', placeholder: '输入竞争对手的完整名称,可补充关注业务' },
{ key: 'market', icon: Map, title: '查区域市场', desc: '某地区智慧水务需求如何?', placeholder: '如:调研华东地区近一年的智慧水务市场' },
] as const
/** 界面只使用原型的三个入口及输入框;真实任务仍在服务端创建、确认和保存。 */
export function ResearchPage() {
const { research, saveConversation } = useStore()
const [convId, setConvId] = useState<string | null>(null)
const [messages, setMessages] = useState<LocalMsg[]>([])
const [title, setTitle] = useState('')
const [entry, setEntry] = useState<Entry>(null)
const [input, setInput] = useState('')
const [busy, setBusy] = useState(false)
const scrollRef = useRef<HTMLDivElement>(null)
const traceCancelRef = useRef<(() => void) | null>(null)
// 新对话的 convId 在流式输出完成后才入库;入库前先记入待持久化集合,避免被“对话已删除”守卫误清
const pendingConvRef = useRef<Set<string>>(new Set())
const { stream, stop } = useStreaming()
const [searchParams, setSearchParams] = useSearchParams()
const [params, setParams] = useSearchParams()
const navigate = useNavigate()
const entry = params.get('entry') || ''
const selected = params.get('task')
const conversationId = params.get('conv')
const qaBatch = params.get('qaBatch'), qaProject = params.get('qaProject')
const [input, setInput] = useState(params.get('input') || '')
const [busy, setBusy] = useState(false), [error, setError] = useState('')
const [budget, setBudget] = useState({ maxCalls: 18, maxCostUnits: 10 })
const [fileId, setFileId] = useState<string | null>(null)
const pending = useRef<{ signature: string; key: string; conversationId?: string } | null>(null)
useEffect(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })
}, [messages])
useEffect(() => () => { stop(); traceCancelRef.current?.() }, [stop])
const messagesRef = useRef<LocalMsg[]>([])
useEffect(() => { messagesRef.current = messages }, [messages])
const persist = (msgs: LocalMsg[], t: string, id: string | null): string => {
const cid = id ?? uid('conv')
const existing = research.find(c => c.id === cid)
const conv: ResearchConversation = {
id: cid,
title: t || existing?.title || '未命名调研',
createdAt: existing?.createdAt ?? nowStr(),
messages: msgs.map(({ streaming: _s, pendingTrace: _p, ...m }) => m),
}
saveConversation(conv)
return cid
}
const ask = (raw: string) => {
const q = raw.trim()
if (!q || busy) return
setBusy(true)
setInput('')
const userMsg: LocalMsg = { role: 'user', content: q, time: nowStr() }
const result = researchAnswer(q, entry)
const assistantMsg: LocalMsg = {
role: 'assistant', content: '', time: nowStr(),
skillTrace: [], pendingTrace: true,
}
setMessages([...messages, userMsg, assistantMsg])
const newTitle = title || result.title
if (!title) setTitle(newTitle)
const cid = convId ?? uid('conv')
if (!convId) setConvId(cid)
pendingConvRef.current.add(cid)
// 展示实际发生的 Skill 调用进展,再输出结果
traceCancelRef.current?.()
traceCancelRef.current = runSkillTrace(result.skillTrace, doneSteps => {
setMessages(m => {
const arr = [...m]
arr[arr.length - 1] = { ...arr[arr.length - 1], skillTrace: doneSteps, pendingTrace: true }
return arr
})
}, () => {
stream(result.markdown, (partial, done) => {
setMessages(m => {
const arr = [...m]
arr[arr.length - 1] = { ...arr[arr.length - 1], content: partial, streaming: !done, pendingTrace: false }
return arr
})
if (done) {
setBusy(false)
pendingConvRef.current.delete(cid)
persist(messagesRef.current, newTitle, cid)
let active = true
// 请求保护沿用服务端上限,不为了展示技术参数增加原型没有的设置入口。
void api<{ maxCalls: number; maxCostUnits: number }>('/system/limits').then(value => {
if (active) setBudget({ maxCalls: Math.min(18, value.maxCalls), maxCostUnits: Math.min(10, value.maxCostUnits) })
}).catch(e => { if (active) setError(message(e)) })
return () => { active = false }
}, [])
useEffect(() => {
const id = params.get('file')
if (!id) return
let active = true
// 从已有项目携带的附件仍须校验账号归属与有效期,不能信任 URL 中的文件 ID。
void api<{ status: string }>(`/files/${encodeURIComponent(id)}`).then(file => {
if (!active) return
if (file.status !== 'READY') { setError('文件已删除或过期,请重新上传'); return }
setFileId(id)
}).catch(e => { if (active) setError(message(e)) })
return () => { active = false }
}, [params])
const create = async (request: unknown, path = '/agent/tasks') => {
const signature = `${path}:${JSON.stringify(request)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
if (!pending.current.conversationId) {
const conversation = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) })
pending.current.conversationId = conversation.id
}
})
})
setEntry(null)
// 响应未知时保留原键和会话;重试只回读同一次提交,不重复创建收费任务。
const task = await api<AgentTask>(path, { method: 'POST', headers: { 'Idempotency-Key': pending.current.key }, body: JSON.stringify(request) })
const conv = pending.current.conversationId
await api(`/conversations/${conv}/tasks`, { method: 'POST', body: JSON.stringify({ taskId: task.id }) })
pending.current = null; conversationsChanged()
if (path === '/searches') navigate(`/?batch=${task.id}`)
else setParams({ conv })
}
const openConversation = (c: ResearchConversation) => {
stop(); traceCancelRef.current?.()
setConvId(c.id)
setTitle(c.title)
setMessages(c.messages.map(m => ({ ...m })))
setBusy(false)
const start = async () => {
if (busy || (!input.trim() && !fileId)) return
setBusy(true); setError('')
try {
if (entry === 'market') {
await create({ conditions: { ...initialQuery(), keywords: words(input), mode: 'MARKET' }, ...budget }, '/searches')
} else {
const project = entry === 'project'
const research: ResearchRequest = {
companies: project ? [] : [input.trim()], selections: {}, mode: 'QUICK', fileId: project ? fileId : null,
parentId: params.get('parent'), targetProjectId: params.get('project'), focus: null, acknowledgedCalls: 0,
}
const newConversation = () => {
stop(); traceCancelRef.current?.()
setConvId(null); setTitle(''); setMessages([]); setBusy(false); setEntry(null)
await create({ operation: project ? 'BID_RESEARCH' : 'COMPANY_RESEARCH', workflow: project ? 'BID_DECISION' : 'COMPANY_INTEL', input: project ? input.trim() : '', entityConfirmed: false, ...budget, research })
}
// 左侧导航栏通过 URL 参数控制:?conv=<id> 打开历史对话,?new=1 新建对话
useEffect(() => {
const conv = searchParams.get('conv')
const isNew = searchParams.get('new')
if (!conv && !isNew) return
if (conv) {
const c = research.find(x => x.id === conv)
if (c) openConversation(c)
} else {
newConversation()
} catch (e) { setError(message(e)) } finally { setBusy(false) }
}
setSearchParams({}, { replace: true })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParams])
// 当前对话在左侧导航被删除时,重置为新对话(待持久化的新对话除外)
useEffect(() => {
if (convId && !pendingConvRef.current.has(convId) && !research.some(c => c.id === convId)) newConversation()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [research, convId])
return (
<div className="flex h-full">
{/* 对话区 */}
if (conversationId || qaBatch || qaProject) return <ConversationView key={conversationId ?? `${qaBatch}:${qaProject}`} id={conversationId ?? undefined} scope={qaBatch || qaProject ? { batchId: qaBatch, projectId: qaProject } : undefined} />
return <div className="flex h-full">
<div className="flex min-w-0 flex-1 flex-col">
<div ref={scrollRef} className="flex-1 overflow-y-auto px-6 py-5 scrollbar-thin">
{messages.length === 0 ? (
<div className="mx-auto max-w-[720px] pt-10">
<div className="flex-1 overflow-y-auto px-6 py-5 scrollbar-thin">
{selected ? <div className="mx-auto max-w-[820px] space-y-4"><ResearchTask id={selected} /></div> : <div className="mx-auto max-w-[720px] pt-10">
<div className="text-center">
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl shadow-card-hover"
style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}>
<MessagesSquare size={24} className="text-white" />
</div>
<h1 className="mt-4 text-[22px] font-bold">
对话<span className="text-brand-gradient">调研</span>
</h1>
</div>
<div className="mt-7 grid grid-cols-3 gap-3">
{ENTRIES.map(e => (
<button key={e.key} onClick={() => { setEntry(e.key); setInput('') }}
className="rounded-card border border-line-soft bg-white p-4 text-left shadow-card transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-500/40 hover:shadow-card-hover">
<div className="flex h-9 w-9 items-center justify-center rounded-ctrl bg-brand-50">
<e.icon size={18} className="text-brand-500" />
</div>
<div className="mt-2.5 text-[14px] font-semibold text-ink-900">{e.title}</div>
<div className="mt-0.5 text-xs text-ink-400">{e.desc}</div>
</button>
))}
</div>
</div>
) : (
<div className="mx-auto max-w-[820px] space-y-4">
{messages.map((m, i) => (
<div key={i} className={m.role === 'user' ? 'flex justify-end' : ''}>
{m.role === 'user' ? (
<div className="max-w-[80%] rounded-2xl rounded-br-sm bg-brand-500 px-4 py-2 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]">{m.content}</div>
) : (
<div className="rounded-card border border-line-soft bg-white px-4 py-3 shadow-card">
{m.skillTrace && (
<div className="mb-2 rounded-ctrl border border-line-soft bg-canvas px-3 py-2">
<div className="flex items-center gap-2 text-[12px] font-semibold text-brand-500">
{m.pendingTrace ? <Loader2 size={13} className="animate-spin" /> : <CircuitBoard size={13} />}
Skill 调用进展
</div>
<ul className="mt-1 space-y-1">
{m.skillTrace.map((s, j) => (
<li key={j} className="flex items-center gap-1.5 text-[12px] text-ink-600 fade-up">
<Check size={12} className="text-ok-500" /> {s}
</li>
))}
</ul>
</div>
)}
{m.content ? <Markdown text={m.content} streaming={m.streaming} /> : null}
{m.time && !m.streaming && <div className="mt-2 font-num text-[11px] text-ink-400">{m.time}</div>}
</div>
)}
</div>
))}
</div>
)}
</div>
{/* 输入区 */}
<div className="border-t border-line-soft bg-white/75 px-6 py-3 backdrop-blur-md">
<div className="mx-auto max-w-[820px]">
{entry && (
<div className="mb-2 inline-flex items-center gap-2 rounded-full bg-brand-50 px-2.5 py-1 text-xs text-brand-500">
已选入口:{ENTRIES.find(e => e.key === entry)?.title}
<button onClick={() => setEntry(null)} className="hover:text-bad-500"><X size={12} /></button>
</div>
)}
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl shadow-card-hover" style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}><MessagesSquare size={24} className="text-white" /></div>
<h1 className="mt-4 text-[22px] font-bold">对话<span className="text-brand-gradient">调研</span></h1>
</div>
<div className="mt-7 grid grid-cols-3 gap-3">{ENTRIES.map(item => <button key={item.key} onClick={() => { setParams({ entry: item.key }); setInput('') }} className="rounded-card border border-line-soft bg-white p-4 text-left shadow-card transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-500/40 hover:shadow-card-hover">
<div className="flex h-9 w-9 items-center justify-center rounded-ctrl bg-brand-50"><item.icon size={18} className="text-brand-500" /></div>
<div className="mt-2.5 text-[14px] font-semibold text-ink-900">{item.title}</div><div className="mt-0.5 text-xs text-ink-400">{item.desc}</div>
</button>)}</div>
</div>}
{error && <p role="alert" className="mx-auto mt-4 max-w-[820px] text-xs text-bad-500">{error}</p>}
</div>
{!selected && <div className="border-t border-line-soft bg-white/75 px-6 py-3 backdrop-blur-md"><form onSubmit={e => { e.preventDefault(); void start() }} className="mx-auto max-w-[820px]">
{ENTRIES.some(item => item.key === entry) && <div className="mb-2 inline-flex items-center gap-2 rounded-full bg-brand-50 px-2.5 py-1 text-xs text-brand-500">已选入口:{ENTRIES.find(item => item.key === entry)?.title}<button type="button" aria-label="清除所选入口" onClick={() => setParams({})} className="hover:text-bad-500"><X size={12} /></button></div>}
<div className="flex items-end gap-2">
<textarea
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); ask(input) } }}
rows={1}
placeholder={entry ? ENTRIES.find(e => e.key === entry)?.placeholder : '直接提出研究问题,如:「调研近一个月智慧水务市场」'}
className="max-h-32 flex-1 resize-none rounded-ctrl border border-line-soft px-3.5 py-2.5 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10 scrollbar-thin"
/>
<PrimaryButton onClick={() => ask(input)} disabled={!input.trim() || busy} className="!rounded-full !p-3">
{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
</PrimaryButton>
</div>
</div>
<textarea aria-label="研究问题" value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); void start() } }} rows={1} maxLength={entry === 'project' ? 2000 : 128} placeholder={ENTRIES.find(item => item.key === entry)?.placeholder || '直接提出研究问题,如:「调研近一个月智慧水务市场」'} className="max-h-32 flex-1 resize-none rounded-ctrl border border-line-soft px-3.5 py-2.5 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10 scrollbar-thin" />
<PrimaryButton type="submit" aria-label="发送" disabled={busy || (!input.trim() && !fileId)} className="!rounded-full !p-3">{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}</PrimaryButton>
</div>
</form></div>}
</div>
</div>
)
}
import { useEffect, useRef, useState } from 'react'
import { api } from '../lib/api'
import { useTaskEvents } from '../hooks/useTaskEvents'
import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton'
const OPERATIONS = [
['ZLBX_BALANCE', '知了账户余额'], ['BID_SEARCH', '知了公告检索(近 90 天全国,最多 3 条)'],
['BID_DETAIL', '知了公告详情(填写公告 ID)'], ['COMPANY_SEARCH', '知了企业主体搜索'],
['COMPANY_PROFILE', '知了企业画像(必须确认主体)'], ['MODEL_TEXT', 'DeepSeek 文本'],
['MODEL_JSON', 'DeepSeek 结构化 JSON'], ['MODEL_STREAM', 'DeepSeek 真实流式'],
['WEB_SEARCH', 'DeepSeek 联网搜索'], ['WEB_FETCH', 'DeepSeek 公开网页抓取'], ['VISION', 'DeepSeek 无敏感信息样图识别'],
] as const
const STATE_LABEL: Record<string, string> = {
RECEIVED: '已接收', PLANNING: '计划中', RUNNING: '执行中', SUCCEEDED: '单项完成', PARTIAL: '部分完成 / 中断',
FAILED: '失败', CANCELLED: '已取消', WAITING_INPUT: '等待补充配置或输入', WAITING_ENTITY: '等待确认主体', WAITING_BUDGET: '等待预算处理',
}
const EVENT_LABEL: Record<string, string> = { RECEIVED: '接收', STATE: '状态', TOOL_START: '实际请求开始', TOOL_COMPLETE: '实际请求完成', TOOL_FAILED: '实际请求失败', REPORT_FRAGMENT: '模型片段' }
/** D1 独立验证面板:每个按钮对应单个真实请求;没有凭证时明确等待,不输出演示报告。 */
export function ServiceCheckPage() {
const [ledger, setLedger] = useState<unknown>(null)
const [operation, setOperation] = useState<string>('ZLBX_BALANCE')
const [input, setInput] = useState('')
const [confirmed, setConfirmed] = useState(false)
const [taskId, setTaskId] = useState<string | null>(null)
const [history, setHistory] = useState<string[]>([])
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [limits, setLimits] = useState<Record<string, number>>({})
// 网络结果未知时保留同一幂等键;只在内容改变或成功拿到任务 ID 后更换。
const pending = useRef<{ signature: string; key: string } | null>(null)
const { events, task, error: streamError } = useTaskEvents(taskId)
useEffect(() => {
void api<string[]>('/agent/tasks').then(setHistory).catch(error => setError(error.message))
void api<Record<string, number>>('/system/limits').then(setLimits).catch(error => setError(error.message))
}, [])
const start = async () => {
if (busy) return
const request = { operation, workflow: operation.startsWith('COMPANY_') ? 'COMPANY_INTEL' : 'TENDER_SEARCH',
input, entityConfirmed: confirmed, maxCalls: Math.min(limits.maxCalls ?? 1, 1), maxCostUnits: Math.min(limits.maxCostUnits ?? 1, 1) }
const signature = JSON.stringify(request)
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
setBusy(true); setError('')
try {
const created = await api<{ id: string }>('/agent/tasks', { method: 'POST', body: signature, headers: { 'Idempotency-Key': pending.current.key } })
setTaskId(created.id); setHistory(ids => [created.id, ...ids.filter(id => id !== created.id)])
pending.current = null
} catch (error) { setError(error instanceof Error ? error.message : '任务创建失败') }
finally { setBusy(false) }
}
const cancel = async () => {
if (!taskId) return
setBusy(true)
try {
await api(`/agent/tasks/${taskId}/cancel`, { method: 'POST' })
// 重新挂载事件订阅,以回放取消状态和仍可能到达的实际用量。
setTaskId(null); setTimeout(() => setTaskId(taskId), 0)
} catch (error) { setError(error instanceof Error ? error.message : '取消失败') }
finally { setBusy(false) }
}
const resume = async () => {
if (!task) return
const request = { ...task.request, input: input || task.request.input,
entityConfirmed: confirmed || task.request.entityConfirmed,
maxCalls: task.status === 'WAITING_BUDGET' ? Math.min(limits.maxCalls ?? 1, task.calls.length + 1) : task.request.maxCalls }
const signature = `${task.id}:${JSON.stringify(request)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
setBusy(true); setError('')
try {
await api(`/agent/tasks/${task.id}/continue`, { method: 'POST', body: JSON.stringify(request), headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null
setTaskId(null); setTimeout(() => setTaskId(task.id), 0)
} catch (error) { setError(error instanceof Error ? error.message : '继续失败') }
finally { setBusy(false) }
}
return <div className="mx-auto max-w-5xl space-y-4 p-5">
<h1 className="text-lg font-bold">服务验证与用量核对</h1>
<details className="rounded-card border bg-white p-4 text-sm"><summary>本账号实际调用账本(只读,不查询供应商余额)</summary><GhostButton onClick={() => { void api('/usage').then(setLedger).catch(e => setError(e.message)) }}>读取 / 刷新本地用量</GhostButton>{ledger != null && <pre className="mt-2 overflow-auto whitespace-pre-wrap text-xs">{JSON.stringify(ledger, null, 2)}</pre>}</details>
<p className="text-sm text-ink-600">逐项核对知了与 DeepSeek 能力。每次创建最多发出一个请求,可能消耗供应商积分或 token。缺少密钥时显示等待配置。</p>
<div className="space-y-3 rounded-card border bg-white p-4">
<label className="block text-sm">验证能力<select value={operation} onChange={e => { setOperation(e.target.value); setConfirmed(false) }} className="mt-1 block w-full rounded border p-2">
{OPERATIONS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select></label>
{!['ZLBX_BALANCE', 'VISION'].includes(operation) && <label className="block text-sm">关键词、完整企业名称、公告 ID 或公开 URL
<textarea value={input} onChange={e => setInput(e.target.value)} maxLength={2000} rows={2} className="mt-1 block w-full rounded border p-2" />
</label>}
{operation === 'COMPANY_PROFILE' && <label className="flex gap-2 text-sm"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />已通过主体搜索核对全称或 ID,不合并集团分支</label>}
<p className="text-xs text-ink-400">费用单价尚待账号核实,首个请求可能超过设置的积分保护值;不会自动重试。视觉只发送后端生成的“D1 8240”样图。</p>
<PrimaryButton onClick={() => void start()} disabled={busy} loading={busy}>创建验证任务</PrimaryButton>
</div>
{(error || streamError) && <div role="alert" className="text-sm text-red-700">{error || streamError}</div>}
{history.length > 0 && <label className="block text-sm">回查最近任务<select value={taskId ?? ''} onChange={e => setTaskId(e.target.value || null)} className="ml-3 max-w-full rounded border p-2">
<option value="">选择任务</option>{history.map(id => <option key={id} value={id}>{id}</option>)}
</select></label>}
{task && <section className="space-y-3 rounded-card border bg-white p-4">
<div className="flex flex-wrap items-center gap-3"><strong>{STATE_LABEL[task.status] ?? task.status}</strong><code className="text-xs">{task.id}</code>
{!['SUCCEEDED', 'FAILED', 'CANCELLED', 'PARTIAL'].includes(task.status) && <GhostButton disabled={busy} onClick={() => void cancel()}>取消任务</GhostButton>}
</div>
<p className="text-sm">{task.question}</p>
{task.status.startsWith('WAITING_') && <div className="space-y-2">
{task.status === 'WAITING_BUDGET' && <p className="text-xs text-ink-600">请先核对供应商余额。继续后允许累计最多 {Math.min(limits.maxCalls ?? 1, task.calls.length + 1)} 次实际请求,仍受部署预算限制。</p>}
<label className="block text-sm">补充该任务输入<textarea value={input} onChange={e => setInput(e.target.value)} className="mt-1 block w-full rounded border p-2" /></label>
{task.operation === 'COMPANY_PROFILE' && <label className="flex gap-2 text-sm"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />已核对并确认企业主体</label>}
<GhostButton disabled={busy} onClick={() => void resume()}>已补充配置或信息,继续此任务</GhostButton>
</div>}
<ol className="space-y-2 text-sm" aria-label="真实任务事件">{events.map(event => <li key={event.id}>
<span className="mr-2 text-ink-400">#{event.id} {EVENT_LABEL[event.type] ?? event.type}</span>{event.payload.message ?? event.payload.text}
</li>)}</ol>
<div className="overflow-x-auto"><table className="w-full text-left text-xs"><thead><tr>{['工具', '状态', '积分', '输入 token', '输出 token', '实际模型', '耗时 ms'].map(label => <th className="p-2" key={label}>{label}</th>)}</tr></thead>
<tbody>{task.calls.map(call => <tr key={String(call.id)}>{['tool_name', 'status', 'cost_units', 'input_tokens', 'output_tokens', 'actual_model', 'duration_ms'].map(field => <td className="p-2" key={field}>{call[field] == null ? '待核对' : String(call[field])}</td>)}</tr>)}</tbody>
</table></div>
{task.calls.length === 0 && <p className="text-xs text-ink-400">尚未发生实际外部请求。</p>}
{task.result != null && <details><summary className="cursor-pointer text-sm">查看实际响应</summary><pre className="mt-2 max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">{JSON.stringify(task.result, null, 2)}</pre></details>}
{task.evidence.length > 0 && <details><summary className="cursor-pointer text-sm">来源与证据</summary><ul className="space-y-2 text-xs">{task.evidence.map(item => <li key={item.id}>{item.excerpt}<br />
{item.url && /^https?:\/\//i.test(item.url) && <a className="underline" href={item.url} target="_blank" rel="noopener noreferrer">查看来源</a>}
</li>)}</ul></details>}
</section>}
</div>
}
import { useMemo, useState } from 'react'
import { Star, ExternalLink, Trash2, ChevronDown, ChevronRight, Sparkles, Plus, X, Link2, Tag, FileUp } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import type { AiPanelState, Project, WatchStatus } from '../types'
import { RESULT_STATUSES } from '../types'
import { useStore, isHistoryStatus, uid, nowStr } from '../lib/store'
import * as Popover from '@radix-ui/react-popover'
import { ProjectTags } from '../components/ProjectTags'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Star, ExternalLink, Trash2, History, Tags, Plus, Sparkles, X } from 'lucide-react'
import { api } from '../lib/api'
import { useStore } from '../lib/store'
import type { WatchItem, Tag } from '../lib/day2'
import { inputClass, message, time, registrationDate } from '../lib/day2'
import { WATCH_STATUS_DESC } from '../types'
import type { WatchStatus } from '../types'
import { AddProjectDialog } from '../components/AddProjectDialog'
import Pill from '../components/ui-ext/Pill'
import { GhostButton, PrimaryButton } from '../components/ui-ext/AiButton'
import { cn } from '@/lib/utils'
import type { AnalysisPanelState } from '../components/AiPanel'
import { PrototypeDialog } from '../components/PrototypeDialog'
import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton'
export function WatchPage({ onOpenPanel }: { onOpenPanel: (s: AiPanelState) => void }) {
const {
watch, setWatchStatus, setWatchNote, removeWatch,
customTags, addCustomTag, removeCustomTag, toggleWatchTag, addCustomProject, findProject,
} = useStore()
const [tab, setTab] = useState<'active' | 'result' | 'skipped'>('active')
const [confirmRemove, setConfirmRemove] = useState<string | null>(null)
const [openHistory, setOpenHistory] = useState<string | null>(null)
const [tagFilter, setTagFilter] = useState<string | null>(null)
const [tagEditorFor, setTagEditorFor] = useState<string | null>(null)
const [newTag, setNewTag] = useState('')
const [showAddLink, setShowAddLink] = useState(false)
const [linkForm, setLinkForm] = useState({ url: '', name: '', purchaser: '', region: '', budget: '' })
const [linkFile, setLinkFile] = useState('')
const [linkError, setLinkError] = useState('')
// 状态变更弹窗:避免一排按钮诱导频繁点击,历史记录保持干净;备注随状态一起设置
const [statusModalFor, setStatusModalFor] = useState<string | null>(null)
const [pendingStatus, setPendingStatus] = useState<WatchStatus>('已关注')
const [pendingNote, setPendingNote] = useState('')
const active = useMemo(() => watch.filter(w => !isHistoryStatus(w.status)), [watch])
const result = useMemo(() => watch.filter(w => (RESULT_STATUSES as string[]).includes(w.status)), [watch])
const skipped = useMemo(() => watch.filter(w => w.status === '暂不考虑'), [watch])
const list = (tab === 'active' ? active : tab === 'result' ? result : skipped).filter(w => !tagFilter || w.tags.includes(tagFilter))
const submitLink = () => {
const url = linkForm.url.trim()
const name = linkForm.name.trim()
if (!url && !linkFile) { setLinkError('请填写公告网址或上传公告文件'); return }
if (url && !/^https?:\/\//i.test(url)) { setLinkError('网址需以 http:// 或 https:// 开头'); return }
if (!name) { setLinkError('请填写项目名称'); return }
const budgetNum = linkForm.budget.trim() === '' ? null : Number(linkForm.budget)
if (linkForm.budget.trim() !== '' && (Number.isNaN(budgetNum) || (budgetNum as number) < 0)) { setLinkError('预算需为数字(万元)'); return }
const p: Project = {
id: uid('custom'),
name,
region: linkForm.region.trim() || '未填写',
keywords: [],
budget: budgetNum,
publishDate: nowStr().slice(0, 10),
regDeadline: null,
bidDeadline: null,
purchaser: linkForm.purchaser.trim() || '待确认(详见公告原文)',
noticeType: '手动添加',
sourceName: linkFile ? '上传公告文件' : '手动添加链接',
sourceUrl: url || null,
summary: '手动添加的项目,可通过「向AI提问」进一步了解。',
detail: `该项目由用户手动添加。\n${url ? `公告链接:${url}\n` : ''}${linkFile ? `公告文件:${linkFile}\n` : ''}地区、预算与截止时间等信息以公告原文为准。`,
requirements: [],
/** 所有操作先提交服务端,成功后回读;没有本地假成功或截止日期驱动的自动状态跳转。 */
export function WatchPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPanelState) => void }) {
const { refreshWatch, removeWatch } = useStore()
const [showAdd, setShowAdd] = useState(false)
const [rows, setRows] = useState<WatchItem[]>([])
const [tags, setTags] = useState<Tag[]>([])
const [group, setGroup] = useState('跟进中')
const [tagFilter, setTagFilter] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [loading, setLoading] = useState(true)
const [editing, setEditing] = useState<{ row: WatchItem; noteOnly: boolean } | null>(null)
const [status, setStatus] = useState<WatchStatus>('已关注')
const [note, setNote] = useState('')
const [remove, setRemove] = useState<WatchItem | null>(null)
const [tagFor, setTagFor] = useState<string | null>(null)
const pending = useRef<{ fingerprint: string; key: string } | null>(null)
// 相同编辑保留同一命令键,网络结果不确定时重试不会重复写入历史。
const commandKey = (value: unknown) => {
const fingerprint = JSON.stringify(value)
if (pending.current?.fingerprint !== fingerprint) pending.current = { fingerprint, key: crypto.randomUUID() }
return pending.current.key
}
addCustomProject(p)
setShowAddLink(false)
setLinkForm({ url: '', name: '', purchaser: '', region: '', budget: '' })
setLinkFile('')
setLinkError('')
const reload = useCallback(async () => {
const [watch, savedTags] = await Promise.all([api<WatchItem[]>('/watch'), api<Tag[]>('/tags')])
setRows(watch); setTags(savedTags); await refreshWatch()
}, [refreshWatch])
useEffect(() => { let active = true; void reload().catch(e => { if (active) setError(message(e)) }).finally(() => { if (active) setLoading(false) }); return () => { active = false } }, [reload])
const action = async (run: () => Promise<void>) => {
if (busy) return
setBusy(true); setError('')
try { await run() } catch (e) { setError(message(e)); await reload().catch(() => {}) } finally { setBusy(false) }
}
const filtered = rows.filter(row => row.group === group && (!tagFilter || row.tags.includes(tagFilter)))
const openEdit = (row: WatchItem, noteOnly = false) => { setEditing({ row, noteOnly }); setStatus(row.status); setNote(row.note); pending.current = null }
const closeModal = () => { if (busy) return; setEditing(null); setRemove(null) }
const modal = editing || remove
return (
<div className="mx-auto max-w-[1000px] px-4 py-4 sm:px-5 sm:py-5 xl:px-6">
<div className="flex items-center gap-3">
<Star size={18} className="text-brand-500" />
<h1 className="text-[17px] font-bold">重点关注</h1>
<span className="flex-1" />
<GhostButton onClick={() => {
setLinkForm({ url: '', name: '', purchaser: '', region: '', budget: '' })
setLinkFile('')
setLinkError('')
setShowAddLink(true)
}} className="!px-3 !py-1.5 text-xs">
<Plus size={14} /> 添加项目
</GhostButton>
</div>
{/* 页签:胶囊切换(跟进中 / 已有结果 / 暂不考虑) */}
<div className="mt-4 inline-flex rounded-full border border-line-soft bg-white p-1 shadow-card">
<button onClick={() => setTab('active')}
className={cn('rounded-full px-4 py-1.5 text-[13px] font-medium transition-colors',
tab === 'active' ? 'bg-brand-500 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]' : 'text-ink-600 hover:text-brand-500')}>
跟进中 <span className="font-num">({active.length})</span>
</button>
<button onClick={() => setTab('result')}
className={cn('rounded-full px-4 py-1.5 text-[13px] font-medium transition-colors',
tab === 'result' ? 'bg-brand-500 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]' : 'text-ink-600 hover:text-brand-500')}>
已有结果 <span className="font-num">({result.length})</span>
</button>
<button onClick={() => setTab('skipped')}
className={cn('rounded-full px-4 py-1.5 text-[13px] font-medium transition-colors',
tab === 'skipped' ? 'bg-brand-500 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]' : 'text-ink-600 hover:text-brand-500')}>
暂不考虑 <span className="font-num">({skipped.length})</span>
</button>
</div>
{/* 自定义标签筛选:在卡片上给项目打标签后可按标签分类查看 */}
{customTags.length > 0 && (
<div className="mt-3 flex flex-wrap items-center gap-1.5">
<Tag size={13} className="text-ink-400" />
<button onClick={() => setTagFilter(null)}
className={cn('rounded-full border px-2.5 py-1 text-[12px] transition-colors',
tagFilter === null ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600 hover:border-brand-500/40 hover:text-brand-500')}>
全部
</button>
{customTags.map(t => (
<span key={t}
className={cn('inline-flex items-center rounded-full border text-[12px] transition-colors',
tagFilter === t ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600 hover:border-brand-500/40 hover:text-brand-500')}>
<button onClick={() => setTagFilter(tagFilter === t ? null : t)} className="py-1 pl-2.5 pr-1">
{t}
</button>
<button onClick={() => { removeCustomTag(t); if (tagFilter === t) setTagFilter(null) }}
title={`删除标签「${t}」(同时从各项目移除)`}
className="py-1 pl-0.5 pr-2 text-ink-400 hover:text-bad-500" aria-label={`删除标签 ${t}`}>
<X size={11} />
</button>
</span>
))}
{tagFilter && <span className="text-xs text-ink-400">筛选中:{tagFilter}(再点一次取消)</span>}
</div>
)}
{list.length === 0 ? (
<section className="mt-4 rounded-card border border-dashed border-line-soft bg-white py-16 text-center shadow-card">
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-brand-50">
<Star size={24} className="text-brand-500" />
</div>
<p className="mt-4 text-sm text-ink-400">
{tab === 'active'
? '暂无跟进中的项目。在「发现商机」检索结果中点击 ☆ 加入重点关注。'
: tab === 'result'
? '暂无已有结果的项目。中标 / 未中标 / 流标的项目会保留在这里。'
: '暂无暂不考虑的项目。我方主动放弃跟进的项目会保留在这里,可随时转回跟进。'}
</p>
</section>
) : (
<ul className="mt-4 space-y-3">
{list.map(w => {
const p = findProject(w.projectId)
if (!p) return null
return (
<li key={w.projectId} className="rounded-card border border-line-soft bg-white p-5 shadow-card transition-shadow hover:shadow-card-hover fade-up">
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-[15px] font-semibold text-ink-900">{p.name}</span>
<span className="rounded-full bg-[#F4F7FB] px-2 py-0.5 text-[11px] text-ink-600">{p.region}</span>
<span className="rounded-full bg-[#F4F7FB] px-2 py-0.5 text-[11px] text-ink-600">
{p.budget === null ? '预算未披露' : <span className="font-num">{p.budget.toLocaleString()} 万元</span>}
</span>
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs text-ink-400">
<span>发布 <span className="font-num">{p.publishDate}</span> · 报名截止 <span className="font-num">{p.regDeadline ?? '未披露'}</span></span>
{/* 自定义标签:跟在报名截止右侧,不单独占行 */}
<span className="relative flex flex-wrap items-center gap-1.5">
{w.tags.map(t => (
<span key={t} className="inline-flex items-center gap-1 rounded-full bg-brand-50 px-2 py-0.5 text-[11px] text-brand-500">
{t}
<button onClick={() => toggleWatchTag(w.projectId, t)} className="text-brand-500/60 hover:text-brand-500" aria-label={`移除标签 ${t}`}>
<X size={10} />
</button>
</span>
))}
<button onClick={() => { setTagEditorFor(tagEditorFor === w.projectId ? null : w.projectId); setNewTag('') }}
className="inline-flex items-center gap-0.5 rounded-full border border-dashed border-line-soft px-2 py-0.5 text-[11px] text-ink-400 transition-colors hover:border-brand-500/40 hover:text-brand-500">
<Plus size={10} /> 标签
</button>
{tagEditorFor === w.projectId && (
<div className="absolute left-0 top-full z-20 mt-1 w-56 rounded-card border border-line-soft bg-white p-3 shadow-card-hover fade-up">
<div className="text-xs font-medium text-ink-900">选择或新建标签</div>
<div className="mt-1.5 flex flex-wrap gap-1">
{customTags.length === 0 && <span className="text-[11px] text-ink-400">还没有标签,先在下方新建一个</span>}
{customTags.map(t => {
const on = w.tags.includes(t)
return (
<span key={t}
className={cn('inline-flex items-center rounded-full border text-[11px] transition-colors',
on ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600 hover:border-brand-500/40 hover:text-brand-500')}>
<button onClick={() => toggleWatchTag(w.projectId, t)} className="py-0.5 pl-2 pr-0.5">{t}</button>
<button onClick={() => removeCustomTag(t)} title={`删除标签「${t}」`}
className="py-0.5 pl-0.5 pr-1.5 text-ink-400 hover:text-bad-500" aria-label={`删除标签 ${t}`}>
<X size={9} />
</button>
</span>
)
})}
</div>
<div className="mt-2 flex items-center gap-1.5">
<input value={newTag} onChange={e => setNewTag(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter' && newTag.trim()) {
addCustomTag(newTag.trim())
if (!w.tags.includes(newTag.trim())) toggleWatchTag(w.projectId, newTag.trim())
setNewTag('')
}
}}
placeholder="新标签名,回车创建"
className="w-full rounded-ctrl border border-line-soft px-2 py-1 text-[12px] outline-none placeholder:text-ink-400 focus:border-brand-500/60" />
</div>
</div>
)}
</span>
</div>
<div className="mt-1 text-[13px] text-ink-600">{p.summary}</div>
</div>
<div className="flex shrink-0 flex-col items-end gap-1.5">
{p.sourceUrl && (
<a href={p.sourceUrl} target="_blank" rel="noreferrer"
className="inline-flex items-center gap-1 rounded-ctrl border border-line-soft bg-white px-3 py-1.5 text-xs font-medium text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500">
<ExternalLink size={12} /> 公告原文
</a>
)}
<button onClick={() => onOpenPanel({ kind: 'project', projectId: p.id })}
className="inline-flex items-center gap-1 rounded-ctrl border-brand-gradient px-3 py-1.5 text-xs font-medium shadow-card transition-shadow hover:shadow-card-hover">
<Sparkles size={12} className="text-brand-500" /><span className="text-brand-gradient">向AI提问</span>
</button>
</div>
</div>
{/* 状态:通过弹窗单独设置,避免误点与频繁变更历史 */}
<div className="mt-3.5 flex flex-wrap items-center gap-2">
<span className="text-[13px] text-ink-400">当前状态:</span>
<Pill status={w.status} />
<button onClick={() => {
setStatusModalFor(w.projectId)
setPendingStatus(w.status)
setPendingNote(w.note)
}}
className="rounded-full border border-line-soft px-2.5 py-1 text-[12px] text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500">
变更状态
</button>
<span className="flex-1" />
<button onClick={() => setConfirmRemove(w.projectId)}
className="inline-flex items-center gap-1 text-xs text-bad-500 hover:underline">
<Trash2 size={12} /> 取消关注
</button>
</div>
{/* 备注:填写过才展示;填写与修改统一在「变更状态」弹窗里进行 */}
{w.note && (
<div className="mt-3 rounded-ctrl border border-line-soft bg-canvas px-3 py-2 text-[13px] leading-relaxed text-ink-600">
{w.note}
</div>
)}
<div className="mt-2">
<button onClick={() => setOpenHistory(openHistory === w.projectId ? null : w.projectId)}
className="inline-flex items-center gap-1 text-xs text-ink-400 hover:text-brand-500">
{openHistory === w.projectId ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
状态变更历史(<span className="font-num">{w.history.length}</span> 次)· 关注于 <span className="font-num">{w.createdAt}</span>
</button>
{openHistory === w.projectId && (
<ul className="ml-2 mt-1.5 space-y-1.5 border-l-2 border-line-soft pl-3 text-xs text-ink-400 fade-up">
{[...w.history].reverse().map((h, i) => (
<li key={i}>
<b className="text-ink-900">{h.status}</b> · <span className="font-num">{h.time}</span>
{h.note && <div className="mt-0.5 text-ink-600">当时备注:{h.note}</div>}
</li>
))}
</ul>
)}
</div>
</li>
)
})}
</ul>
)}
<AnimatePresence>
{confirmRemove && (
<motion.div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-900/20 backdrop-blur-sm"
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}
onClick={e => { if (e.target === e.currentTarget) setConfirmRemove(null) }}>
<motion.div className="relative w-[380px] rounded-card border border-line-soft bg-white p-5 text-center shadow-card-hover"
initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }} transition={{ duration: 0.18 }}>
<button onClick={() => setConfirmRemove(null)} aria-label="关闭"
className="absolute right-3 top-3 rounded-full p-1.5 text-ink-400 transition-colors hover:bg-[#F4F7FB]"><X size={15} /></button>
<div className="mx-auto flex h-10 w-10 items-center justify-center rounded-full bg-bad-500/10 text-lg font-bold text-bad-500">!</div>
<h3 className="mt-2 font-bold">取消关注这个项目?</h3>
<p className="mt-1.5 text-[13px] leading-relaxed text-ink-400">
将移除该项目的状态、备注与全部历史。<br />
暂时不跟进,可改设为「暂不考虑」。
</p>
<div className="mt-4 flex justify-center gap-2">
<GhostButton onClick={() => setConfirmRemove(null)}>再想想</GhostButton>
<PrimaryButton onClick={() => { removeWatch(confirmRemove); setConfirmRemove(null) }}
className="!bg-bad-500 hover:!bg-bad-500/90 !shadow-[0_2px_8px_rgba(244,63,94,.25)]">确认取消关注</PrimaryButton>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<AnimatePresence>
{showAddLink && (
<motion.div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-900/20 backdrop-blur-sm"
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}
onClick={e => { if (e.target === e.currentTarget) setShowAddLink(false) }}>
<motion.div className="w-[420px] rounded-card border border-line-soft bg-white p-5 shadow-card-hover"
initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }} transition={{ duration: 0.18 }}>
<div className="flex items-center gap-2">
<Link2 size={15} className="text-brand-500" />
<h3 className="font-bold">添加项目</h3>
<span className="flex-1" />
<button onClick={() => setShowAddLink(false)} aria-label="关闭"
className="rounded-full p-1.5 text-ink-400 transition-colors hover:bg-[#F4F7FB]"><X size={16} /></button>
</div>
<p className="mt-1 text-[13px] leading-relaxed text-ink-400">
粘贴公告网址,或直接上传公告文件(PDF / Word / 图片)。<br />
AI 会提取项目信息,加入后即可提问、跟进与打标签。
</p>
<div className="mt-3 space-y-2.5">
<div>
<label className="text-[13px] font-medium text-ink-900">公告网址 <span className="text-xs font-normal text-ink-400">选填</span></label>
<input value={linkForm.url} onChange={e => { setLinkForm(f => ({ ...f, url: e.target.value })); setLinkError('') }}
placeholder="https://…"
className="mt-1 w-full rounded-ctrl border border-line-soft px-3 py-2 text-[13px] outline-none placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
<div>
<label className="text-[13px] font-medium text-ink-900">公告文件 <span className="text-xs font-normal text-ink-400">选填,与网址二选一</span></label>
{linkFile ? (
<div className="mt-1 flex items-center gap-2 rounded-ctrl border border-brand-500/30 bg-brand-50 px-3 py-2 text-[13px] text-ink-900">
<FileUp size={14} className="shrink-0 text-brand-500" />
<span className="min-w-0 flex-1 truncate">{linkFile}</span>
<button onClick={() => setLinkFile('')} className="shrink-0 rounded-full p-0.5 text-ink-400 hover:text-bad-500" aria-label="移除文件">
<X size={13} />
</button>
</div>
) : (
<label className="mt-1 flex cursor-pointer items-center justify-center gap-1.5 rounded-ctrl border border-dashed border-line-soft px-3 py-2.5 text-[13px] text-ink-400 transition-colors hover:border-brand-500/40 hover:text-brand-500">
<FileUp size={14} /> 上传公告文件,AI 自动提取项目信息
<input type="file" accept=".pdf,.doc,.docx,.txt,.md,.png,.jpg,.jpeg" className="hidden"
onChange={e => {
const f = e.target.files?.[0]
if (!f) return
setLinkFile(f.name)
setLinkError('')
// 按文件名预填项目名称,用户可改
setLinkForm(prev => prev.name ? prev : { ...prev, name: f.name.replace(/\.[^.]+$/, '') })
e.target.value = ''
}} />
</label>
)}
</div>
<div>
<label className="text-[13px] font-medium text-ink-900">项目名称 <span className="text-warn-500">*</span></label>
<input value={linkForm.name} onChange={e => { setLinkForm(f => ({ ...f, name: e.target.value })); setLinkError('') }}
placeholder="按公告标题填写"
className="mt-1 w-full rounded-ctrl border border-line-soft px-3 py-2 text-[13px] outline-none placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
<div className="grid grid-cols-3 gap-2">
<div>
<label className="text-[13px] font-medium text-ink-900">招标方</label>
<input value={linkForm.purchaser} onChange={e => setLinkForm(f => ({ ...f, purchaser: e.target.value }))}
placeholder="选填"
className="mt-1 w-full rounded-ctrl border border-line-soft px-3 py-2 text-[13px] outline-none placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
<div>
<label className="text-[13px] font-medium text-ink-900">地区</label>
<input value={linkForm.region} onChange={e => setLinkForm(f => ({ ...f, region: e.target.value }))}
placeholder="选填"
className="mt-1 w-full rounded-ctrl border border-line-soft px-3 py-2 text-[13px] outline-none placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
<div>
<label className="text-[13px] font-medium text-ink-900">预算(万元)</label>
<input type="number" min={0} value={linkForm.budget} onChange={e => { setLinkForm(f => ({ ...f, budget: e.target.value })); setLinkError('') }}
placeholder="选填"
className="mt-1 w-full rounded-ctrl border border-line-soft px-3 py-2 text-[13px] font-num outline-none placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div>
</div>
{linkError && <div className="text-xs text-bad-500">{linkError}</div>}
</div>
<div className="mt-4 flex justify-end gap-2">
<GhostButton onClick={() => setShowAddLink(false)}>取消</GhostButton>
<PrimaryButton onClick={submitLink}>添加并关注</PrimaryButton>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
{/* 状态变更弹窗 */}
<AnimatePresence>
{statusModalFor && (
<motion.div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-900/20 backdrop-blur-sm"
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}
onClick={e => { if (e.target === e.currentTarget) setStatusModalFor(null) }}>
<motion.div className="max-h-[85vh] w-[460px] max-w-[92vw] overflow-y-auto rounded-card border border-line-soft bg-white p-5 shadow-card-hover scrollbar-thin"
initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }} transition={{ duration: 0.18 }}>
<div className="flex items-center justify-between">
<h3 className="font-bold">变更跟进状态</h3>
<button onClick={() => setStatusModalFor(null)} aria-label="关闭"
className="rounded-full p-1.5 text-ink-400 transition-colors hover:bg-[#F4F7FB]"><X size={16} /></button>
</div>
<p className="mt-1 text-[13px] text-ink-400">选择新状态后可顺手更新备注,变更与备注会一起记入状态历史。</p>
<div className="mt-3 space-y-2.5">
{([
return <div className="mx-auto max-w-[1000px] px-4 py-4 sm:px-5 sm:py-5 xl:px-6">
<div className="flex items-center gap-3"><Star size={18} className="text-brand-500" /><h1 className="text-[17px] font-bold">重点关注</h1><span className="flex-1" /><GhostButton onClick={() => setShowAdd(true)} className="!px-3 !py-1.5 text-xs"><Plus size={14} /> 添加项目</GhostButton></div>
{error && <div role="alert" className="mt-3 rounded-ctrl bg-red-50 p-3 text-sm text-red-700">{error}</div>}
{/* 原型胶囊分组只按状态与标签筛选,不增加独立搜索入口。 */}
<div className="mt-4 inline-flex max-w-full overflow-x-auto rounded-full border border-line-soft bg-white p-1 shadow-card">{['跟进中', '已有结果', '暂不考虑'].map(name => <button key={name} aria-pressed={group === name} onClick={() => setGroup(name)} className={`shrink-0 rounded-full px-4 py-1.5 text-[13px] font-medium transition-colors ${group === name ? 'bg-brand-500 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]' : 'text-ink-600 hover:text-brand-500'}`}>{name} <span className="font-num">({rows.filter(row => row.group === name).length})</span></button>)}</div>
{!!tags.length && <div className="mt-3 flex flex-wrap items-center gap-1.5"><Tags size={13} className="text-ink-400" /><button onClick={() => setTagFilter('')} className={`rounded-full border px-2.5 py-1 text-[12px] ${!tagFilter ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600'}`}>全部</button>{tags.map(tag => <span key={tag.id} className={`inline-flex items-center rounded-full border text-[12px] ${tagFilter === tag.name ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600'}`}><button onClick={() => setTagFilter(tagFilter === tag.name ? '' : tag.name)} className="py-1 pl-2.5 pr-1">{tag.name}</button><button disabled={busy} aria-label={`删除标签${tag.name}`} onClick={() => void action(async () => { await api(`/tags/${tag.id}`, { method: 'DELETE' }); if (tagFilter === tag.name) setTagFilter(''); await reload() })} className="py-1 pl-0.5 pr-2 text-ink-400 hover:text-bad-500"><X size={11} /></button></span>)}</div>}
{loading && <p role="status" className="p-8 text-center text-sm text-ink-400">正在读取关注…</p>}
{!loading && !filtered.length && <section className="mt-4 rounded-card border border-dashed border-line-soft bg-white py-16 text-center shadow-card"><div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-brand-50"><Star size={24} className="text-brand-500" /></div><p className="mt-4 px-4 text-sm text-ink-400">{tagFilter ? '暂无符合筛选条件的项目。' : group === '跟进中' ? '暂无跟进中的项目。在「发现商机」检索结果中点击 ☆ 加入重点关注。' : group === '已有结果' ? '暂无已有结果的项目。中标 / 未中标 / 流标的项目会保留在这里。' : '暂无暂不考虑的项目。我方主动放弃跟进的项目会保留在这里,可随时转回跟进。'}</p></section>}
<ul className="mt-4 space-y-3">{filtered.map(row => <li key={row.projectId} className="rounded-card border border-line-soft bg-white p-5 shadow-card transition-shadow hover:shadow-card-hover fade-up">
<div className="flex items-start gap-3"><div className="min-w-0 flex-1"><div className="flex flex-wrap items-center gap-2"><h3 className="text-[15px] font-semibold">{row.project.title || '标题待核验'}</h3><span className="rounded-full bg-[#F4F7FB] px-2 py-0.5 text-[11px] text-ink-600">{row.project.region || '地区待核验'}</span><span className="rounded-full bg-[#F4F7FB] px-2 py-0.5 text-[11px] text-ink-600">{row.project.budgetWan == null ? '预算未披露' : `${row.project.budgetWan.toLocaleString()} 万元`}</span></div><div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs text-ink-400"><span>发布 <span className="font-num">{row.project.publishDate || '未披露'}</span> · <span className="font-num">报名截止 {registrationDate(row.summary?.schedule) ?? '未披露'}</span></span><span className="flex flex-wrap items-center gap-1.5">{row.tags.map(tag => <span key={tag} className="inline-flex items-center gap-1 rounded-full bg-brand-50 px-2 py-0.5 text-[11px] text-brand-500">{tag}<button aria-label={`移除标签 ${tag}`} onClick={() => void action(async () => { const body = { tags: row.tags.filter(name => name !== tag), version: row.version }; await api(`/watch/${row.projectId}/tags`, { method: 'PUT', headers: { 'Idempotency-Key': commandKey({ project: row.projectId, ...body }) }, body: JSON.stringify(body) }); pending.current = null; await reload() })} className="text-brand-500/60 hover:text-brand-500"><X size={10} /></button></span>)}<Popover.Root open={tagFor === row.projectId} onOpenChange={open => setTagFor(open ? row.projectId : null)}><Popover.Trigger asChild><button className="inline-flex items-center gap-0.5 rounded-full border border-dashed border-line-soft px-2 py-0.5 text-[11px] text-ink-400 hover:border-brand-500/40 hover:text-brand-500"><Plus size={10} /> 标签</button></Popover.Trigger><Popover.Portal><Popover.Content align="start" sideOffset={4} className="z-50"><ProjectTags projectId={row.projectId} showDone={false} onClose={() => setTagFor(null)} /></Popover.Content></Popover.Portal></Popover.Root></span></div><p className="mt-1 text-[13px] text-ink-600">{row.summary?.construction || row.project.purchaser || '项目内容待公告原文核验'}</p></div><div className="flex shrink-0 flex-col items-end gap-1.5">{row.project.url && <a href={row.project.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 rounded-ctrl border border-line-soft bg-white px-3 py-1.5 text-xs font-medium text-ink-600 hover:border-brand-500/40 hover:text-brand-500"><ExternalLink size={12} /> 公告原文</a>}<button onClick={() => onOpenPanel({ kind: 'project', project: { ...row.project, userFileId: row.fileId }, summary: row.summary })} className="inline-flex items-center gap-1 rounded-ctrl border-brand-gradient px-3 py-1.5 text-xs font-medium shadow-card hover:shadow-card-hover"><Sparkles size={12} className="text-brand-500" /><span className="text-brand-gradient">向AI提问</span></button></div></div>
<div className="mt-3.5 flex flex-wrap items-center gap-2"><span className="text-[13px] text-ink-400">当前状态:</span><Pill status={row.status} /><button disabled={busy} onClick={() => openEdit(row)} className="rounded-full border border-line-soft px-2.5 py-1 text-[12px] text-ink-600 hover:border-brand-500/40 hover:text-brand-500">变更状态</button><span className="flex-1" /><button disabled={busy} onClick={() => setRemove(row)} className="inline-flex items-center gap-1 text-xs text-bad-500 hover:underline"><Trash2 size={12} /> 取消关注</button></div>
{/* 原型只在已有备注时展示内容,填写和修改统一通过“变更状态”弹窗完成。 */}
{row.note && <div className="mt-3 rounded-ctrl border border-line-soft bg-canvas px-3 py-2 text-[13px] leading-relaxed text-ink-600">{row.note}</div>}
<details className="mt-2 text-xs text-ink-400"><summary className="flex cursor-pointer items-center gap-1"><History size={12} /> 状态变更历史({row.history.length} 次)· 关注于 {time(row.createdAt)}</summary><ol className="mt-3 space-y-3 border-l-2 border-line-soft pl-4">{[...row.history].reverse().map((entry, i) => <li key={i}><b className="text-ink-900">{entry.status}</b> · {time(entry.time)}{entry.note && <p className="mt-1 whitespace-pre-wrap text-ink-600">当时备注:{entry.note}</p>}</li>)}</ol></details>
</li>)}</ul>
{showAdd && <AddProjectDialog onClose={() => setShowAdd(false)} onAdded={reload} />}
{modal && <PrototypeDialog open onClose={closeModal} title={editing ? '变更跟进状态' : '取消关注这个项目?'} className={editing ? 'w-[460px]' : 'w-[380px] text-center [&>h2]:mt-12 [&>h2]:pr-0'}>
{editing && <><p className="mt-1 text-[13px] text-ink-400">选择新状态后可顺手更新备注,变更与备注会一起记入状态历史。</p><div className="mt-3 space-y-2.5">{([
['跟进中', ['已关注', '准备投标', '已报名', '已提交投标文件']],
['已有结果', ['已中标', '未中标', '已流标']],
['我方决定', ['暂不考虑']],
] as const).map(([group, statuses]) => (
<div key={group}>
<div className="mb-1 text-[11px] font-medium text-ink-400">{group}</div>
<div className="grid grid-cols-2 gap-1.5">
{statuses.map(s => (
<button key={s} onClick={() => setPendingStatus(s)}
className={cn('flex items-center gap-2 rounded-ctrl border px-2.5 py-2 text-left transition-colors',
pendingStatus === s ? 'border-brand-500 bg-brand-50' : 'border-line-soft hover:border-brand-500/40')}>
<span className={cn('h-3 w-3 shrink-0 rounded-full border-2', pendingStatus === s ? 'border-brand-500 bg-brand-500' : 'border-line-soft')} />
<span className={cn('min-w-0 text-[13px] font-medium leading-tight', pendingStatus === s ? 'text-brand-500' : 'text-ink-900')}>{s}</span>
</button>
))}
</div>
</div>
))}
</div>
<textarea
value={pendingNote}
onChange={e => setPendingNote(e.target.value)}
placeholder="备注(可选):为什么变更到这个状态、下一步要做什么…"
rows={2}
className="mt-3 w-full resize-y rounded-ctrl border border-line-soft px-3 py-2 text-[13px] text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10 scrollbar-thin"
/>
<div className="mt-4 flex justify-end gap-2">
<GhostButton onClick={() => setStatusModalFor(null)}>取消</GhostButton>
<PrimaryButton onClick={() => {
// 先保存备注再改状态,状态历史快照记下的就是这条新备注
setWatchNote(statusModalFor, pendingNote)
setWatchStatus(statusModalFor, pendingStatus)
setStatusModalFor(null)
}}>确定</PrimaryButton>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
['已有结果', ['已中标', '未中标', '已流标']], ['我方决定', ['暂不考虑']],
] as const).map(([name, values]) => <div key={name}><div className="mb-1 text-[11px] font-medium text-ink-400">{name}</div><div className="grid grid-cols-2 gap-1.5">{values.map(value => <button key={value} onClick={() => setStatus(value)} aria-pressed={status === value} title={WATCH_STATUS_DESC[value]} className={`flex items-center gap-2 rounded-ctrl border px-2.5 py-2 text-left transition-colors ${status === value ? 'border-brand-500 bg-brand-50' : 'border-line-soft hover:border-brand-500/40'}`}><span className={`h-3 w-3 shrink-0 rounded-full border-2 ${status === value ? 'border-brand-500 bg-brand-500' : 'border-line-soft'}`} /><span className={`min-w-0 text-[13px] font-medium leading-tight ${status === value ? 'text-brand-500' : 'text-ink-900'}`}>{value}</span></button>)}</div></div>)}</div><textarea aria-label="跟进备注" placeholder="备注(可选):为什么变更到这个状态、下一步要做什么…" value={note} onChange={e => setNote(e.target.value)} maxLength={5000} rows={2} className={`${inputClass} mt-3 text-[13px]`} /></>}
{remove && <><div className="absolute left-1/2 top-5 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full bg-bad-500/10 text-lg font-bold text-bad-500">!</div><p className="mt-1.5 text-[13px] leading-relaxed text-ink-400">将移除该项目的状态、备注与全部历史。<br />暂时不跟进,可改设为「暂不考虑」。</p></>}
{error && <p role="alert" className="mt-3 text-sm text-red-600">{error}</p>}
<div className={`mt-4 flex gap-2 ${remove ? 'justify-center' : 'justify-end'}`}><GhostButton disabled={busy} onClick={closeModal}>{remove ? '再想想' : '取消'}</GhostButton><PrimaryButton disabled={busy} className={remove ? '!bg-bad-500 hover:!bg-bad-500/90' : undefined} onClick={() => void action(async () => {
if (editing) {
const body = { status: editing.noteOnly ? null : status, note, version: editing.row.version }
await api(`/watch/${editing.row.projectId}/changes`, { method: 'POST', headers: { 'Idempotency-Key': commandKey({ project: editing.row.projectId, ...body }) }, body: JSON.stringify(body) })
setEditing(null)
} else if (remove) { await removeWatch(remove.projectId); setRemove(null) }
pending.current = null; await reload()
})}>{busy ? '保存中…' : remove ? '确认取消关注' : '确定'}</PrimaryButton></div>
</PrototypeDialog>}
</div>
)
}
......@@ -68,6 +68,7 @@ export interface StatusChange {
}
export interface WatchRecord {
version: number
projectId: string
status: WatchStatus
note: string
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment