feat(settings): 集中刷新策略与账号授权并独立设置审计
build / build (push) Successful in 1m11s

This commit is contained in:
姚章浩
2026-10-27 09:28:16 +08:00
parent a55d7f454e
commit 8930ef29cd
8 changed files with 520 additions and 214 deletions
+340
View File
@@ -0,0 +1,340 @@
import './SourceManagement.css'
import { useEffect, useState } from 'react'
import { DingtalkSessionControl } from './DingtalkSessionControl'
import { fetchAvailableDingtalkSources } from './dingtalkSources'
import { fetchSourceConnectionList, fetchSourceSettingsRevisions } from './sourceConnections'
import type { SourceConnectionListItem, SourceSettingsRevision } from './sourceConnections'
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 [error, setError] = useState('')
const [revision, setRevision] = useState(0)
const [expanded, setExpanded] = useState(false)
useEffect(() => {
const controller = new AbortController()
setStatus('检查中…')
setError('')
void fetchAvailableDingtalkSources(controller.signal)
.then((data) => {
if (!controller.signal.aborted)
setStatus(data.knowledge_notice || data.drive_notice ? '已连接,部分目录受限' : '已连接')
})
.catch((cause) => {
if (!controller.signal.aborted) {
setStatus('状态暂不可用')
setError(errorText(cause))
}
})
return () => controller.abort()
}, [revision])
return (
<div className="source-account">
<button className="link" aria-expanded={expanded} onClick={() => setExpanded(!expanded)}>
钉钉账号 · {status}
</button>
{expanded ? (
<div className="source-account-detail">
<p>此账号授权由所有钉钉来源共享。</p>
{error ? <p role="alert">{error}</p> : null}
<DingtalkSessionControl triggerLabel="重新授权" onSuccess={() => setRevision((value) => value + 1)} />
<button className="link" onClick={() => setRevision((value) => value + 1)}>
重新检查
</button>
</div>
) : null}
</div>
)
}
export function SourceSettingsCard({
connection,
onSourcesChanged,
}: {
connection: SourceConnectionListItem
onSourcesChanged: () => void
}) {
const [open, setOpen] = useState(false)
const [confirm, setConfirm] = useState(false)
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 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 ? (
<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}`}>
<button
className={connection.enabled ? 'danger' : 'secondary'}
disabled={busy}
onClick={() => (connection.enabled ? setConfirm(true) : void toggle())}
>
{busy ? '处理中…' : connection.enabled ? '暂停自动刷新' : '恢复自动刷新'}
</button>
<small>仅控制自动扫描,不下架或删除已有知识。</small>
</div>
) : null}
{message ? (
<p role="status" className="success-message">
{message}
</p>
) : null}
{error ? (
<p role="alert" className="error-message">
{error}
</p>
) : 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 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 [id, setID] = useState(connections[0]?.id ?? '')
const [rows, setRows] = useState<SourceSettingsRevision[]>([])
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
useEffect(() => {
const controller = new AbortController()
setRows([])
setError('')
if (!id) return
setLoading(true)
void fetchSourceSettingsRevisions(id, controller.signal)
.then((items) => {
if (!controller.signal.aborted) setRows(items)
})
.catch((cause) => {
if (!controller.signal.aborted) setError(errorText(cause))
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [id])
return (
<section className="settings-panel wide">
<h2>数据源设置审计</h2>
<label>
数据源
<select value={id} onChange={(event) => setID(event.target.value)}>
{connections.map((row) => (
<option key={row.id} value={row.id}>
{row.name}
</option>
))}
</select>
</label>
{error ? (
<p role="alert" className="error-message">
{error}
</p>
) : loading ? (
<p>加载中…</p>
) : !rows.length ? (
<p>暂无设置变更记录。</p>
) : (
<ul className="revision-list">
{rows.map((row) => (
<li key={row.id}>
<b>修订 {row.revision_number}</b>
<span>
{row.state === 'active'
? '当前生效'
: row.state === 'retired'
? '历史版本'
: row.state === 'validated'
? '待启用'
: '草稿或失败'}
</span>
<small>
{row.created_by} · {new Date(row.created_at).toLocaleString('zh-CN')} ·{' '}
{row.enabled ? '允许自动刷新' : '已暂停'} ·{' '}
{row.refresh_interval_seconds ? `周期 ${row.refresh_interval_seconds} 秒` : '仅手动'}
</small>
</li>
))}
</ul>
)}
</section>
)
}