Files
knowledge-governance/web/src/SourceManagement.tsx
T
姚章浩 7448d130ec
build / build (push) Successful in 1m13s
feat(settings): 汇总全部数据源配置操作审计
2026-10-27 10:42:30 +08:00

434 lines
15 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 './SourceManagement.css'
import { useEffect, useState } from 'react'
import { archiveSourceConnection, fetchSourceConnectionList, fetchSourceSettingsRevisions } from './sourceConnections'
import { useOptionalAuth } from './auth'
import type { SourceConnectionListItem } from './sourceConnections'
import { fetchSourceAudit, sourceAuditActions } from './sourceSettingsAudit'
import type { SourceAuditItem } from './sourceSettingsAudit'
import { configuredInterval, saveSourceRefresh } from './sourceRefreshPolicy'
const types: Record<string, string> = {
dingtalk: '钉钉知识库',
pp: 'PP 资料下载中心',
alist: 'AList 文件源',
manual: '本地手工导入',
}
const choices = [
{ value: 0, label: '仅手动刷新' },
{ value: 3600, label: '每小时' },
{ value: 21600, label: '每6小时' },
{ value: 86400, label: '每24小时' },
]
const errorText = (error: unknown) => (error instanceof Error ? error.message : '操作失败,请重试')
export function DingtalkAccountStatus() {
const [status, setStatus] = useState('读取中…')
const [expires, setExpires] = useState('')
useEffect(() => {
const controller = new AbortController()
void fetch('/api/v1/dingtalk-spaces/credential-status', {
headers: { Accept: 'application/json' },
signal: controller.signal,
})
.then(async (response) => {
if (!response.ok) throw new Error('读取失败')
const value = await response.json()
const data = value.data
if (!data || typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean')
throw new Error('状态格式错误')
if (controller.signal.aborted) return
setStatus(!data.authenticated ? '未登录' : data.refresh_token_valid ? '已登录' : '凭证需更新')
setExpires(data.authenticated && typeof data.refresh_expires_at === 'string' ? data.refresh_expires_at : '')
})
.catch(() => {
if (!controller.signal.aborted) setStatus('状态读取失败')
})
return () => controller.abort()
}, [])
return (
<div className="source-account" role="status">
<span>DWS 凭证 · {status}</span>
{expires ? (
<small> · 续期凭证有效期至 {new Date(expires).toLocaleString('zh-CN', { hour12: false })}</small>
) : null}
<div>
<small>仅显示本地凭证状态,不检测目录权限或业务接口。</small>
</div>
</div>
)
}
export function SourceSettingsCard({
connection,
onSourcesChanged,
}: {
connection: SourceConnectionListItem
onSourcesChanged: () => void
}) {
const [open, setOpen] = useState(false)
const [confirm, setConfirm] = useState(false)
const [confirmRemove, setConfirmRemove] = useState(false)
const isAdmin = useOptionalAuth()?.identity?.role === 'admin'
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState('')
const [error, setError] = useState('')
const toggle = async () => {
setBusy(true)
setError('')
setMessage('')
try {
await saveSourceRefresh(connection, !connection.enabled)
setMessage(connection.enabled ? '已暂停自动刷新;已有知识不受影响。' : '已恢复刷新调度;仅手动策略不会自动扫描。')
setConfirm(false)
onSourcesChanged()
} catch (cause) {
setError(errorText(cause))
} finally {
setBusy(false)
}
}
const remove = async () => {
if (!isAdmin || busy) return
setBusy(true)
setError('')
try {
await archiveSourceConnection(connection.id)
setConfirmRemove(false)
onSourcesChanged()
} catch (cause) {
setError(errorText(cause))
} finally {
setBusy(false)
}
}
const manual = connection.source_type === 'manual'
return (
<article className="settings-source-row">
<div className="settings-source-name">
<strong>{connection.name}</strong>
<span>{types[connection.source_type] ?? connection.source_type}</span>
</div>
<div className="settings-source-status">
<span className={connection.enabled ? 'source-enabled' : 'source-disabled'}>
{manual
? '手工来源'
: !connection.enabled
? '自动刷新已暂停'
: connection.next_refresh_at
? '自动刷新中'
: '仅手动刷新'}
</span>
</div>
{!manual || isAdmin ? (
<button
className="secondary source-more"
aria-expanded={open}
aria-controls={`source-options-${connection.id}`}
onClick={() => setOpen(!open)}
>
{open ? '收起' : '更多'}
</button>
) : null}
{open ? (
<div className="source-schedule-form" id={`source-options-${connection.id}`}>
{!manual ? (
<button
className={connection.enabled ? 'danger' : 'secondary'}
disabled={busy}
onClick={() => (connection.enabled ? setConfirm(true) : void toggle())}
>
{busy ? '处理中…' : connection.enabled ? '暂停自动刷新' : '恢复自动刷新'}
</button>
) : null}
{isAdmin ? (
<button
className="danger"
disabled={busy}
onClick={() => {
setError('')
setConfirmRemove(true)
}}
>
移除连接
</button>
) : null}
<small>仅管理平台连接,不删除源端文件或已入库知识。</small>
</div>
) : null}
{message ? (
<p role="status" className="success-message">
{message}
</p>
) : null}
{error ? (
<p role="alert" className="error-message">
{error}
</p>
) : null}
{confirmRemove ? (
<div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="移除连接">
<div className="modal-card">
<h3>移除「{connection.name}」的连接?</h3>
<p>移除后将不再展示该来源,也不再安排新的自动扫描。</p>
<p>
<strong>源端文件和已入库知识不会删除,历史记录保留。</strong>
</p>
{error ? (
<p role="alert" className="error-message">
{error}
</p>
) : null}
<div className="modal-actions">
<button className="secondary" disabled={busy} onClick={() => setConfirmRemove(false)}>
取消
</button>
<button className="danger" disabled={busy} onClick={() => void remove()}>
{busy ? '移除中…' : '确认移除'}
</button>
</div>
</div>
</div>
) : null}
{confirm ? (
<div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="暂停自动刷新">
<div className="modal-card">
<h3>暂停「{connection.name}」自动刷新?</h3>
<p>停止新的自动扫描任务入队,不取消已运行任务。已有知识、目录快照和标注均保留。</p>
<div className="modal-actions">
<button disabled={busy} className="danger" onClick={() => void toggle()}>
确认暂停
</button>
<button disabled={busy} className="secondary" onClick={() => setConfirm(false)}>
取消
</button>
</div>
</div>
</div>
) : null}
</article>
)
}
export function SourceManagementDetails({
connections,
onSourcesChanged,
}: {
connections: SourceConnectionListItem[]
onSourcesChanged: () => void
}) {
const [policyOpen, setPolicyOpen] = useState(false)
const [auditOpen, setAuditOpen] = useState(false)
return (
<div className="source-management-details">
<details onToggle={(event) => setPolicyOpen(event.currentTarget.open)}>
<summary>刷新设置</summary>
{policyOpen ? <SourceRefreshPolicy connections={connections} onSourcesChanged={onSourcesChanged} /> : null}
</details>
<details onToggle={(event) => setAuditOpen(event.currentTarget.open)}>
<summary>数据源设置审计</summary>
{auditOpen ? <SourceSettingsAudit connections={connections} /> : null}
</details>
</div>
)
}
export function SourceRefreshPolicy({
connections,
onSourcesChanged,
}: {
connections: SourceConnectionListItem[]
onSourcesChanged: () => void
}) {
const [interval, setInterval] = useState<number | null>(null)
const [summary, setSummary] = useState('读取当前策略…')
const [busy, setBusy] = useState(false)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [result, setResult] = useState('')
useEffect(() => {
let cancelled = false
setLoading(true)
setError('')
const rows = connections.filter((item) => item.source_type !== 'manual')
void Promise.all(rows.map(async (row) => configuredInterval(row, await fetchSourceSettingsRevisions(row.id))))
.then((values) => {
if (cancelled) return
const unique = [...new Set(values)]
setInterval(unique.length === 1 ? unique[0] : null)
setSummary(
!values.length
? '尚无在线来源'
: unique.length === 1
? `当前策略:${choices.find((c) => c.value === unique[0])?.label ?? `每 ${unique[0]} 秒`}`
: '当前来源策略不一致,请选择统一周期。'
)
})
.catch((cause) => {
if (!cancelled) setError(errorText(cause))
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [connections])
const save = async () => {
if (interval === null) return
setBusy(true)
setError('')
setResult('')
let completed = 0
const failed: string[] = []
try {
const rows = (await fetchSourceConnectionList()).filter((row) => row.source_type !== 'manual')
for (const row of rows) {
try {
await saveSourceRefresh(row, row.enabled, interval)
completed++
} catch (cause) {
failed.push(`${row.name}:${errorText(cause)}`)
}
}
setResult(`已保存 ${completed} 个来源${failed.length ? `,失败 ${failed.length} 个` : ''}。`)
if (failed.length) setError(failed.join(';'))
onSourcesChanged()
} catch (cause) {
setError(errorText(cause))
} finally {
setBusy(false)
}
}
return (
<section className="source-policy-panel">
<h3>数据源自动刷新</h3>
<p>{summary}</p>
<p>
统一应用到当前已接入的在线来源,保留各来源的暂停状态。新增来源仍为手动刷新,需在此应用策略;不触发文件入库。
</p>
<div className="source-policy-controls">
<label>
统一刷新周期
<select
disabled={loading || busy}
value={interval ?? ''}
onChange={(event) => setInterval(Number(event.target.value))}
>
<option value="" disabled>
选择周期
</option>
{choices.map((choice) => (
<option key={choice.value} value={choice.value}>
{choice.label}
</option>
))}
</select>
</label>
<button
className="secondary"
disabled={loading || busy || interval === null || !connections.some((row) => row.source_type !== 'manual')}
onClick={() => void save()}
>
{busy ? '保存中…' : '应用到现有来源'}
</button>
</div>
{result ? <p role="status">{result}</p> : null}
{error ? (
<p role="alert" className="error-message">
{error}
</p>
) : null}
</section>
)
}
export function SourceSettingsAudit({ connections }: { connections: SourceConnectionListItem[] }) {
const [rows, setRows] = useState<SourceAuditItem[]>([])
const [total, setTotal] = useState(0)
const [offset, setOffset] = useState(0)
const [retry, setRetry] = useState(0)
const [error, setError] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
setOffset(0)
setRows([])
setTotal(0)
}, [connections])
useEffect(() => {
const controller = new AbortController()
setLoading(true)
setError('')
void fetchSourceAudit(offset, controller.signal)
.then((page) => {
if (controller.signal.aborted) return
setRows((previous) =>
offset === 0 ? page.items : [...new Map([...previous, ...page.items].map((row) => [row.id, row])).values()]
)
setTotal(page.total)
})
.catch((cause) => {
if (!controller.signal.aborted) setError(errorText(cause))
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [offset, retry, connections])
return (
<section className="settings-panel wide source-audit-panel" aria-label="数据源操作记录">
<h2>数据源设置审计</h2>
<p>全部数据源的配置操作记录,按时间倒序展示,包含已移除的连接。</p>
{rows.length ? (
<div className="source-audit-scroll">
<table className="source-audit-table">
<thead>
<tr>
<th>时间</th>
<th>操作人</th>
<th>数据源</th>
<th>操作</th>
<th>变更内容</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
<td>
<time dateTime={row.created_at}>
{new Date(row.created_at).toLocaleString('zh-CN', { hour12: false })}
</time>
</td>
<td>{row.actor || '未记录'}</td>
<td>{row.source_name}</td>
<td>{sourceAuditActions[row.action] ?? '配置操作'}</td>
<td>{row.detail}</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
{loading ? <p role="status">加载操作记录中…</p> : null}
{error ? (
<p role="alert" className="error-message">
{error}{' '}
<button className="secondary" onClick={() => setRetry((value) => value + 1)}>
重试
</button>
</p>
) : null}
{!loading && !error && !rows.length ? <p>暂无数据源配置操作记录。</p> : null}
{rows.length ? (
<p>
已展示 {rows.length} / {total} 条记录
</p>
) : null}
{!loading && !error && rows.length < total ? (
<button className="secondary" onClick={() => setOffset(offset + 100)}>
加载更多
</button>
) : null}
</section>
)
}