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

按照原型还原

parent 12121653
> 2026-10-29:已按 `Downloads/getbusiness` 原型恢复页面结构和主要交互,保留真实后端。逐页对照、验收截图及发布注意事项见 [原型一致性验收](docs/原型一致性验收.md)。新增手动项目保存接口需与前端同步更新后端。
# 如昼商机助手前端
D1–D2 已接入会话登录、手填档案、分页检索与获客报告、平台市场聚合、检索方案快照、八状态关注与标签。发现商机与重点关注只读取后端事实;对话调研继续按 D3 计划接入,仍明确标注原型。真实 MySQL 与供应商联调待配置后验收。
```sh
npm ci
npm run dev
```
默认端口 3000,`/api` 代理到 `http://127.0.0.1:8240`。后端按相邻 `rz-GB/README.md` 配置并启动;前端不需要任何 API Key,也不要配置 `VITE_*_API_KEY`。
- 登录使用预设 `admin` 和后端初始化密码;浏览器只保存 HttpOnly 会话 Cookie,不再认可旧 `rz-authed`。
- 公司档案从服务端加载,保存失败或版本冲突不会显示成功;八组表单支持手填及 TXT / Markdown 本地字段识别,导入需先核对再写入表单,最后显式保存;介绍文件不上传给供应商。
- “服务验证”按单个动作创建任务。缺凭证时等待配置,补充环境并重启后端后可继续;历史任务重放不会重复收费。
- “发现商机”默认全国近 90 天,普通检索按发布时间,获客偏好不删除候选;临时偏好视图不发起外部请求。区域市场分别展示平台聚合与已读样本。
- 方案保存不执行;手动执行使用部署预算上限、保存时的具体日期,并冻结方案/档案版本和有序结果。
- 关注状态与备注一次提交,单独修改备注也留痕;版本冲突拒绝覆盖;取消关注需确认,标签全局删除自动解绑。
- 列表摘要为已有原文规则摘录;缺正文如实提示。右侧 AI 面板展示已有摘要,提交问题才创建问答任务;了解采购方/深入研判进入对应调研表单,显式提交后执行。
- D2 契约、39 项后端测试及浏览器夹具验收见相邻 `rz-GB/docs/D2实施与验收.md`。
- `npm run build` 校验 TypeScript 并打包;`npm run lint` 仍存在原型遗留问题,详见后端 `docs/D1实施与验收.md`。生产部署需要配置同源 `/api` 反向代理和前端路由回退,不能只双击 `dist/index.html`。
以下保留原模板技术说明。
# React + TypeScript + Vite # React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
...@@ -71,3 +96,13 @@ export default defineConfig([ ...@@ -71,3 +96,13 @@ export default defineConfig([
}, },
]) ])
``` ```
## D3 企业与项目调研
对话调研已接入研究客户、研究竞对(单/双公司)、区域市场和投标项目四入口。页面读取后端真实 SSE;主体歧义、预算暂停需显式确认,取消不会清除已发生费用。获客结果的了解采购方/深入研判创建对象关联子任务,点击前不深查。
投标文件只发送同源 `/api/files`,保留 multipart boundary、会话与 CSRF;必要正文和扫描页由后端发送 DeepSeek,不向公开搜索传文件全文。页面展示来源、文件定位、实际调用与模型 token;原件删除不等于删除报告摘录。
运行 `npm run build` 和本次改动文件 ESLint 已通过;浏览器在 H2 + 本地模拟 HTTP 环境验证候选确认、预算恢复、市场跳转、对象深挖和文件上传。真实 MySQL/知了/DeepSeek 尚待配置后验收。后端详细记录:[D3 实施与验收](../rz-GB/docs/D3实施与验收.md)。
D4 历史会话和单项目/整批提问均由后端保存。发现商机的“基于整批结果提问”覆盖该批全部已读候选,来源、日期、覆盖范围与实际模型 token 可回查。调研会话支持服务端搜索、改名、删除;删除范围在界面确认。构建与部署详见后端 `docs/接口契约与运行交付.md`。开发代理可设置 `API_PROXY_TARGET`,不在浏览器配置供应商密钥。
> 根据后续要求,已移除原型之外的高级检索、预算设置、服务验证、独立搜索、独立备注编辑和审计展示入口;界面以原型现有元素为准。下文为首轮验收记录,其中有关附加入口的描述已被本次修正取代。
# 原型一致性验收
日期:2026-10-29。原型为 `/Users/ruzhoukeji/Downloads/getbusiness/`,修改项目为 `/Users/ruzhoukeji/rz-GB-web/`。
本次按用户确认的范围执行:恢复全部业务页面的外观、布局和交互入口,保留真实登录、后端数据及任务流程。未覆盖原有业务实现,也未把原型模拟数据写入正式数据库。
## 逐页对照
| 页面 | 原有偏差 | 本次处理 |
| --- | --- | --- |
| 登录 | 登录后落地公司档案 | 恢复进入发现商机;保留原型品牌图、左右结构和表单,继续使用服务端认证 |
| 导航与顶栏 | 新增第五个主导航,调研副标题变化 | 恢复四个主导航及原型副标题;服务验证移到用户区;时间明确使用北京时间 |
| 发现商机 | 深色营销横幅、大量常驻筛选和方案区、五列表格 | 恢复小蜜蜂问候横幅、单行检索栏、权重弹窗、方案弹窗、七列表格、每页八条、关注及就地标签、批次页签 |
| 项目分析 | 点击项目跳到调研页,缺少原型右侧面板 | 恢复 600px 右侧面板、原文入口、关注按钮、快捷问题和底部输入;使用已有摘要和真实问答 |
| 重点关注 | 大块统计卡、常驻搜索和标签管理、宽版操作栏 | 恢复胶囊页签、紧凑项目卡、状态弹窗、备注、历史、标签和添加项目入口;搜索管理收进辅助弹窗 |
| 对话调研 | 四卡片和大表单、重复历史列表 | 恢复三个主要入口、居中欢迎区和底部输入,历史回到左侧;投标文件和预算由输入框内辅助按钮打开 |
| 公司档案 | 缺少导入入口,额外常驻权重区 | 恢复八组表单和文件识别核对预览;权重回到发现商机弹窗,保存继续读取服务端结果 |
基础配色、字体、圆角、阴影、原型图片和通用样式本来一致,保持复用。桌面对照使用相同 1280px 视口,按页面结构和组件外观检查;没有宣称不同数据、动态时间及动画画面能逐像素相等。
## 保留真实业务的差异
- 登录仍需真实账号密码,用户区展示当前预设账号,不展示原型的虚构人员身份。
- 查询仍遵循后端契约:获客模式中的地区与金额是排序偏好;普通检索使用硬条件。高级入口保留查询方式、关键词组合、精确日期、公告阶段和预算。后端时间范围最多一年,未伪装为无限历史。
- 检索和调研保留费用上限、主体确认、暂停继续、取消、来源、调用和 token 记录;这些信息通过弹窗或展开区域访问。
- 分数、摘要、参与条件及日期均来自后端已有原文;缺失显示未知,不生成原型里的演示结论。截止统计只识别明确的报名日期,不使用投标日期替代。
- “AI 导入”沿用原型的本地文本识别入口,提示中明确其为 TXT / Markdown 字段识别;不冒充模型调用。用户核对后写入表单,点击保存才提交后端。
- 手动项目尚无已核验的检索快照,先通过面板中的“项目研判”取得原文和证据,不能直接调用仅适用于检索快照的问答。
## 补充的真实保存与交互修复
原型“添加项目”只写浏览器内存。本次新增 `POST /api/watch/manual`,原子保存项目、关注及初始历史;公告链接和附件至少提供一个,附件需属于当前账号且未过期。相同提交键重试不重复创建,改变内容需新键;其他账号不能关注私有手动项目。
`GET /api/watch` 在原有字段外增加 `summary` 和 `fileId`,摘要复用已有原文规则提取,不发外部请求。附件信息独立返回,未改变历史检索候选的结构及完整性校验。
补充了弹窗焦点管理、Esc 关闭和恢复焦点;普通按钮默认不提交表单,避免“取消”触发保存。文件识别修复公司名称中的“验收”被误当作业绩的问题。已保存或提交结果未知的附件不会因关闭添加弹窗而误删。
## 验证结果
- `npm run build`:通过 TypeScript 检查和生产构建。
- 本次修改的 TS / TSX / MJS 文件 ESLint:通过。
- `npm run test:prototype`:10 项断言通过,覆盖文本识别、误识别和报名日期缺失/无效/投标日期混淆。
- Java 21 下运行 `./mvnw -q test`:107 项通过,0 失败、0 错误。包含新增手动保存、幂等冲突、来源与金额校验、CSRF、附件归属及跨账号拒绝访问。
- 浏览器使用本次启动的独立 H2 数据库与本机样例供应商,验证登录、公司档案保存、文件识别预览、检索和八条分页、项目面板、关注和真实问答提交、手动添加、状态备注保存、标签创建绑定及刷新回读、方案取消与保存、投标文件入口。
- 浏览器中的模型响应仅为本机验收样例,不能代表真实模型答案质量;未进行真实 MySQL、知了或 DeepSeek 付费联调。
## 截图
截图中的企业、项目与采购方是隔离验收样例,不是正式检索结果。
- [登录页](prototype-check/login.png)
- [发现商机](prototype-check/discover.png)
- [项目分析面板](prototype-check/panel.png)
- [重点关注](prototype-check/watch.png)
- [公司档案](prototype-check/profile.png)
- [对话调研](prototype-check/research.png)
- [原型对话调研参考](prototype-check/reference-research.png)
## 运行与更新
前端 `npm run dev` 使用现有 `vite.config.ts` 的同源 `/api` 代理;目标地址可用 `API_PROXY_TARGET` 指定。生产前端产物已重新生成到 `dist/`。
前后端需要同步更新并重启后端,新增的手动项目接口和关注摘要才会生效;只替换前端不能启用这些新接口。本次没有修改数据库表结构,没有发布线上环境,也没有停止用户原来运行的后端进程。
测试环境启动的数据库、样例服务及预览服务器仅供本次验收,完成后关闭。生产供应商凭证和已有业务数据未用于验收。
...@@ -7,7 +7,8 @@ ...@@ -7,7 +7,8 @@
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"test:prototype": "node --experimental-strip-types scripts/verify-prototype.mjs"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.2.2",
......
import assert from 'node:assert/strict'
import { extractProfileFromText } from '../src/lib/profileImport.ts'
import { registrationDate } from '../src/lib/day2.ts'
// 验收型公司名称曾触发“业绩”误识别;导入应保留原文事实并去掉字段标签。
const draft = extractProfileFromText('杭州验收科技有限公司\n主营业务:智慧水务、监测设备\n服务地区:浙江、江苏\n资质:电子与智能化工程专业承包二级')
assert.equal(draft.companyName, '杭州验收科技有限公司')
assert.equal(draft.mainBusiness, '智慧水务、监测设备')
assert.equal(draft.serviceRegions, '浙江、江苏')
assert.equal(draft.trackRecord, undefined)
assert.deepEqual(extractProfileFromText(''), {})
// 日期来自已有摘录;错误日期、只有投标截止或缺失摘录时必须保留未知。
assert.equal(registrationDate(['报名截止2026-11-06,投标截止2026-11-12']), '2026-11-06')
assert.equal(registrationDate(['报名截止时间:2026年11月6日']), '2026-11-06')
assert.equal(registrationDate(['投标截止2026-11-12']), null)
assert.equal(registrationDate(['报名截止2026-02-30']), null)
assert.equal(registrationDate(), null)
console.log('原型交互数据检查通过(10 项断言)')
...@@ -3,27 +3,45 @@ import { Routes, Route, useLocation, Navigate } from 'react-router' ...@@ -3,27 +3,45 @@ import { Routes, Route, useLocation, Navigate } from 'react-router'
import { StoreProvider } from './lib/store' import { StoreProvider } from './lib/store'
import Sidebar from './components/Sidebar' import Sidebar from './components/Sidebar'
import Topbar from './components/Topbar' import Topbar from './components/Topbar'
import { AiPanel } from './components/AiPanel'
import { DiscoverPage } from './pages/DiscoverPage' import { DiscoverPage } from './pages/DiscoverPage'
import { WatchPage } from './pages/WatchPage' import { WatchPage } from './pages/WatchPage'
import { ResearchPage } from './pages/ResearchPage' import { ResearchPage } from './pages/ResearchPage'
import { ProfilePage } from './pages/ProfilePage' import { ProfilePage } from './pages/ProfilePage'
import { LoginPage } from './pages/LoginPage' import { LoginPage } from './pages/LoginPage'
import type { AiPanelState } from './types' import { api, logout as serverLogout } from './lib/api'
import { AiPanel } from './components/AiPanel'
import type { AnalysisPanelState } from './components/AiPanel'
export default function App() { export default function App() {
const [panel, setPanel] = useState<AiPanelState>({ kind: 'closed' }) const [panel, setPanel] = useState<AnalysisPanelState>({ kind: 'closed' })
const { pathname } = useLocation() const { pathname, search } = useLocation()
// 演示登录态:本地记录,退出登录清除 // 每次加载均向服务端恢复会话,不能信任浏览器旧演示环境的布尔值。
const [authed, setAuthed] = useState(() => localStorage.getItem('rz-authed') === '1') const [authed, setAuthed] = useState<boolean | null>(null)
const [authError, setAuthError] = useState('')
useEffect(() => {
let active = true
void api('/auth/me').then(() => { if (active) setAuthed(true) }).catch(error => {
if (!active) return
if (error.status !== 401) setAuthError(error.message)
setAuthed(false)
})
const expire = () => { setAuthed(false) }
window.addEventListener('session-expired', expire)
return () => { active = false; window.removeEventListener('session-expired', expire) }
}, [])
// 路由切换时内容区回顶 // 路由切换时内容区回顶
useEffect(() => { useEffect(() => {
document.getElementById('main-scroll')?.scrollTo({ top: 0, behavior: 'auto' }) document.getElementById('main-scroll')?.scrollTo({ top: 0, behavior: 'auto' })
}, [pathname]) }, [pathname])
const login = () => { localStorage.setItem('rz-authed', '1'); setAuthed(true) } const login = () => { setAuthError(''); setAuthed(true) }
const logout = () => { localStorage.removeItem('rz-authed'); setAuthed(false) } const logout = async () => {
try { await serverLogout(); setAuthed(false) }
catch (error) { setAuthError(error instanceof Error ? error.message : '退出失败,请重试') }
}
if (authed === null) return <div className="p-8 text-sm" role="status">正在恢复登录会话…</div>
if (pathname === '/login') { if (pathname === '/login') {
return authed ? <Navigate to="/" replace /> : <LoginPage onLogin={login} /> return authed ? <Navigate to="/" replace /> : <LoginPage onLogin={login} />
...@@ -38,16 +56,17 @@ export default function App() { ...@@ -38,16 +56,17 @@ export default function App() {
</div> </div>
<div className="flex min-w-0 flex-1 flex-col"> <div className="flex min-w-0 flex-1 flex-col">
<Topbar /> <Topbar />
{authError && <div role="alert" className="bg-red-50 px-5 py-2 text-sm text-red-700">{authError}</div>}
<main id="main-scroll" className="min-h-0 flex-1 overflow-y-auto overscroll-contain scrollbar-thin"> <main id="main-scroll" className="min-h-0 flex-1 overflow-y-auto overscroll-contain scrollbar-thin">
<Routes> <Routes>
<Route path="/" element={<DiscoverPage onOpenPanel={setPanel} />} /> <Route path="/" element={<DiscoverPage onOpenPanel={setPanel} />} />
<Route path="/watch" element={<WatchPage onOpenPanel={setPanel} />} /> <Route path="/watch" element={<WatchPage onOpenPanel={setPanel} />} />
<Route path="/research" element={<ResearchPage />} /> <Route path="/research" element={<ResearchPage key={search} />} />
<Route path="/profile" element={<ProfilePage />} /> <Route path="/profile" element={<ProfilePage />} />
</Routes> </Routes>
</main> </main>
</div> </div>
<AiPanel state={panel} onClose={() => setPanel({ kind: 'closed' })} /> <AiPanel key={panel.kind === 'project' ? panel.project.id : panel.kind === 'search' ? panel.batchId : 'closed'} state={panel} onClose={() => setPanel({ kind: 'closed' })} />
</div> </div>
</StoreProvider> </StoreProvider>
) )
......
import { useEffect, useRef, useState } from 'react'
import { FileUp, X } from 'lucide-react'
import { api } from '../lib/api'
import { inputClass, message } from '../lib/day2'
import { PrototypeDialog } from './PrototypeDialog'
import { GhostButton, PrimaryButton } from './ui-ext/AiButton'
/** 原型手动添加入口:附件真正上传到同源后端,项目与关注原子保存,失败保留输入。 */
export function AddProjectDialog({ onClose, onAdded }: { onClose: () => void; onAdded: () => Promise<void> }) {
const [form, setForm] = useState({ url: '', title: '', purchaser: '', region: '', budget: '' })
const [file, setFile] = useState<{ id: string; filename: string } | null>(null)
const [saved, setSaved] = useState(false)
const [limit, setLimit] = useState(20 * 1024 * 1024)
const [busy, setBusy] = useState(false), [error, setError] = useState('')
const pending = useRef<{ body: string; commandId: string } | null>(null)
useEffect(() => {
let active = true
void api<{ maxFileBytes: number }>('/system/limits').then(value => { if (active) setLimit(value.maxFileBytes) }).catch(e => { if (active) setError(message(e)) })
return () => { active = false }
}, [])
const upload = async (value?: File) => {
if (!value || busy) return
if (value.size > limit) { setError(`文件不能超过 ${Math.floor(limit / 1024 / 1024)} MB`); return }
setBusy(true); setError('')
try {
// 替换附件先清理旧临时原件;只有上传成功后才展示新文件名。
if (file) { await api(`/files/${file.id}`, { method: 'DELETE' }); setFile(null) }
const body = new FormData(); body.set('purpose', 'BID_PROJECT'); body.set('file', value)
const uploaded = await api<{ id: string; filename: string }>('/files', { method: 'POST', body })
setFile(uploaded)
// 与原型一致,仅用文件名预填尚未填写的项目名称,不虚构缺失的采购方、预算等资料。
setForm(current => current.title ? current : { ...current, title: uploaded.filename.replace(/\.[^.]+$/, '') })
} catch (e) { setError(message(e)) } finally { setBusy(false) }
}
const close = async () => {
if (busy) return
setBusy(true); setError('')
// 已尝试提交但响应未知时,文件可能已关联成功;关闭只保留到期清理,不能误删已保存项目的原件。
try { if (file && !pending.current) await api(`/files/${file.id}`, { method: 'DELETE' }); onClose() }
catch (e) { setError(message(e)) } finally { setBusy(false) }
}
const submit = async () => {
if (busy) return
if (!form.url.trim() && !file) { setError('请填写公告网址或上传公告文件'); return }
if (form.url.trim() && !/^https?:\/\//i.test(form.url.trim())) { setError('网址需以 http:// 或 https:// 开头'); return }
setBusy(true); setError('')
try {
if (saved) { await onAdded(); onClose(); return }
const data = { title: form.title.trim(), url: form.url.trim(), purchaser: form.purchaser.trim(), region: form.region.trim(), budgetWan: form.budget === '' ? null : Number(form.budget), fileId: file?.id ?? null }
const body = JSON.stringify(data)
if (pending.current?.body !== body) pending.current = { body, commandId: crypto.randomUUID() }
await api('/watch/manual', { method: 'POST', body: JSON.stringify({ ...data, commandId: pending.current.commandId }) })
// 保存后即使刷新列表失败,也不能在关闭弹窗时删除已绑定的附件。
setFile(null); pending.current = null; setSaved(true)
await onAdded(); onClose()
} catch (e) { setError(message(e)) } finally { setBusy(false) }
}
return <PrototypeDialog open onClose={() => void close()} title="添加项目" className="w-[420px]">
<p className="mt-1 text-[13px] leading-relaxed text-ink-400">粘贴公告网址,或直接上传公告文件(PDF / Word / 图片)。</p>
<form onSubmit={e => { e.preventDefault(); void submit() }} className="mt-3 space-y-2.5">
<fieldset disabled={busy || saved} className="space-y-2.5">
<label className="block text-[13px] font-medium text-ink-900">公告网址 <span className="text-xs font-normal text-ink-400">选填</span><input value={form.url} maxLength={2048} onChange={e => setForm(f => ({ ...f, url: e.target.value }))} placeholder="https://…" className={`${inputClass} mt-1 text-[13px]`} /></label>
<div><label className="text-[13px] font-medium text-ink-900">公告文件 <span className="text-xs font-normal text-ink-400">选填,与网址二选一</span></label>{file ? <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">{file.filename}</span><button type="button" aria-label="移除文件" onClick={() => { setBusy(true); void api(`/files/${file.id}`, { method: 'DELETE' }).then(() => setFile(null)).catch(e => setError(message(e))).finally(() => setBusy(false)) }} className="shrink-0 rounded-full p-0.5 text-ink-400 hover:text-bad-500"><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 hover:border-brand-500/40 hover:text-brand-500"><FileUp size={14} /> 上传公告文件<input aria-label="上传公告文件" type="file" accept=".pdf,.doc,.docx,.txt,.md,.png,.jpg,.jpeg" onChange={e => void upload(e.target.files?.[0])} className="hidden" /></label>}</div>
<label className="block text-[13px] font-medium text-ink-900">项目名称 <span className="text-warn-500">*</span><input required maxLength={512} value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} className={`${inputClass} mt-1 text-[13px]`} placeholder="按公告标题填写" /></label>
<div className="grid grid-cols-3 gap-2"><label className="text-[13px] font-medium text-ink-900">招标方<input maxLength={512} value={form.purchaser} onChange={e => setForm(f => ({ ...f, purchaser: e.target.value }))} className={`${inputClass} mt-1 text-[13px]`} placeholder="选填" /></label><label className="text-[13px] font-medium text-ink-900">地区<input maxLength={120} value={form.region} onChange={e => setForm(f => ({ ...f, region: e.target.value }))} className={`${inputClass} mt-1 text-[13px]`} placeholder="选填" /></label><label className="text-[13px] font-medium text-ink-900">预算(万元)<input type="number" min={0} max={100000000} step="any" value={form.budget} onChange={e => setForm(f => ({ ...f, budget: e.target.value }))} className={`${inputClass} mt-1 font-num text-[13px]`} placeholder="选填" /></label></div>
</fieldset>
{error && <p role="alert" className="text-xs text-bad-500">{error}</p>}
<div className="!mt-4 flex justify-end gap-2"><GhostButton disabled={busy} onClick={() => void close()}>取消</GhostButton><PrimaryButton type="submit" disabled={busy || !form.title.trim()}>{saved ? '重试' : '添加并关注'}</PrimaryButton></div>
</form>
</PrototypeDialog>
}
import { useEffect, useRef, useState } from 'react' import { useState } from 'react'
import { X, ExternalLink, Star, Send, Loader2, Sparkles } from 'lucide-react' import * as Dialog from '@radix-ui/react-dialog'
import { motion, AnimatePresence } from 'framer-motion' import { ExternalLink, Sparkles, Star, X } from 'lucide-react'
import type { AiPanelState } from '../types' import type { Candidate, RankedItem } from '../lib/day2'
import { useStore, conditionsText, nowStr } from '../lib/store' import { message } from '../lib/day2'
import { projectAnalysis, projectFollowUp, searchQaAnswer } from '../lib/ai' import { useStore } from '../lib/store'
import { ConversationView } from './ConversationView'
import { Markdown } from './Markdown' import { Markdown } from './Markdown'
import { useStreaming } from '../hooks/useStreaming' import { defaultMatchDimNames } from '../types'
import { cn } from '@/lib/utils'
export type AnalysisPanelState = { kind: 'closed' } | { kind: 'project'; project: Candidate; item?: RankedItem; summary?: NonNullable<RankedItem['analysis']>['summary']; batchId?: string } | { kind: 'search'; batchId: string }
interface Msg {
role: 'user' | 'assistant' /** 严格复用原型 600px 面板与快捷提问;展示真实数据,不插入额外按钮和说明区。 */
content: string export function AiPanel({ state, onClose }: { state: AnalysisPanelState; onClose: () => void }) {
streaming?: boolean const { isWatched, addWatch, removeWatch } = useStore()
} const [error, setError] = useState(''), [busy, setBusy] = useState(false)
if (state.kind === 'closed') return null
const PROJECT_QUICK = ['报名和投标截止时间', '公告参与条件', '预算口径与报价参考', '风险与注意事项'] const project = state.kind === 'project' ? state.project : null
const SEARCH_QUICK = ['哪些项目报名快截止了', '这些项目的预算披露情况', '这些项目有哪些共同要求', '比较一下这些项目'] const item = state.kind === 'project' ? state.item : undefined
const summary = state.kind === 'project' ? state.item?.analysis?.summary ?? state.summary : undefined
export function AiPanel({ state, onClose }: { state: AiPanelState; onClose: () => void }) { const batchId = state.batchId ?? null
const { profile, batches, addWatch, isWatched, removeWatch, findProject } = useStore() const title = project ? '项目 AI 分析' : '基于本次搜索提问'
const [messages, setMessages] = useState<Msg[]>([]) const follow = async (remove = false) => {
const [input, setInput] = useState('') if (!project || busy) return
const [busy, setBusy] = useState(false) setBusy(true); setError('')
const scrollRef = useRef<HTMLDivElement>(null) try { if (remove) await removeWatch(project.id); else await addWatch(project.id) }
const { stream, stop } = useStreaming() catch (e) { setError(message(e)) } finally { setBusy(false) }
const project = state.kind === 'project' ? findProject(state.projectId) : null
const batch = state.kind === 'search' ? batches.find(b => b.id === state.batchId) : null
const open = state.kind !== 'closed'
// 打开或切换项目/批次时重置对话,保证对话绑定当前对象
useEffect(() => {
if (!open) return
stop()
setInput('')
setBusy(true)
const initText = state.kind === 'project' && project
? projectAnalysis(project, profile)
: state.kind === 'search' && batch
? `### 基于本次搜索提问\n\n本次对话对应实际执行的检索条件:**${conditionsText(batch.conditions)}**,执行时间 ${batch.executedAt},共 **${batch.total} 条结果**。\n\n你可以围绕这批结果比较、提问。我只基于本次结果回答,不会修改结果列表的范围或顺序;如结果分页,默认覆盖全部 ${batch.total} 条而非仅当前页。`
: '暂无上下文'
setMessages([{ role: 'assistant', content: '', streaming: true }])
stream(initText, (partial, done) => {
setMessages([{ role: 'assistant', content: partial, streaming: !done }])
if (done) setBusy(false)
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state])
useEffect(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })
}, [messages])
const ask = (q: string) => {
const question = q.trim()
if (!question || busy) return
setInput('')
setBusy(true)
const answer = state.kind === 'project' && project
? projectFollowUp(project, question, profile)
: state.kind === 'search' && batch
? searchQaAnswer(batch, question, profile)
: '暂无上下文'
setMessages(m => [...m, { role: 'user', content: question }, { role: 'assistant', content: '', streaming: true }])
setTimeout(() => {
stream(answer, (partial, done) => {
setMessages(m => {
const next = [...m]
next[next.length - 1] = { role: 'assistant', content: partial, streaming: !done }
return next
})
if (done) setBusy(false)
})
}, 400)
} }
// 按原型的报告标题和正文排版展示后端事实,不增加“深入研判”等原型没有的入口。
const title = state.kind === 'project' ? '项目 AI 分析' : '基于本次搜索提问' const lines = project ? [
const subtitle = state.kind === 'project' && project `### 项目分析:${project.title}`,
? `${project.region} · ${project.purchaser}` '**公告事实**',
: state.kind === 'search' && batch `- 采购单位:${project.purchaser || '待确认'}`,
? conditionsText(batch.conditions) `- 地区:${project.region || '未披露'}`,
: '' `- 预算:${project.budgetWan == null ? '公告未披露预算' : `${project.budgetWan.toLocaleString()} 万元`}`,
`- 发布日期:${project.publishDate || '未披露'}`,
return ( '\n**项目内容**', summary?.construction || '暂无已取得的公告正文',
<AnimatePresence> '\n**公告参与条件**', summary?.qualifications.map(value => `- ${value}`).join('\n') || '公告参与条件待核验',
{open && ( ] : ['### 基于本次搜索提问', '你可以围绕这批结果比较、提问。我只基于本次结果回答,不会修改结果列表的范围或顺序。']
<div className="fixed inset-0 z-50" role="dialog" aria-label={title}> if (item?.analysis?.match) {
<motion.div className="absolute inset-0 bg-ink-900/20 backdrop-blur-sm" const match = item.analysis.match
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }} lines.push(`\n**结合公司档案对照**(档案版本 v${match.profileVersion})`, `- 贴合度参考:**${match.score ?? '—'} 分**`, '\n**贴合度打分报告**', '| 维度 | 权重 | 得分 | 依据 |', '| --- | --- | --- | --- |')
onClick={onClose} /> for (const [key, dimension] of Object.entries(match.dimensions)) lines.push(`| ${defaultMatchDimNames[key as keyof typeof defaultMatchDimNames] ?? key} | ${match.weights[key]}% | ${dimension.known ? dimension.score : '待核验'} | ${dimension.basis} |`)
<motion.aside }
className="absolute right-0 top-0 flex h-full w-[600px] max-w-[94vw] flex-col border-l border-line-soft bg-white shadow-card-hover" if (project && (summary?.gaps ?? project.gaps).length) lines.push('\n**风险与未知项**', ...(summary?.gaps ?? project.gaps).map(value => `- ${value}`))
initial={{ x: 60, opacity: 0 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 60, opacity: 0 }} const analysisText = lines.join('\n')
transition={{ duration: 0.22, ease: 'easeOut' }}> return <Dialog.Root open onOpenChange={open => { if (!open) onClose() }}><Dialog.Portal>
{/* 头部:项目名称与操作(加入重点关注不单独占行) */} <Dialog.Overlay className="fixed inset-0 z-50 bg-ink-900/20 backdrop-blur-sm" />
<header className="flex items-start gap-2 border-b border-line-soft px-4 py-3"> <Dialog.Content aria-describedby={undefined} className="fixed right-0 top-0 z-50 flex h-[100dvh] w-[600px] max-w-[94vw] flex-col border-l border-line-soft bg-white shadow-card-hover outline-none">
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-ctrl" <header className="flex items-start gap-2 border-b border-line-soft px-4 py-3"><div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-ctrl bg-gradient-to-br from-brand-500 to-indigo-400"><Sparkles size={16} className="text-white" /></div><div className="min-w-0 flex-1"><Dialog.Title className="text-[13px] font-normal text-ink-400">{title}</Dialog.Title><h2 className="truncate text-[15px] font-bold leading-snug" title={project?.title}>{project?.title || '围绕当前检索结果提问'}</h2><p className="mt-0.5 truncate text-xs text-ink-400">{project ? `${project.region || '地区待核验'} · ${project.purchaser || '采购方待核验'}` : '基于本次执行的全部已读候选,保留检索条件与结果顺序'}</p>{project?.url && <a href={project.url} target="_blank" rel="noreferrer" className="mt-1 inline-flex items-center gap-1 text-xs text-brand-500 hover:underline"><ExternalLink size={12} /> 查看公告原文</a>}</div>{project && <button disabled={busy} onClick={() => void follow(isWatched(project.id))} className="mt-1 inline-flex shrink-0 items-center gap-1 rounded-full border border-brand-500/50 bg-brand-50 px-2.5 py-1.5 text-xs font-medium text-brand-500"><Star size={13} fill={isWatched(project.id) ? 'currentColor' : 'none'} />{isWatched(project.id) ? '已关注' : '加入重点关注'}</button>}<Dialog.Close aria-label="关闭" className="mt-1 rounded-full p-1.5 text-ink-400 hover:bg-canvas"><X size={16} /></Dialog.Close></header>
style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}> {error && <p role="alert" className="px-4 py-2 text-xs text-bad-500">{error}</p>}
<Sparkles size={16} className="text-white" /> <ConversationView embedded scope={{ batchId, projectId: project?.id ?? null }}>
</div> <div className="max-w-full rounded-card rounded-tl-sm border border-line-soft bg-white px-3.5 py-2.5 shadow-card">
<div className="min-w-0 flex-1"> <Markdown text={analysisText} />
<div className="text-[13px] text-ink-400">{title}</div>
<h2 className="truncate text-[15px] font-bold leading-snug" title={project?.name ?? ''}>
{state.kind === 'project' ? project?.name : '围绕当前检索结果提问'}
</h2>
<div className="mt-0.5 truncate text-xs text-ink-400">{subtitle}</div>
{state.kind === 'project' && project && (
<div className="mt-1">
{project.sourceUrl ? (
<a href={project.sourceUrl} target="_blank" rel="noreferrer"
className="inline-flex items-center gap-1 text-xs text-brand-500 hover:underline">
<ExternalLink size={12} /> 查看公告原文({project.sourceName})
</a>
) : (
<span className="text-xs text-ink-400">来源:{project.sourceName}(链接暂未收录)</span>
)}
</div>
)}
</div>
{state.kind === 'project' && project && (
isWatched(project.id) ? (
<button onClick={() => removeWatch(project.id)}
className="mt-1 inline-flex shrink-0 items-center gap-1 rounded-full bg-brand-50 px-2.5 py-1.5 text-xs font-medium text-brand-500 transition-colors hover:bg-brand-100">
<Star size={13} fill="currentColor" /> 已关注
</button>
) : (
<button onClick={() => addWatch(project.id)}
className="mt-1 inline-flex shrink-0 items-center gap-1 rounded-full border border-brand-500/50 px-2.5 py-1.5 text-xs font-medium text-brand-500 transition-colors hover:bg-brand-50">
<Star size={13} /> 加入重点关注
</button>
)
)}
<button onClick={onClose} className="mt-1 shrink-0 rounded-full p-1.5 text-ink-400 transition-colors hover:bg-[#F4F7FB]" aria-label="关闭">
<X size={16} />
</button>
</header>
{/* 消息区 */}
<div ref={scrollRef} className="flex-1 space-y-4 overflow-y-auto bg-canvas px-4 py-3 scrollbar-thin">
{messages.map((m, i) => (
<div key={i} className={m.role === 'user' ? 'flex justify-end' : ''}>
{m.role === 'user' ? (
<div className="max-w-[85%] rounded-2xl rounded-br-sm bg-brand-500 px-3.5 py-2 text-[14px] text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]">{m.content}</div>
) : (
<div className="max-w-full rounded-card rounded-tl-sm border border-line-soft bg-white px-3.5 py-2.5 shadow-card">
<Markdown text={m.content} streaming={m.streaming} />
</div>
)}
</div>
))}
{busy && messages[messages.length - 1]?.role === 'user' && (
<div className="flex items-center gap-2 text-[13px] text-ink-400">
<Loader2 size={14} className="animate-spin text-brand-500" /> 正在分析…
</div>
)}
</div>
{/* 快捷问题 + 输入区(紧凑排列) */}
<footer className="border-t border-line-soft bg-white px-3 pb-3 pt-2">
<div className="mb-2 flex flex-wrap gap-1.5">
{(state.kind === 'project' ? PROJECT_QUICK : SEARCH_QUICK).map(q => (
<button key={q} disabled={busy} onClick={() => ask(q)}
className="rounded-full border border-line-soft px-2.5 py-1 text-xs text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500 disabled:opacity-50">
{q}
</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={state.kind === 'project' ? '围绕这个项目继续追问…' : '围绕本次检索结果提问…'}
className="max-h-28 flex-1 resize-none rounded-ctrl border border-line-soft px-3 py-2 text-[14px] 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"
/>
<button onClick={() => ask(input)} disabled={!input.trim() || busy}
className={cn('rounded-full bg-brand-500 p-2.5 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)] transition-colors hover:bg-brand-600 disabled:opacity-40')}
aria-label="发送">
<Send size={16} />
</button>
</div>
<div className="mt-1.5 text-[11px] text-ink-400">
AI 分析供参考,是否跟进、报名或投标由你决定 · 上下文时间 <span className="font-num">{nowStr().slice(0, 10)}</span>
</div>
</footer>
</motion.aside>
</div> </div>
)} </ConversationView>
</AnimatePresence> </Dialog.Content>
) </Dialog.Portal></Dialog.Root>
} }
import { useEffect, useRef, useState } from 'react'
import type { ReactNode } from 'react'
import { Send, Loader2 } from 'lucide-react'
import { useNavigate } from 'react-router'
import { api } from '../lib/api'
import { conversationsChanged } from '../lib/conversations'
import type { Conversation, ConversationMessage, QaScope } from '../lib/conversations'
import type { AgentTask } from '../hooks/useTaskEvents'
import { beijingDate, message } from '../lib/day2'
import { ResearchTask } from './ResearchTask'
import { PrimaryButton } from './ui-ext/AiButton'
/** 会话保存任务引用,恢复历史只执行 GET;只有明确提交问题才创建一次收费模型任务。 */
export function ConversationView({ id: initialId, scope: initialScope, embedded = false, children }: { id?: string; scope?: QaScope; embedded?: boolean; children?: ReactNode }) {
// 面板内创建会话后原地回读,不跳转离开检索页;关闭面板不取消已创建任务。
const [id, setId] = useState(initialId)
const navigate = useNavigate()
const [messages, setMessages] = useState<ConversationMessage[]>([])
const [scope, setScope] = useState<QaScope | undefined>(initialScope)
const [input, setInput] = useState(''), [error, setError] = useState(''), [busy, setBusy] = useState(false)
const [ready, setReady] = useState(!id)
const scrollRef = useRef<HTMLDivElement>(null)
useEffect(() => { scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' }) }, [messages])
const inFlight = useRef(false)
// 网络结果未知时保留会话与幂等键;重复点击或手动重试不产生第二次模型请求。
const pending = useRef<{ signature: string; key: string; conversationId?: string } | null>(null)
useEffect(() => {
if (!id) return
let active = true
void Promise.all([api<Conversation>(`/conversations/${id}`), api<ConversationMessage[]>(`/conversations/${id}/messages`)]).then(async ([, rows]) => {
if (!active) return
setMessages(rows)
const taskId = rows.at(-1)?.task_id
if (taskId) {
const task = await api<AgentTask>(`/agent/tasks/${taskId}`)
if (active) setScope(task.request.qa ?? undefined)
}
if (active) setReady(true)
}).catch(e => { if (active) setError(message(e)) })
return () => { active = false }
}, [id])
const ask = async (raw = input) => {
if (inFlight.current || !raw.trim() || !scope) return
inFlight.current = true; setBusy(true); setError('')
const body = { question: raw.trim(), scope }
const signature = JSON.stringify(body)
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID(), conversationId: id }
try {
if (!pending.current.conversationId) {
const c = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) })
pending.current.conversationId = c.id
}
const conv = pending.current.conversationId
await api(`/conversations/${conv}/messages`, { method: 'POST', headers: { 'Idempotency-Key': pending.current.key }, body: JSON.stringify(body) })
pending.current = null; setInput(''); conversationsChanged()
if (id) {
setMessages(await api<ConversationMessage[]>(`/conversations/${id}/messages`))
} else if (embedded) setId(conv)
else navigate(`/research?conv=${conv}`, { replace: true })
} catch (e) { setError(message(e)) } finally { inFlight.current = false; setBusy(false) }
}
const quick = scope?.projectId ? ['报名和投标截止时间', '公告参与条件', '预算口径与报价参考', '风险与注意事项'] : ['哪些项目报名快截止了', '这些项目的预算披露情况', '这些项目有哪些共同要求', '比较一下这些项目']
return <section className="flex h-full min-h-0 flex-col">
<div ref={scrollRef} className={`min-h-0 flex-1 space-y-4 overflow-y-auto scrollbar-thin ${embedded ? 'bg-canvas px-4 py-3' : 'px-6 py-5'}`}>
<div className={embedded ? 'space-y-4' : 'mx-auto max-w-[820px] space-y-4'}>
{children}
{error && <p role="alert" className="rounded-ctrl bg-red-50 p-3 text-sm text-red-700">{error}<button className="ml-3 underline" onClick={() => window.location.reload()}>重新读取历史</button></p>}
{!ready && !error && <p role="status" className="text-sm text-ink-400">正在读取历史会话…</p>}
{messages.map(row => <article key={row.id} className="space-y-3"><div className="flex justify-end"><p className="max-w-[85%] whitespace-pre-wrap rounded-2xl rounded-br-sm bg-brand-500 px-4 py-2 text-[14px] text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]">{row.content}</p></div>{row.task_id && <ResearchTask id={row.task_id} />}</article>)}
</div>
</div>
{ready && scope && <footer className="shrink-0 border-t border-line-soft bg-white/75 px-4 py-3 backdrop-blur-md"><div className={embedded ? '' : 'mx-auto max-w-[820px]'}>
{embedded && <div className="mb-2 flex flex-wrap gap-1.5">{quick.map(q => <button key={q} disabled={busy} onClick={() => { setInput(q); void ask(q) }} className="rounded-full border border-line-soft px-2.5 py-1 text-xs text-ink-600 hover:border-brand-500/40 hover:text-brand-500 disabled:opacity-40">{q}</button>)}</div>}
<form onSubmit={e => { e.preventDefault(); void ask() }} className="flex items-end gap-2"><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 ask() } }} required maxLength={2000} rows={1} className="max-h-28 flex-1 resize-none rounded-ctrl border border-line-soft px-3 py-2 text-[14px] outline-none focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" placeholder={scope.projectId ? '围绕这个项目继续追问…' : '围绕本次检索结果提问…'} /><PrimaryButton aria-label="发送" disabled={busy || !input.trim()} type="submit" className="!rounded-full !p-2.5">{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}</PrimaryButton></form>
{embedded && <p className="mt-1.5 text-[11px] text-ink-400">AI 分析供参考,是否跟进、报名或投标由你决定 · 上下文时间 <span className="font-num">{beijingDate()}</span></p>}
</div></footer>}
</section>
}
import { useState } from 'react'
import { useStore } from '../lib/store'
import { defaultMatchDimNames } from '../types'
import { message } from '../lib/day2'
import { PrototypeDialog } from './PrototypeDialog'
import { GhostButton, PrimaryButton } from './ui-ext/AiButton'
/** 权重入口回到原型检索栏;继续使用服务端档案版本,失败时保留草稿和弹窗。 */
export function MatchWeightsDialog({ onClose }: { onClose: () => void }) {
const { profile, saveProfile } = useStore()
const [draft, setDraft] = useState({ ...profile.matchWeights })
const [busy, setBusy] = useState(false), [error, setError] = useState('')
const total = Object.values(draft).reduce((sum, value) => sum + value, 0)
const save = async () => {
if (busy || !total) return
setBusy(true); setError('')
try { await saveProfile({ ...profile, matchWeights: draft }); onClose() }
catch (e) { setError(message(e)) } finally { setBusy(false) }
}
return <PrototypeDialog open onClose={() => { if (!busy) onClose() }} title="匹配度权重">
<p className="mt-1 text-[13px] text-ink-400">拖动滑块调整各维度权重;合计不为 100 时按比例折算。</p>
<div className="mt-3 space-y-2.5">{(Object.keys(defaultMatchDimNames) as (keyof typeof draft)[]).map(key => <label key={key} className="flex items-center gap-3">
<span className="w-20 shrink-0 text-[13px] font-medium">{defaultMatchDimNames[key]}</span>
<input type="range" min={0} max={100} step={5} value={draft[key]} onChange={e => setDraft(d => ({ ...d, [key]: Number(e.target.value) }))} className="min-w-0 flex-1 accent-brand-500" />
<span className="w-12 text-right font-num text-[13px]">{draft[key]}%</span>
</label>)}</div>
{total !== 100 && <p className="mt-2 text-xs text-warn-500">当前合计 {total}%,{total ? '保存后按比例折算为 100% 参与计分' : '至少设置一个非零权重'}</p>}
{error && <p role="alert" className="mt-3 text-xs text-bad-500">{error}</p>}
<div className="mt-4 flex justify-end gap-2"><GhostButton disabled={busy} onClick={onClose}>取消</GhostButton><PrimaryButton disabled={busy || !total} onClick={() => void save()}>保存权重</PrimaryButton></div>
</PrototypeDialog>
}
import { useState } from 'react'
import { ChevronLeft, ChevronRight, ExternalLink, Sparkles, Star } from 'lucide-react'
import * as Popover from '@radix-ui/react-popover'
import type { RankedItem } from '../lib/day2'
import { message } from '../lib/day2'
import { useStore } from '../lib/store'
import { defaultMatchDimNames } from '../types'
import type { AnalysisPanelState } from './AiPanel'
import { ProjectTags } from './ProjectTags'
import { GhostButton } from './ui-ext/AiButton'
const PAGE_SIZE = 8
/** 原型七列表格,所有分数、节奏与门槛均读取已保存摘要,缺字段不在浏览器猜测。 */
export function OpportunityTable({ items, batchId, onOpenPanel }: {
items: RankedItem[]; batchId: string; onOpenPanel: (state: AnalysisPanelState) => void
}) {
const { addWatch, isWatched } = useStore()
const [scoreProject, setScoreProject] = useState<string | null>(null)
const [page, setPage] = useState(1), [error, setError] = useState('')
const [tagProject, setTagProject] = useState<string | null>(null), [saving, setSaving] = useState(false)
const totalPages = Math.max(1, Math.ceil(items.length / PAGE_SIZE)), current = Math.min(page, totalPages)
const rows = items.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE)
const open = (item: RankedItem) => onOpenPanel({ kind: 'project', project: item.facts, item, batchId })
const follow = async (id: string) => {
if (saving) return
setSaving(true); setError('')
try { if (!isWatched(id)) await addWatch(id); setTagProject(id) }
catch (e) { setError(message(e)) } finally { setSaving(false) }
}
return <>
{error && <p role="alert" className="px-5 py-2 text-xs text-bad-500">{error}</p>}
<div className="overflow-x-auto"><table className="w-full min-w-[940px] table-fixed text-left text-[13px]">
<colgroup>{[30, 15, 9, 14, 11, 7, 14].map((width, i) => <col key={i} style={{ width: `${width}%` }} />)}</colgroup>
<thead><tr className="border-b border-line-soft bg-[#FAFBFD] text-ink-400">{['项目名称', '招标方', '预算', '时间节奏', '参与门槛', '匹配度', '操作'].map((name, i) => <th key={name} className={i === 0 ? 'w-[30%] px-5 py-2.5 font-medium' : 'px-3 py-2.5 font-medium'}>{name}</th>)}</tr></thead>
<tbody>{rows.map(item => {
const p = item.facts, summary = item.analysis?.summary, match = item.analysis?.match
return <tr key={p.id} onClick={() => open(item)} 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.url ?? undefined} target="_blank" rel="noreferrer" onClick={e => { e.stopPropagation(); if (!p.url) open(item) }} className="inline-flex items-start gap-1 font-medium leading-snug text-ink-900 hover:text-brand-500 hover:underline"><span>{p.title || '标题待核验'}</span>{p.url && <ExternalLink size={12} className="mt-1 shrink-0 text-ink-400" />}</a><div className="mt-1 flex flex-wrap gap-1">{p.products.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">{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.budgetWan == null ? <span className="text-ink-400">未披露</span> : <span className="font-num font-bold">{p.budgetWan.toLocaleString()}<span className="text-xs font-medium text-ink-400"> 万元</span></span>}</td>
<td className="max-w-[150px] px-3 py-3"><div className="flex items-start gap-1.5 text-xs font-medium text-ink-600"><span className="mt-1 h-1.5 w-1.5 shrink-0 rounded-full bg-ink-400" /><span className="line-clamp-2" title={summary?.schedule.join(';')}>{summary?.schedule[0] || '截止未披露'}</span></div><div className="mt-0.5 font-num text-xs text-ink-400">发布 {p.publishDate || '未知'}</div></td>
<td className="max-w-[135px] px-3 py-3"><span className="block truncate rounded-full bg-warn-500/10 px-2.5 py-0.5 text-xs text-warn-500" title={summary?.qualifications.join(';')}>{summary?.qualifications[0] || '条件待核验'}</span></td>
<td className="px-3 py-3"><Popover.Root open={scoreProject === p.id} onOpenChange={value => setScoreProject(value ? p.id : null)}><Popover.Trigger asChild><button onMouseEnter={() => setScoreProject(p.id)} onMouseLeave={() => setScoreProject(null)} onFocus={() => setScoreProject(p.id)} onBlur={() => setScoreProject(null)} onClick={e => e.stopPropagation()} className="whitespace-nowrap font-num text-[15px] font-bold text-brand-500" aria-label={`查看${p.title}匹配度构成`}>{match?.score ?? '—'}{match?.score != null && <span className="text-xs font-medium text-ink-400"> 分</span>}</button></Popover.Trigger><Popover.Portal><Popover.Content onClick={e => e.stopPropagation()} sideOffset={8} className="z-50 w-72 rounded-card border border-line-soft bg-white p-3 shadow-card-hover"><h4 className="text-xs font-medium">贴合度打分构成</h4>{match ? <><ul className="mt-2 space-y-2">{Object.entries(match.dimensions).map(([key, dim]) => <li key={key} className="text-xs"><div className="flex justify-between"><span>{defaultMatchDimNames[key as keyof typeof defaultMatchDimNames] ?? key} · 权重 {match.weights[key]}%</span><b>{dim.known ? `${dim.score} 分` : '待核验'}</b></div><p className="mt-0.5 text-[11px] text-ink-400">{dim.basis}</p></li>)}</ul><p className="mt-2 text-[11px] text-ink-400">完整性 {match.completeness}% · 档案 v{match.profileVersion} · {match.limitation}</p></> : <p className="mt-2 text-xs text-ink-400">尚无已保存评分,请完善公司档案后重新检索。</p>}</Popover.Content></Popover.Portal></Popover.Root></td>
<td className="whitespace-nowrap px-3 py-3"><div className="flex items-center gap-1.5"><button onClick={e => { e.stopPropagation(); open(item) }} className="inline-flex 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>
<Popover.Root open={tagProject === p.id} onOpenChange={value => { if (!value) setTagProject(null) }}><Popover.Trigger asChild><button disabled={saving} onClick={e => { e.stopPropagation(); void follow(p.id) }} aria-label={isWatched(p.id) ? '管理关注标签' : '加入重点关注'} className="rounded-full p-1.5 text-brand-500 hover:bg-brand-50"><Star size={15} fill={isWatched(p.id) ? 'currentColor' : 'none'} /></button></Popover.Trigger><Popover.Portal><Popover.Content align="end" sideOffset={6} className="z-50" onClick={e => e.stopPropagation()}><ProjectTags projectId={p.id} onClose={() => setTagProject(null)} /></Popover.Content></Popover.Portal></Popover.Root>
</div></td>
</tr>
})}</tbody>
</table></div>
{!items.length && <div className="py-16 text-center"><SearchEmpty /></div>}
{!!items.length && <div className="flex flex-wrap items-center gap-3 px-5 py-3 text-[13px] text-ink-400"><span>第 <span className="font-num text-ink-900">{(current - 1) * PAGE_SIZE + 1}–{Math.min(current * PAGE_SIZE, items.length)}</span> 条,共 <span className="font-num text-ink-900">{items.length}</span> 条</span><span className="flex-1" /><GhostButton disabled={current <= 1} onClick={() => setPage(current - 1)} className="!px-2.5 !py-1 text-xs"><ChevronLeft size={14} /> 上一页</GhostButton><span className="font-num">第 {current} / {totalPages} 页</span><GhostButton disabled={current >= totalPages} onClick={() => setPage(current + 1)} className="!px-2.5 !py-1 text-xs">下一页 <ChevronRight size={14} /></GhostButton></div>}
</>
}
function SearchEmpty() {
return <><p className="text-sm font-medium">没有符合条件的项目</p><p className="mt-1 text-xs text-ink-400">可调整关键词、地区、预算或发布时间范围后重新检索</p></>
}
import { useEffect, useRef, useState } from 'react'
import { api } from '../lib/api'
import type { Tag, WatchItem } from '../lib/day2'
import { message } from '../lib/day2'
import { useStore } from '../lib/store'
import { cn } from '../lib/utils'
/** 列表内直接打标签;每次保存回读最新版本,网络重试沿用同一幂等键。 */
export function ProjectTags({ projectId, onClose, showDone = true }: { projectId: string; onClose: () => void; showDone?: boolean }) {
const { refreshWatch } = useStore()
const [tags, setTags] = useState<Tag[]>([]), [row, setRow] = useState<WatchItem | null>(null)
const [name, setName] = useState(''), [error, setError] = useState(''), [busy, setBusy] = useState(false)
const pending = useRef<{ body: string; key: string } | null>(null)
useEffect(() => {
let active = true
void Promise.all([api<Tag[]>('/tags'), api<WatchItem[]>('/watch')]).then(([all, rows]) => {
if (active) { setTags(all); setRow(rows.find(item => item.projectId === projectId) ?? null) }
}).catch(e => { if (active) setError(message(e)) })
return () => { active = false }
}, [projectId])
const save = async (tag: string, create = false) => {
if (!row || busy || !tag.trim()) return
setBusy(true); setError('')
try {
if (create) await api('/tags', { method: 'POST', body: JSON.stringify({ name: tag.trim() }) })
const selected = create ? [...new Set([...row.tags, tag.trim()])] : row.tags.includes(tag) ? row.tags.filter(t => t !== tag) : [...row.tags, tag]
const body = JSON.stringify({ tags: selected, version: row.version })
if (pending.current?.body !== body) pending.current = { body, key: crypto.randomUUID() }
await api(`/watch/${encodeURIComponent(projectId)}/tags`, { method: 'PUT', body, headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null
const [all, rows] = await Promise.all([api<Tag[]>('/tags'), api<WatchItem[]>('/watch')])
setTags(all); setRow(rows.find(item => item.projectId === projectId) ?? null); setName(''); await refreshWatch()
} catch (e) { setError(message(e)) } finally { setBusy(false) }
}
return <div className="w-60 rounded-card border border-line-soft bg-white p-3 text-left shadow-card-hover">
<div className="text-xs font-medium">{showDone ? '给这个项目打个标签' : '选择或新建标签'}</div>
<div className="mt-2 flex flex-wrap gap-1.5">{tags.map(tag => <button key={tag.id} disabled={busy || !row} onClick={() => void save(tag.name)} className={cn('rounded-full border px-2.5 py-1 text-[12px]', row?.tags.includes(tag.name) ? 'border-brand-500 bg-brand-50 text-brand-500' : 'border-line-soft text-ink-600')}>{tag.name}</button>)}</div>
<form onSubmit={e => { e.preventDefault(); void save(name, true) }} className="mt-2 flex gap-1.5"><input aria-label="新标签名称" maxLength={64} value={name} onChange={e => setName(e.target.value)} placeholder="新建标签,回车添加" className="min-w-0 flex-1 rounded-ctrl border border-line-soft px-2.5 py-1.5 text-[12px] outline-none focus:border-brand-500" />{showDone && <button disabled={busy || !row || !name.trim()} className="rounded-ctrl bg-brand-500 px-2 text-xs text-white disabled:opacity-40">添加</button>}</form>
{error && <p role="alert" className="mt-2 whitespace-normal text-xs text-bad-500">{error}</p>}
{showDone && <button onClick={onClose} className="mt-2 w-full rounded-ctrl border border-line-soft py-1 text-xs text-ink-600">完成</button>}
</div>
}
import type { ReactNode } from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import { cn } from '../lib/utils'
/** 原型弹窗的统一外观;Radix 负责焦点圈定、Esc 关闭和关闭后恢复焦点。 */
export function PrototypeDialog({ open, onClose, title, children, className }: {
open: boolean; onClose: () => void; title: string; children: ReactNode; className?: string
}) {
return <Dialog.Root open={open} onOpenChange={value => { if (!value) onClose() }}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-50 bg-ink-900/20 backdrop-blur-sm" />
<Dialog.Content aria-describedby={undefined} className={cn('fixed left-1/2 top-1/2 z-50 max-h-[85dvh] w-[400px] max-w-[94vw] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-card border border-line-soft bg-white p-5 shadow-card-hover outline-none scrollbar-thin', className)}>
<Dialog.Title className="pr-7 text-[16px] font-bold">{title}</Dialog.Title>
<Dialog.Close aria-label="关闭" className="absolute right-4 top-4 rounded-full p-1.5 text-ink-400 hover:bg-canvas"><X size={16} /></Dialog.Close>
{children}
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
}
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