Files
knowledge-governance/web/src/DingtalkSourceDiscovery.tsx
T
姚章浩 2c7265efc4
build / build (push) Successful in 58s
feat(sources): 数据源配置收敛成 dws 导入 + PP 导入;「去掉来源」= 归档下架(不删数据)
主人要求:去掉入口,统一成 dws 导入与 PP 导入;其他来源连数据一起下架,之后用 dws 重新获取。

界面(web):
- 「数据源配置」只剩两块:**dws 导入(钉钉)**(按当前钉钉账号列出可访问的知识库与钉盘空间)
  与 **PP 导入**(PP 资料下载中心)。上一步加的「显示 AList/钉钉知识库来源」折叠开关删除。
- 来源卡片新增管理员可见的「去掉来源」(带确认弹窗,说明是归档下架、数据保留可恢复)。
- 侧栏文案改成"只留两个入口";发现面板标题改为「dws 导入(钉钉)」。

后端(归档语义,可逆):
- 迁移 000047:source_connections 增 archived_at / archived_by + 只覆盖未归档行的部分索引。
- store:ArchiveSourceConnection / RestoreSourceConnection(幂等;归档同时停用并清空
  next_refresh_at,避免被手工改回后立刻带着旧调度跑)。列表、目录、计划刷新(claimDue)、
  手动扫描(triggerBlock/inspect)四类查询一律排除归档行。
- 注册路径(dws 重新获取):RegisterDingtalkSpace 的 ON CONFLICT 清掉归档标记 ——
  重新登记同一个空间**原地复活同一行**,不产生重复,历史快照仍属于同一行。
- HTTP:POST /api/v1/source-connections/{id}/archive|restore(管理员专属,写意图头
  source-archive / source-restore + Idempotency-Key;404 区分"不存在"与"已是目标状态");
  openapi 同步两条契约。

验证:
- 集成测试(真 postgres):归档从列表消失但 source_items 一行不少、重复归档不漂移归档时间与人、
  未知 ID 报 ErrSourceConnectionNotFound、归档来源不能再被扫描、恢复后回到列表但保持停用;
  dws 重新登记同一空间复活同一行。
- httpapi:写意图/幂等键门禁、200/403/404/500、错误体不回显内部细节、classifyRole 管理员专属。
- 迁移护栏:000047 结构 + 四类 SQL 必须含 archived_at is null(漏一条就是入口没去掉)。
- make verify 15/15。
2026-10-14 12:36:32 +08:00

194 lines
7.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useState } from 'react'
import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession'
import { DingtalkSessionControl } from './DingtalkSessionControl'
import {
discoveryCandidates,
fetchAvailableDingtalkSources,
type AvailableDingtalkSources,
type DiscoveryCandidate,
} from './dingtalkSources'
// 「系统设置 → 数据源配置」里的数据源发现面板(管理员):
// ① 列出当前钉钉账号(dws)能看到的钉钉知识库;
// ② 列出钉盘空间(我的文件 / 组织空间);
// ③ 勾选后加入为来源(登记走既有路径,首次目录扫描自动排队);
// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。
// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。
export function DingtalkSourceDiscovery({
registeredNames,
onRegistered,
}: {
registeredNames: string[]
onRegistered: () => void
}) {
const [list, setList] = useState<AvailableDingtalkSources | null>(null)
const [loading, setLoading] = useState(false)
const [loadError, setLoadError] = useState<string | null>(null)
const [checked, setChecked] = useState<string[]>([])
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null)
const [failure, setFailure] = useState<string | null>(null)
const [loginRequired, setLoginRequired] = useState(false)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
setLoadError(null)
try {
const next = await fetchAvailableDingtalkSources(signal)
setList(next)
// 已登记的默认不再勾选:避免重复登记。
setChecked([])
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setLoadError(cause instanceof Error ? cause.message : '列举数据源失败')
setList(null)
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
const controller = new AbortController()
void load(controller.signal)
return () => controller.abort()
}, [load])
const candidates = discoveryCandidates(list, registeredNames)
const knowledgeBases = candidates.filter((item) => item.kind === 'knowledge_base')
const driveSpaces = candidates.filter((item) => item.kind === 'drive_space')
const selected = candidates.filter((item) => checked.includes(item.key))
const toggle = (key: string) =>
setChecked((current) => (current.includes(key) ? current.filter((item) => item !== key) : [...current, key]))
const submit = async (retryAfterLogin = false) => {
setBusy(true)
setFailure(null)
setMessage(null)
const added: string[] = []
const failed: string[] = []
let needLogin = false
for (const candidate of selected) {
try {
const result = await registerDingtalkSpace(candidate.url)
added.push(result.name || candidate.name)
} catch (cause) {
// 扫码会话失效:登记本身没问题,直接弹二维码,扫完自动重试剩下的。
if (cause instanceof DingtalkRequestError && cause.code === 'login_required' && !retryAfterLogin) {
needLogin = true
break
}
failed.push(`${candidate.name}:${cause instanceof Error ? cause.message : '登记失败'}`)
}
}
setBusy(false)
if (needLogin) {
setLoginRequired(true)
setFailure('钉钉扫码会话已失效:请扫码登录,登录成功后会自动继续这次登记。')
return
}
if (added.length) {
setMessage(`已加入 ${added.length} 个来源:${added.join('、')}。首次目录扫描已在后台排队。`)
onRegistered()
void load()
}
if (failed.length) setFailure(failed.join(';'))
}
const resumeAfterLogin = () => {
setLoginRequired(false)
setFailure(null)
void submit(true)
}
const renderRow = (candidate: DiscoveryCandidate) => {
const already = candidate.alreadyRegistered
return (
<li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
<label>
<input
type="checkbox"
aria-label={`选择${candidate.name}`}
checked={checked.includes(candidate.key)}
disabled={already || busy}
onChange={() => toggle(candidate.key)}
/>
<span>
<strong>{candidate.name}</strong>
<small>{candidate.detail}</small>
</span>
</label>
{already ? <span className="safe-badge">已是来源</span> : null}
</li>
)
}
return (
<section className="dingtalk-discovery" aria-label="可加入的数据源">
<div className="dingtalk-discovery-heading">
<div>
<strong>dws 导入(钉钉)</strong>
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
</div>
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>
{loading ? '正在列举…' : '刷新列表'}
</button>
</div>
{loadError ? (
<p className="error-message" role="alert">
{loadError}
</p>
) : null}
{list ? (
<div className="dingtalk-discovery-groups">
<div className="discovery-group">
<h4>知识库({knowledgeBases.length})</h4>
{list.knowledge_notice ? (
<small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small>
) : null}
{knowledgeBases.length ? (
<ul>{knowledgeBases.map(renderRow)}</ul>
) : (
<small className="empty-inline">当前账号下没有可访问的知识库。</small>
)}
</div>
<div className="discovery-group">
<h4>钉盘({driveSpaces.length})</h4>
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
{!list.drive_notice && !driveSpaces.length ? (
<small className="empty-inline">当前账号下没有可见的钉盘空间。</small>
) : null}
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
</div>
</div>
) : null}
<div className="dingtalk-discovery-actions">
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>
{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}
</button>
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
</div>
{message ? (
<p className="success-message" role="status">
{message}
</p>
) : null}
{failure ? (
<p className="error-message" role="alert">
{failure}
</p>
) : null}
{loginRequired ? (
<DingtalkSessionControl
autoStart
hideTrigger
space={selected[0]?.url}
onSuccess={resumeAfterLogin}
onClose={() => setLoginRequired(false)}
/>
) : null}
</section>
)
}