PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。 钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。 认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。 验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。 尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
This commit is contained in:
+29
-2
@@ -12,7 +12,20 @@ import type { DWSCredentials, DWSLogin } from './dwsLogin'
|
||||
const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : '请求失败,请重试')
|
||||
const moment = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
|
||||
export function DWSAccount() {
|
||||
export function DWSAccount({
|
||||
autoStart = false,
|
||||
onAuthorized,
|
||||
onCredentials,
|
||||
onCancel,
|
||||
}: {
|
||||
autoStart?: boolean
|
||||
onAuthorized?: (credentials: DWSCredentials) => void
|
||||
onCredentials?: (credentials: DWSCredentials) => void
|
||||
onCancel?: () => void
|
||||
} = {}) {
|
||||
const callbacks = useRef({ onAuthorized, onCredentials, onCancel })
|
||||
callbacks.current = { onAuthorized, onCredentials, onCancel }
|
||||
const startedAutomatically = useRef(false)
|
||||
const [credentials, setCredentials] = useState<DWSCredentials | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
@@ -34,7 +47,10 @@ export function DWSAccount() {
|
||||
mounted.current = true
|
||||
const controller = new AbortController()
|
||||
void fetchDWSCredentials(controller.signal)
|
||||
.then(setCredentials)
|
||||
.then((fresh) => {
|
||||
setCredentials(fresh)
|
||||
callbacks.current.onCredentials?.(fresh)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted) setError(messageOf(cause))
|
||||
})
|
||||
@@ -101,6 +117,13 @@ export function DWSAccount() {
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (autoStart && !startedAutomatically.current) {
|
||||
startedAutomatically.current = true
|
||||
void start()
|
||||
}
|
||||
}, [autoStart])
|
||||
|
||||
const close = async () => {
|
||||
const current = generation.current
|
||||
const sessionID = id.current
|
||||
@@ -110,6 +133,7 @@ export function DWSAccount() {
|
||||
++generation.current
|
||||
setOpen(false)
|
||||
setStarting(false)
|
||||
callbacks.current.onCancel?.()
|
||||
return
|
||||
}
|
||||
if (sessionID && session && dwsLoginActive(session.state)) {
|
||||
@@ -125,6 +149,7 @@ export function DWSAccount() {
|
||||
id.current = ''
|
||||
setOpen(false)
|
||||
setSession(null)
|
||||
callbacks.current.onCancel?.()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,7 +184,9 @@ export function DWSAccount() {
|
||||
if (!mounted.current || current !== generation.current) return
|
||||
setCredentials(fresh)
|
||||
setNotice('DWS 登录成功')
|
||||
callbacks.current.onCredentials?.(fresh)
|
||||
void check()
|
||||
callbacks.current.onAuthorized?.(fresh)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (mounted.current && current === generation.current) setError(`授权成功,状态刷新失败:${messageOf(cause)}`)
|
||||
|
||||
@@ -8,11 +8,18 @@ describe('DingtalkSourceDiscovery', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />
|
||||
)
|
||||
for (const text of ['dws 导入(钉钉)', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
|
||||
for (const text of ['添加数据源向导', '类型', '授权', '范围', '校验', '保存', '钉钉知识库', '钉盘']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
// 需求(2026-10-10):数据源配置这里不再做文件格式筛选——格式归目录级标注决定。
|
||||
for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则']) {
|
||||
for (const removed of [
|
||||
'文件格式筛选',
|
||||
'未勾选的一律不取件',
|
||||
'保存保留格式',
|
||||
'恢复继承上级规则',
|
||||
'扫码会话',
|
||||
'弹二维码',
|
||||
]) {
|
||||
expect(html).not.toContain(removed)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,21 +1,6 @@
|
||||
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)能看到的钉钉知识库;
|
||||
// ② 列出钉盘空间(我的文件 / 组织空间);
|
||||
// ③ 勾选后加入为来源(登记走既有路径,首次目录扫描自动排队);
|
||||
// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。
|
||||
// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。
|
||||
import { SourceWizard } from './SourceWizard'
|
||||
|
||||
// Keep historical callers on the same DWS authorization and recovery path.
|
||||
export function DingtalkSourceDiscovery({
|
||||
registeredNames,
|
||||
onRegistered,
|
||||
@@ -23,171 +8,5 @@ export function DingtalkSourceDiscovery({
|
||||
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>
|
||||
)
|
||||
return <SourceWizard registeredNames={registeredNames} ppConnected={false} onRegistered={onRegistered} initialOpen />
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
.pp-connection {
|
||||
border: 1px solid var(--border, #dce3eb);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
margin: 12px 0;
|
||||
background: var(--surface, #fff);
|
||||
}
|
||||
.pp-heading,
|
||||
.pp-actions,
|
||||
.pp-password {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.pp-heading {
|
||||
justify-content: space-between;
|
||||
}
|
||||
.pp-heading h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
.pp-state {
|
||||
color: var(--text-muted, #66758a);
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection dl {
|
||||
margin: 12px 0;
|
||||
}
|
||||
.pp-connection dl > div {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin: 6px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection dt {
|
||||
flex: 0 0 76px;
|
||||
color: var(--text-muted, #66758a);
|
||||
}
|
||||
.pp-connection dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.pp-connection form {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.pp-connection label {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection input {
|
||||
width: 100%;
|
||||
max-width: 540px;
|
||||
box-sizing: border-box;
|
||||
padding: 9px 11px;
|
||||
border: 1px solid var(--border, #cdd7e4);
|
||||
border-radius: 6px;
|
||||
background: var(--surface, #fff);
|
||||
color: inherit;
|
||||
}
|
||||
.pp-connection button {
|
||||
padding: 7px 12px;
|
||||
border: 1px solid var(--border, #cdd7e4);
|
||||
border-radius: 6px;
|
||||
background: var(--surface, #fff);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pp-connection button.primary {
|
||||
background: #2563eb;
|
||||
color: #fff;
|
||||
border-color: #2563eb;
|
||||
}
|
||||
.pp-connection button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.pp-connection [role='alert'] {
|
||||
color: #a93835;
|
||||
}
|
||||
.pp-connection [role='status'] {
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection.compact {
|
||||
margin-top: 0;
|
||||
}
|
||||
.pp-test-result {
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--border, #dce3eb);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { PPConnection } from './PPConnection'
|
||||
let root: Root, host: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
const active = {
|
||||
id: 'active-one',
|
||||
base_url: 'https://api.example.invalid',
|
||||
username: 'example',
|
||||
password_configured: true,
|
||||
}
|
||||
const view = {
|
||||
revision: 1,
|
||||
active,
|
||||
pending: null,
|
||||
observation: { state: 'valid', message: '认证有效 · 目录可读', checked_at: '2026-11-17T10:00:00Z' },
|
||||
pending_observation: null,
|
||||
}
|
||||
const json = (data: unknown) => new Response(JSON.stringify({ data }))
|
||||
const click = async (label: string) => {
|
||||
const b = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label)
|
||||
expect(b, label).toBeTruthy()
|
||||
await act(async () => b!.click())
|
||||
}
|
||||
const type = async (label: string, value: string) => {
|
||||
const input = [...host.querySelectorAll('label')]
|
||||
.find((x) => x.textContent?.startsWith(label))
|
||||
?.querySelector('input')
|
||||
expect(input, label).toBeTruthy()
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
|
||||
input!.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
beforeEach(() => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
||||
host = document.createElement('div')
|
||||
document.body.append(host)
|
||||
root = createRoot(host)
|
||||
fetcher = vi.fn(async (_p: string, init?: RequestInit) =>
|
||||
json(init?.method === 'PUT' ? { ...view, revision: 2 } : view)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
host.remove()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
describe('PP configuration editor', () => {
|
||||
it('keeps the stored password without sending a masked replacement or launching scans', async () => {
|
||||
await act(async () => root.render(<PPConnection />))
|
||||
await click('配置')
|
||||
expect(host.querySelector('input[type=password]')).toBeNull()
|
||||
await click('保存并校验')
|
||||
const writes = fetcher.mock.calls.filter(([, i]) => i?.method === 'PUT')
|
||||
expect(writes).toHaveLength(1)
|
||||
const data = JSON.parse(String(writes[0][1]?.body))
|
||||
expect(data).toEqual({ base_url: active.base_url, username: 'example', revision: 1 })
|
||||
expect(host.textContent).toContain('已保存并生效')
|
||||
expect(fetcher.mock.calls.every(([p]) => p.startsWith('/api/v1/pp-connection'))).toBe(true)
|
||||
})
|
||||
it('sends a newly entered password only on explicit replacement and clears it after save', async () => {
|
||||
await act(async () => root.render(<PPConnection />))
|
||||
await click('配置')
|
||||
await click('更新密码')
|
||||
await type('新密码', 'example-replacement')
|
||||
await click('保存并校验')
|
||||
const write = fetcher.mock.calls.find(([, i]) => i?.method === 'PUT')
|
||||
expect(JSON.parse(String(write?.[1]?.body)).password).toBe('example-replacement')
|
||||
expect(host.querySelector('input[type=password]')).toBeNull()
|
||||
expect(host.textContent).not.toContain('example-replacement')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { PPConnection } from './PPConnection'
|
||||
describe('PP connection card', () => {
|
||||
it('starts with an observation gap and exposes configuration without inventing validity', () => {
|
||||
const html = renderToStaticMarkup(<PPConnection />)
|
||||
expect(html).toContain('PP 连接')
|
||||
expect(html).toContain('读取中')
|
||||
expect(html).toContain('配置')
|
||||
expect(html).not.toContain('认证有效')
|
||||
expect(html).not.toContain('公开只读可达')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,288 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
readPPConnection,
|
||||
savePPConnection,
|
||||
testPPConnection,
|
||||
type PPDraft,
|
||||
type PPObservation,
|
||||
type PPView,
|
||||
} from './ppConnection'
|
||||
import './PPConnection.css'
|
||||
const errorText = (e: unknown) => (e instanceof Error ? e.message : '请求失败,请重试')
|
||||
const when = (s: string) => new Date(s).toLocaleString('zh-CN', { hour12: false })
|
||||
export function PPConnection({ compact = false }: { compact?: boolean }) {
|
||||
const [view, setView] = useState<PPView | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [draft, setDraft] = useState<PPDraft>({ base_url: 'https://api.dobot.cn', username: '', revision: 0 })
|
||||
const [password, setPassword] = useState('')
|
||||
const [replacing, setReplacing] = useState(false)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [tested, setTested] = useState<PPObservation | null>(null)
|
||||
const mounted = useRef(false)
|
||||
const sequence = useRef(0)
|
||||
const action = useRef<AbortController | null>(null)
|
||||
const formState = useRef({ editing: false, busy: '' })
|
||||
formState.current = { editing, busy }
|
||||
const load = useCallback(async () => {
|
||||
const current = ++sequence.current
|
||||
try {
|
||||
const next = await readPPConnection()
|
||||
if (mounted.current && sequence.current === current) {
|
||||
setView(next)
|
||||
setError('')
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted.current && sequence.current === current) setError(errorText(e))
|
||||
} finally {
|
||||
if (mounted.current && sequence.current === current) setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
void load()
|
||||
const refresh = () => {
|
||||
if (!formState.current.editing && !formState.current.busy) void load()
|
||||
}
|
||||
window.addEventListener('pp-config-updated', refresh)
|
||||
return () => {
|
||||
mounted.current = false
|
||||
sequence.current++
|
||||
action.current?.abort()
|
||||
window.removeEventListener('pp-config-updated', refresh)
|
||||
}
|
||||
}, [load])
|
||||
const open = () => {
|
||||
if (!view) return
|
||||
const source = view.pending ?? view.active
|
||||
setDraft({
|
||||
base_url: source?.base_url ?? 'https://api.dobot.cn',
|
||||
username: source?.username ?? '',
|
||||
revision: view.revision,
|
||||
...(view.pending ? { pending_id: view.pending.id } : {}),
|
||||
})
|
||||
setPassword('')
|
||||
setReplacing(false)
|
||||
setTested(null)
|
||||
setNotice('')
|
||||
setError('')
|
||||
setEditing(true)
|
||||
}
|
||||
const resetTest = () => {
|
||||
setTested(null)
|
||||
setNotice('')
|
||||
}
|
||||
const run = async (save: boolean) => {
|
||||
if (!view) return
|
||||
setBusy(save ? 'saving' : 'testing')
|
||||
setError('')
|
||||
setNotice('')
|
||||
setTested(null)
|
||||
const controller = new AbortController()
|
||||
action.current = controller
|
||||
const current = ++sequence.current
|
||||
const payload: PPDraft = editing
|
||||
? { ...draft, ...(password ? { password } : {}) }
|
||||
: {
|
||||
base_url: view.active?.base_url ?? 'https://api.dobot.cn',
|
||||
username: view.active?.username ?? '',
|
||||
revision: view.revision,
|
||||
}
|
||||
try {
|
||||
if (save) {
|
||||
const next = await savePPConnection(payload, controller.signal)
|
||||
if (!mounted.current || sequence.current !== current) return
|
||||
setView(next)
|
||||
setPassword('')
|
||||
setReplacing(false)
|
||||
setEditing(false)
|
||||
setNotice(next.pending ? '修改已保存为待验证;原生效配置保留。' : 'PP 配置已保存并生效。')
|
||||
window.dispatchEvent(new Event('pp-config-updated'))
|
||||
} else {
|
||||
const result = await testPPConnection(payload, controller.signal)
|
||||
if (!mounted.current || sequence.current !== current) return
|
||||
setTested(result)
|
||||
const next = await readPPConnection(controller.signal)
|
||||
if (mounted.current && sequence.current === current) setView(next)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted && mounted.current && sequence.current === current) {
|
||||
setError(errorText(e))
|
||||
try {
|
||||
const next = await readPPConnection(controller.signal)
|
||||
if (mounted.current && sequence.current === current) setView(next)
|
||||
} catch {
|
||||
/* Keep the last observation with the visible error. */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current && sequence.current === current) setBusy('')
|
||||
}
|
||||
}
|
||||
const observation = view?.observation
|
||||
const status = loading
|
||||
? '读取中…'
|
||||
: error && !view
|
||||
? '状态读取失败'
|
||||
: !view?.active
|
||||
? '未配置'
|
||||
: !observation
|
||||
? '未检查'
|
||||
: observation.state === 'valid'
|
||||
? '认证有效 · 目录可读'
|
||||
: observation.message
|
||||
return (
|
||||
<section className={`pp-connection${compact ? ' compact' : ''}`} aria-label="PP 连接">
|
||||
<div className="pp-heading">
|
||||
<h3>PP 连接</h3>
|
||||
<span className={observation?.state === 'valid' ? 'safe-badge' : 'pp-state'}>{status}</span>
|
||||
</div>
|
||||
{!editing && (
|
||||
<>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>API 地址</dt>
|
||||
<dd>{view?.active?.base_url || '未配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>账号</dt>
|
||||
<dd>{view?.active?.username || '未配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>密码</dt>
|
||||
<dd>{view?.active?.password_configured ? '已配置' : '未配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>最近检查</dt>
|
||||
<dd>{observation ? `${when(observation.checked_at)} · ${observation.message}` : '尚无检查记录'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{observation?.previous && (
|
||||
<p className="hint">
|
||||
上次结果(旧):{observation.previous.message} · {when(observation.previous.checked_at)}
|
||||
</p>
|
||||
)}
|
||||
{view?.pending && (
|
||||
<p className="hint">存在待验证修改;{view.active ? '当前仍使用原生效配置。' : '尚无生效配置。'}</p>
|
||||
)}
|
||||
<div className="pp-actions">
|
||||
<button type="button" disabled={!view || !!busy} onClick={open}>
|
||||
配置
|
||||
</button>
|
||||
<button type="button" disabled={!view || !!busy || !view.active} onClick={() => void run(false)}>
|
||||
{busy === 'testing' ? '正在检查…' : '测试连接'}
|
||||
</button>
|
||||
{error && (
|
||||
<button type="button" disabled={!!busy} onClick={() => void load()}>
|
||||
刷新状态
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{editing && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void run(true)
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
API 地址
|
||||
<input
|
||||
type="url"
|
||||
value={draft.base_url}
|
||||
disabled={!!busy}
|
||||
autoComplete="off"
|
||||
onChange={(e) => {
|
||||
setDraft({ ...draft, base_url: e.target.value })
|
||||
resetTest()
|
||||
}}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
账号
|
||||
<input
|
||||
value={draft.username}
|
||||
disabled={!!busy}
|
||||
autoComplete="off"
|
||||
onChange={(e) => {
|
||||
setDraft({ ...draft, username: e.target.value })
|
||||
resetTest()
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="pp-password">
|
||||
<span>密码:{(view?.pending ?? view?.active)?.password_configured ? '已配置' : '未配置'}</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!!busy}
|
||||
onClick={() => {
|
||||
setReplacing(!replacing)
|
||||
setPassword('')
|
||||
resetTest()
|
||||
}}
|
||||
>
|
||||
{replacing ? '保留已存密码' : '更新密码'}
|
||||
</button>
|
||||
</div>
|
||||
{replacing && (
|
||||
<label>
|
||||
新密码
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
disabled={!!busy}
|
||||
placeholder="留空保留已存密码"
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value)
|
||||
resetTest()
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<div className="pp-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!!busy}
|
||||
onClick={() => {
|
||||
setEditing(false)
|
||||
setPassword('')
|
||||
setTested(null)
|
||||
setError('')
|
||||
}}
|
||||
>
|
||||
取消修改
|
||||
</button>
|
||||
<button type="button" disabled={!!busy} onClick={() => void run(false)}>
|
||||
{busy === 'testing' ? '正在检查…' : '测试连接'}
|
||||
</button>
|
||||
<button type="submit" className="primary" disabled={!!busy}>
|
||||
{busy === 'saving' ? '正在校验…' : '保存并校验'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{tested && (
|
||||
<p role="status" className="pp-test-result">
|
||||
{editing ? '未保存配置测试:' : '当前配置检查:'}
|
||||
{tested.message}({when(tested.checked_at)})
|
||||
</p>
|
||||
)}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{error && (
|
||||
<p role="alert">
|
||||
{error}
|
||||
{view && ';上次读取的配置与检查结果仍保留。'}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function PPAuthorizationStep() {
|
||||
return <PPConnection compact />
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SourceWizard } from './SourceWizard'
|
||||
let root: Root, host: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
const reply = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status })
|
||||
const account = {
|
||||
authenticated: true,
|
||||
refresh_token_valid: true,
|
||||
status_known: true,
|
||||
identity: 'account-a',
|
||||
corp_name: '示例组织',
|
||||
user_name: '示例账号',
|
||||
}
|
||||
const spaces = {
|
||||
knowledge_bases: [
|
||||
{ name: '资料一', space_id: 'space-one', url: 'https://alidocs.dingtalk.com/i/spaces/space-one/overview' },
|
||||
{ name: '资料二', space_id: 'space-two', url: 'https://alidocs.dingtalk.com/i/spaces/space-two/overview' },
|
||||
],
|
||||
drive_spaces: [],
|
||||
fetched_at: '2026-11-17T10:00:00Z',
|
||||
}
|
||||
const click = async (text: string) => {
|
||||
const b = [...host.querySelectorAll('button')].find(
|
||||
(x) => x.textContent?.trim() === text || x.textContent?.trim().includes(text)
|
||||
)
|
||||
expect(b, text).toBeTruthy()
|
||||
await act(async () => b!.click())
|
||||
}
|
||||
const flush = async () => {
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
beforeEach(() => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
||||
vi.useFakeTimers()
|
||||
host = document.createElement('div')
|
||||
document.body.append(host)
|
||||
root = createRoot(host)
|
||||
fetcher = vi.fn(async (path: string) => {
|
||||
if (path.endsWith('credential-status')) return reply(account)
|
||||
if (path.endsWith('/available')) return reply(spaces)
|
||||
if (path.endsWith('/validate')) return reply({ valid: true, count: 2, checked_at: '2026-11-17T10:00:00Z' })
|
||||
throw new Error('unexpected ' + path)
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
host.remove()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
async function selectTwo() {
|
||||
await act(async () => root.render(<SourceWizard registeredNames={[]} ppConnected onRegistered={() => {}} />))
|
||||
await click('+ 添加数据源')
|
||||
await click('钉钉知识库')
|
||||
await click('下一步')
|
||||
await flush()
|
||||
await click('下一步')
|
||||
await act(async () => {
|
||||
for (const box of host.querySelectorAll<HTMLInputElement>('input[type=checkbox]')) box.click()
|
||||
})
|
||||
await click('下一步')
|
||||
await flush()
|
||||
}
|
||||
describe('DWS source wizard', () => {
|
||||
it('uses shared DWS identity and really validates the selected spaces', async () => {
|
||||
await selectTwo()
|
||||
expect(host.textContent).not.toContain('扫码会话')
|
||||
expect(fetcher.mock.calls.some(([p]) => String(p).endsWith('/validate'))).toBe(true)
|
||||
expect(host.textContent).toContain('校验通过')
|
||||
})
|
||||
it('resumes only the unregistered space after inline DWS authorization', async () => {
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
let tries = 0
|
||||
fetcher.mockImplementation(async (path: string, init?: RequestInit) => {
|
||||
if (path === '/api/v1/dingtalk-spaces') {
|
||||
const url = JSON.parse(String(init?.body)).url
|
||||
if (url.includes('space-two') && ++tries === 1)
|
||||
return new Response(JSON.stringify({ error: 'dws_login_required', hint: '授权已失效' }), { status: 401 })
|
||||
return reply(
|
||||
{
|
||||
connection_id: url.includes('space-one') ? 'one' : 'two',
|
||||
name: url.includes('space-one') ? '资料一' : '资料二',
|
||||
first_scan_queued: true,
|
||||
},
|
||||
201
|
||||
)
|
||||
}
|
||||
if (path === '/api/v1/dws-login')
|
||||
return reply(
|
||||
{
|
||||
id: 'a'.repeat(32),
|
||||
state: 'waiting',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
verification_url: 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=EXAMPLE',
|
||||
user_code: 'EXAMPLE',
|
||||
},
|
||||
202
|
||||
)
|
||||
if (path.startsWith('/api/v1/dws-login/'))
|
||||
return reply({
|
||||
id: 'a'.repeat(32),
|
||||
state: init?.method === 'DELETE' ? 'cancelled' : 'succeeded',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
verification_url: '',
|
||||
user_code: '',
|
||||
})
|
||||
return fallback(path, init)
|
||||
})
|
||||
await selectTwo()
|
||||
await click('保存并首次扫描')
|
||||
await flush()
|
||||
expect(host.textContent).toContain('DWS 登录授权')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(1500))
|
||||
await flush()
|
||||
const calls = fetcher.mock.calls.filter(([p]) => p === '/api/v1/dingtalk-spaces')
|
||||
expect(calls.filter(([, i]) => String((i as RequestInit).body).includes('space-one'))).toHaveLength(1)
|
||||
const second = calls.filter(([, i]) => String((i as RequestInit).body).includes('space-two'))
|
||||
expect(second).toHaveLength(2)
|
||||
expect((second[0][1] as RequestInit).headers).toEqual((second[1][1] as RequestInit).headers)
|
||||
expect(fetcher.mock.calls.some(([p]) => String(p).includes('/dingtalk-session'))).toBe(false)
|
||||
})
|
||||
|
||||
it('requires a new selection when authorization changes the account', async () => {
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
let authorized = false
|
||||
fetcher.mockImplementation(async (path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('credential-status'))
|
||||
return reply({ ...account, identity: authorized ? 'account-b' : 'account-a' })
|
||||
if (path === '/api/v1/dingtalk-spaces')
|
||||
return new Response(JSON.stringify({ error: 'dws_login_required', hint: '授权失效' }), { status: 401 })
|
||||
if (path === '/api/v1/dws-login')
|
||||
return reply(
|
||||
{
|
||||
id: 'b'.repeat(32),
|
||||
state: 'waiting',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
verification_url: 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=EXAMPLE',
|
||||
user_code: 'EXAMPLE',
|
||||
},
|
||||
202
|
||||
)
|
||||
if (path.startsWith('/api/v1/dws-login/')) {
|
||||
authorized = true
|
||||
return reply({
|
||||
id: 'b'.repeat(32),
|
||||
state: 'succeeded',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
verification_url: '',
|
||||
user_code: '',
|
||||
})
|
||||
}
|
||||
return fallback(path, init)
|
||||
})
|
||||
await selectTwo()
|
||||
await click('保存并首次扫描')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(1500))
|
||||
await flush()
|
||||
expect(host.textContent).toContain('账号或组织已变化,请重新确认来源')
|
||||
expect(fetcher.mock.calls.filter(([p]) => p === '/api/v1/dingtalk-spaces')).toHaveLength(1)
|
||||
expect([...host.querySelectorAll<HTMLInputElement>('input[type=checkbox]')].every((x) => !x.checked)).toBe(true)
|
||||
})
|
||||
})
|
||||
+340
-196
@@ -1,147 +1,294 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { DWSAccount } from './DWSAccount'
|
||||
import { PPAuthorizationStep } from './PPConnection'
|
||||
import { DingtalkRequestError, registerDingtalkSpace, type RegisteredDingtalkSpace } from './dingtalkSession'
|
||||
import { fetchDWSCredentials, type DWSCredentials } from './dwsLogin'
|
||||
import {
|
||||
discoveryCandidates,
|
||||
fetchAvailableDingtalkSources,
|
||||
validateDingtalkSources,
|
||||
type AvailableDingtalkSources,
|
||||
type DiscoveryCandidate,
|
||||
} from './dingtalkSources'
|
||||
import { newOperationID } from './operationKey'
|
||||
import './sourceWizard.css'
|
||||
|
||||
// 「系统设置 → 数据源配置」的统一添加向导。
|
||||
// 一个入口、五步固定:类型 → 授权 → 范围 → 校验 → 保存。
|
||||
// 类型只决定「候选从哪来」与「授权怎么说明」,版式和动作词完全一致。
|
||||
// 对内/对外不在这里配置:策略只在「来源与目录」标注。
|
||||
// 单篇钉钉文档/表格不进这里——把链接发给我,我用 dws 导入。
|
||||
|
||||
type SourceKind = 'wiki' | 'drive' | 'pp'
|
||||
|
||||
const kinds: { key: SourceKind; title: string; detail: string; icon: string }[] = [
|
||||
{ key: 'wiki', title: '钉钉知识库', detail: '组织 / 我的知识库', icon: '库' },
|
||||
{ key: 'drive', title: '钉盘', detail: '我的文件 / 组织空间', icon: '盘' },
|
||||
{ key: 'pp', title: 'Partner Portal', detail: '公开只读资料中心', icon: '↧' },
|
||||
const kinds = [
|
||||
{ key: 'wiki' as const, title: '钉钉知识库', detail: '组织 / 我的知识库', icon: '库' },
|
||||
{ key: 'drive' as const, title: '钉盘', detail: '我的文件 / 组织空间', icon: '盘' },
|
||||
{ key: 'pp' as const, title: 'Partner Portal', detail: '资料中心 · 只读访问', icon: '↧' },
|
||||
]
|
||||
|
||||
const steps = ['类型', '授权', '范围', '校验', '保存'] as const
|
||||
const steps = ['类型', '授权', '范围', '校验', '保存']
|
||||
const text = (e: unknown) => (e instanceof Error ? e.message : '请求失败,请重试')
|
||||
const needsLogin = (e: unknown) =>
|
||||
e instanceof DingtalkRequestError && ['dws_login_required', 'login_required'].includes(e.code)
|
||||
const validAccount = (c: DWSCredentials | null) =>
|
||||
Boolean(c?.status_known && (c.authenticated || c.refresh_token_valid))
|
||||
|
||||
export function SourceWizard({
|
||||
registeredNames,
|
||||
ppConnected,
|
||||
onRegistered,
|
||||
initialOpen = false,
|
||||
}: {
|
||||
registeredNames: string[]
|
||||
// PP 是一个门户一条来源:已接入时向导只做说明,不重复登记。
|
||||
ppConnected: boolean
|
||||
onRegistered: () => void
|
||||
initialOpen?: boolean
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [open, setOpen] = useState(initialOpen)
|
||||
const [step, setStep] = useState(0)
|
||||
const [kind, setKind] = useState<SourceKind | null>(null)
|
||||
const [list, setList] = useState<AvailableDingtalkSources | null>(null)
|
||||
const [credentials, setCredentials] = useState<DWSCredentials | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [checked, setChecked] = useState<string[]>([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const [loginRequired, setLoginRequired] = useState(false)
|
||||
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
setLoading(true)
|
||||
setLoadError(null)
|
||||
try {
|
||||
setList(await fetchAvailableDingtalkSources(signal))
|
||||
} catch (cause) {
|
||||
if (cause instanceof DOMException && cause.name === 'AbortError') return
|
||||
setLoadError(cause instanceof Error ? cause.message : '列举数据源失败')
|
||||
setList(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
const [failure, setFailure] = useState('')
|
||||
const [message, setMessage] = useState('')
|
||||
const [authNeeded, setAuthNeeded] = useState(false)
|
||||
const [autoAuthorize, setAutoAuthorize] = useState(false)
|
||||
const [verified, setVerified] = useState('')
|
||||
const alive = useRef(true)
|
||||
const epoch = useRef(0)
|
||||
const completed = useRef(new Map<string, RegisteredDingtalkSpace>())
|
||||
const pending = useRef<DiscoveryCandidate[]>([])
|
||||
const operationIDs = useRef(new Map<string, string>())
|
||||
const identity = useRef('')
|
||||
const submitted = useRef(false)
|
||||
const recovering = useRef(false)
|
||||
const callbacks = useRef({ onRegistered })
|
||||
callbacks.current = { onRegistered }
|
||||
useEffect(() => {
|
||||
alive.current = true
|
||||
return () => {
|
||||
alive.current = false
|
||||
epoch.current++
|
||||
}
|
||||
}, [])
|
||||
const load = useCallback(async () => {
|
||||
const current = ++epoch.current
|
||||
setLoading(true)
|
||||
setLoadError('')
|
||||
try {
|
||||
const account = await fetchDWSCredentials()
|
||||
if (!alive.current || current !== epoch.current) return null
|
||||
setCredentials(account)
|
||||
if (identity.current && account.identity && identity.current !== account.identity && !submitted.current) {
|
||||
setChecked([])
|
||||
setVerified('')
|
||||
setFailure('DWS 账号或组织已变化,请重新确认来源。')
|
||||
identity.current = account.identity
|
||||
}
|
||||
if (!identity.current && account.identity) identity.current = account.identity
|
||||
if (!validAccount(account)) {
|
||||
setList(null)
|
||||
setAuthNeeded(true)
|
||||
setLoadError('请先完成 DWS 登录授权')
|
||||
return null
|
||||
}
|
||||
const result = await fetchAvailableDingtalkSources()
|
||||
if (!alive.current || current !== epoch.current) return null
|
||||
setList(result)
|
||||
return result
|
||||
} catch (e) {
|
||||
if (alive.current && current === epoch.current) {
|
||||
setList(null)
|
||||
setLoadError(text(e))
|
||||
if (needsLogin(e)) setAuthNeeded(true)
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
if (alive.current && current === epoch.current) setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || (kind !== 'wiki' && kind !== 'drive')) return
|
||||
const controller = new AbortController()
|
||||
void load(controller.signal)
|
||||
return () => controller.abort()
|
||||
if (open && (kind === 'wiki' || kind === 'drive')) void load()
|
||||
return () => {
|
||||
epoch.current++
|
||||
}
|
||||
}, [open, kind, load])
|
||||
|
||||
const candidates = useMemo(() => discoveryCandidates(list, registeredNames), [list, registeredNames])
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
candidates.filter((item) =>
|
||||
kind === 'wiki' ? item.kind === 'knowledge_base' : kind === 'drive' ? item.kind === 'drive_space' : false
|
||||
),
|
||||
[candidates, kind]
|
||||
const visible = candidates.filter((x) =>
|
||||
kind === 'wiki' ? x.kind === 'knowledge_base' : kind === 'drive' ? x.kind === 'drive_space' : false
|
||||
)
|
||||
const selected = visible.filter((item) => checked.includes(item.key))
|
||||
|
||||
const selected = visible.filter((x) => checked.includes(x.key) && !x.alreadyRegistered)
|
||||
const close = () => {
|
||||
if (busy) return
|
||||
epoch.current++
|
||||
setOpen(false)
|
||||
setStep(0)
|
||||
setKind(null)
|
||||
setChecked([])
|
||||
setFailure(null)
|
||||
setMessage(null)
|
||||
setLoginRequired(false)
|
||||
setFailure('')
|
||||
setMessage('')
|
||||
setAuthNeeded(false)
|
||||
setAutoAuthorize(false)
|
||||
setVerified('')
|
||||
identity.current = ''
|
||||
submitted.current = false
|
||||
pending.current = []
|
||||
completed.current.clear()
|
||||
operationIDs.current.clear()
|
||||
}
|
||||
|
||||
const toggle = (key: string) =>
|
||||
setChecked((current) => (current.includes(key) ? current.filter((item) => item !== key) : [...current, key]))
|
||||
|
||||
const submit = async (retryAfterLogin = false) => {
|
||||
const report = () => {
|
||||
const values = [...completed.current.values()]
|
||||
const queued = values.filter((x) => x.first_scan_queued === true).length
|
||||
setMessage(
|
||||
values.length
|
||||
? `已加入 ${values.length} 个来源:${values.map((x) => x.name).join('、')}。${queued ? `首次目录扫描已入队 ${queued} 项。` : ''}${values.some((x) => x.first_scan_queued === false) ? '部分首次扫描尚未入队,请检查来源状态。' : ''}`
|
||||
: ''
|
||||
)
|
||||
}
|
||||
const submit = async (items: DiscoveryCandidate[] = selected) => {
|
||||
if (busy && !recovering.current) return
|
||||
setBusy(true)
|
||||
setFailure(null)
|
||||
const added: string[] = []
|
||||
const failed: string[] = []
|
||||
let needLogin = false
|
||||
for (const candidate of selected) {
|
||||
setFailure('')
|
||||
submitted.current = true
|
||||
pending.current = items.filter((x) => !completed.current.has(x.key))
|
||||
const remaining = [...pending.current]
|
||||
let changed = false
|
||||
for (const candidate of remaining) {
|
||||
if (!alive.current) break
|
||||
let operation = operationIDs.current.get(candidate.key)
|
||||
if (!operation) {
|
||||
operation = newOperationID()
|
||||
operationIDs.current.set(candidate.key, operation)
|
||||
}
|
||||
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
|
||||
const result = await registerDingtalkSpace(candidate.url, operation, identity.current || undefined)
|
||||
if (!alive.current) return
|
||||
completed.current.set(candidate.key, result)
|
||||
pending.current = pending.current.filter((x) => x.key !== candidate.key)
|
||||
changed = true
|
||||
} catch (e) {
|
||||
if (!alive.current) return
|
||||
if (needsLogin(e)) {
|
||||
setAuthNeeded(true)
|
||||
setAutoAuthorize(!recovering.current)
|
||||
setFailure('DWS 授权已失效;重新授权后继续剩余来源。')
|
||||
setBusy(false)
|
||||
report()
|
||||
if (changed) callbacks.current.onRegistered()
|
||||
return
|
||||
}
|
||||
failed.push(`${candidate.name}:${cause instanceof Error ? cause.message : '登记失败'}`)
|
||||
if (e instanceof DingtalkRequestError && e.code === 'dws_identity_changed') {
|
||||
pending.current = []
|
||||
submitted.current = false
|
||||
setChecked([])
|
||||
setStep(2)
|
||||
setVerified('')
|
||||
setFailure('DWS 账号或组织已变化,请重新确认来源。')
|
||||
void load()
|
||||
} else setFailure(`${candidate.name}:${text(e)}。已成功项保留,可重试剩余来源。`)
|
||||
setBusy(false)
|
||||
report()
|
||||
if (changed) callbacks.current.onRegistered()
|
||||
return
|
||||
}
|
||||
}
|
||||
setBusy(false)
|
||||
if (needLogin) {
|
||||
setLoginRequired(true)
|
||||
setFailure('钉钉扫码会话已失效:扫码后会自动继续这次添加。')
|
||||
if (alive.current) {
|
||||
setBusy(false)
|
||||
setAuthNeeded(false)
|
||||
setAutoAuthorize(false)
|
||||
submitted.current = false
|
||||
report()
|
||||
if (changed) callbacks.current.onRegistered()
|
||||
}
|
||||
}
|
||||
const authorized = async (account: DWSCredentials) => {
|
||||
if (!alive.current) return
|
||||
setCredentials(account)
|
||||
setAuthNeeded(false)
|
||||
setAutoAuthorize(false)
|
||||
const changed = Boolean(identity.current && account.identity !== identity.current)
|
||||
if (!identity.current && account.identity) identity.current = account.identity
|
||||
if (changed) {
|
||||
identity.current = account.identity || ''
|
||||
pending.current = []
|
||||
submitted.current = false
|
||||
completed.current.clear()
|
||||
operationIDs.current.clear()
|
||||
setChecked([])
|
||||
setVerified('')
|
||||
setStep(2)
|
||||
setFailure('DWS 账号或组织已变化,请重新确认来源。')
|
||||
await load()
|
||||
return
|
||||
}
|
||||
if (added.length) {
|
||||
setMessage(`已加入 ${added.length} 个来源:${added.join('、')}。首次目录扫描已在后台排队。`)
|
||||
onRegistered()
|
||||
void load()
|
||||
const result = await load()
|
||||
if (!result || !alive.current) return
|
||||
if (submitted.current && pending.current.length) {
|
||||
if (!identity.current || !account.identity) {
|
||||
pending.current = []
|
||||
submitted.current = false
|
||||
setChecked([])
|
||||
setStep(2)
|
||||
setVerified('')
|
||||
setFailure('无法确认授权前后为同一账号,请重新选择来源。')
|
||||
return
|
||||
}
|
||||
const available = new Set(discoveryCandidates(result, []).map((x) => x.key))
|
||||
if (pending.current.some((x) => !available.has(x.key))) {
|
||||
setFailure('重新授权后部分来源已不可见,请重新确认范围。')
|
||||
setStep(2)
|
||||
setVerified('')
|
||||
submitted.current = false
|
||||
return
|
||||
}
|
||||
recovering.current = true
|
||||
await submit([...pending.current])
|
||||
recovering.current = false
|
||||
}
|
||||
if (failed.length) setFailure(failed.join(';'))
|
||||
}
|
||||
|
||||
const canAdvance =
|
||||
(step === 0 && kind !== null) ||
|
||||
(step === 1 && kind !== null) ||
|
||||
(step === 2 && (kind === 'pp' || selected.length > 0)) ||
|
||||
(step === 3 && (kind === 'pp' || selected.length > 0))
|
||||
|
||||
const verify = async () => {
|
||||
if (!selected.length) return
|
||||
const current = epoch.current
|
||||
setStep(3)
|
||||
setBusy(true)
|
||||
setVerified('')
|
||||
setFailure('')
|
||||
try {
|
||||
const result = await validateDingtalkSources(
|
||||
selected.map((x) => x.url),
|
||||
identity.current || undefined
|
||||
)
|
||||
if (alive.current && current === epoch.current) setVerified(result.checked_at)
|
||||
} catch (e) {
|
||||
if (alive.current && current === epoch.current) {
|
||||
setFailure(text(e))
|
||||
if (needsLogin(e)) setAuthNeeded(true)
|
||||
}
|
||||
} finally {
|
||||
if (alive.current && current === epoch.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
const authPanel = (
|
||||
<DWSAccount
|
||||
autoStart={autoAuthorize}
|
||||
onCredentials={(c) => {
|
||||
setCredentials(c)
|
||||
if (!identity.current && c.identity) identity.current = c.identity
|
||||
}}
|
||||
onAuthorized={(c) => void authorized(c)}
|
||||
onCancel={() => {
|
||||
setAutoAuthorize(false)
|
||||
setFailure('授权已取消,选择已保留。')
|
||||
}}
|
||||
/>
|
||||
)
|
||||
const scopeNotice = kind === 'wiki' ? list?.knowledge_notice : list?.drive_notice
|
||||
return (
|
||||
<section className="source-wizard" aria-label="添加数据源">
|
||||
<div className="source-wizard-bar">
|
||||
<div>
|
||||
<h3>数据源</h3>
|
||||
</div>
|
||||
<h3>数据源</h3>
|
||||
<button type="button" className="source-wizard-open" onClick={() => setOpen(true)}>
|
||||
+ 添加数据源
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{open ? (
|
||||
{open && (
|
||||
<div className="source-wizard-panel" role="dialog" aria-label="添加数据源向导">
|
||||
<ol className="source-wizard-steps">
|
||||
{steps.map((label, index) => (
|
||||
@@ -150,8 +297,7 @@ export function SourceWizard({
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
{step === 0 ? (
|
||||
{step === 0 && (
|
||||
<div className="source-wizard-types">
|
||||
{kinds.map((item) => (
|
||||
<button
|
||||
@@ -161,6 +307,9 @@ export function SourceWizard({
|
||||
onClick={() => {
|
||||
setKind(item.key)
|
||||
setChecked([])
|
||||
setVerified('')
|
||||
setFailure('')
|
||||
setAuthNeeded(false)
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">{item.icon}</span>
|
||||
@@ -169,136 +318,131 @@ export function SourceWizard({
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step === 1 ? (
|
||||
<div className="source-wizard-auth">
|
||||
{kind === 'pp' ? (
|
||||
<>
|
||||
<div className="row">
|
||||
<span>授权方式</span>
|
||||
<b>公开只读</b>
|
||||
</div>
|
||||
<div className="row">
|
||||
<span>凭据</span>
|
||||
<span>由服务端持有,无需填写</span>
|
||||
</div>
|
||||
<p className="hint">资料下载中心的登录凭据由运维放在服务端,向导里不录入任何密码。</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="row">
|
||||
<span>授权方式</span>
|
||||
<b>当前钉钉账号扫码会话</b>
|
||||
</div>
|
||||
<div className="row">
|
||||
<span>读取权限</span>
|
||||
<span>只读;不写回、不删除源文件</span>
|
||||
</div>
|
||||
<p className="hint">
|
||||
用的是平台已登录的 dws 凭据,不需要每个来源单独扫码;会话失效时会在保存时弹二维码。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step === 2 ? (
|
||||
)}
|
||||
{step === 1 && (
|
||||
<div className="source-wizard-auth">{kind === 'pp' ? <PPAuthorizationStep /> : authPanel}</div>
|
||||
)}
|
||||
{step === 2 && (
|
||||
<div className="source-wizard-scope">
|
||||
{kind === 'pp' ? (
|
||||
<p className="hint">
|
||||
{ppConnected
|
||||
? '已接入 PP 资料下载中心(一个门户一条来源),无需重复添加;刷新与归档在下方清单里做。'
|
||||
: 'PP 需要服务端放置只读凭据后才能接入;凭据到位后联系我开通,向导本身不录密码。'}
|
||||
? 'PP 资料下载中心已接入,一个门户保留一条来源。'
|
||||
: 'PP 来源尚未接入;认证配置与来源登记分别管理。'}
|
||||
</p>
|
||||
) : loading ? (
|
||||
<p className="hint">正在列举当前账号可见的来源…</p>
|
||||
<p>正在列举当前 DWS 账号可见的来源…</p>
|
||||
) : loadError ? (
|
||||
<p role="alert">{loadError}</p>
|
||||
) : visible.length === 0 ? (
|
||||
<p className="hint">
|
||||
当前账号没有可添加的{kind === 'wiki' ? '知识库' : '钉盘空间'};已加入的不会重复列出。
|
||||
</p>
|
||||
<>
|
||||
<p role="alert">{loadError}</p>
|
||||
<button onClick={() => void load()}>重新读取目录</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="source-wizard-check">
|
||||
{visible.map((item) => (
|
||||
<label key={item.key}>
|
||||
<input type="checkbox" checked={checked.includes(item.key)} onChange={() => toggle(item.key)} />
|
||||
<span>{item.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="hint">
|
||||
已选 {selected.length} 项。勾选空间即可,目录细节加入后再在「来源与目录」里标注。
|
||||
</p>
|
||||
{scopeNotice && <p role="alert">{scopeNotice}</p>}
|
||||
{visible.length ? (
|
||||
<div className="source-wizard-check">
|
||||
{visible.map((item) => (
|
||||
<label key={item.key}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked.includes(item.key)}
|
||||
disabled={item.alreadyRegistered || busy}
|
||||
onChange={() => {
|
||||
setChecked((current) =>
|
||||
current.includes(item.key)
|
||||
? current.filter((x) => x !== item.key)
|
||||
: [...current, item.key]
|
||||
)
|
||||
setVerified('')
|
||||
}}
|
||||
/>
|
||||
<span>
|
||||
{item.name}
|
||||
{item.alreadyRegistered ? '(已接入)' : ''}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p>当前账号没有可添加的{kind === 'wiki' ? '知识库' : '钉盘空间'}。</p>
|
||||
)}
|
||||
<p className="hint">已选 {selected.length} 项;目录规则在加入后的“来源与目录”设置。</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step === 3 ? (
|
||||
)}
|
||||
{step === 3 && (
|
||||
<div className="source-wizard-verify">
|
||||
<ul>
|
||||
{(kind === 'pp' ? [] : selected).map((item: DiscoveryCandidate) => (
|
||||
<li key={item.key}>
|
||||
<span>{item.name}</span>
|
||||
<b className="ok">仍可见</b>
|
||||
</li>
|
||||
))}
|
||||
{kind === 'pp' ? (
|
||||
<li>
|
||||
<span>Partner Portal 公开目录</span>
|
||||
<b className="ok">公开只读可达</b>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
<p className="hint">添加时会按当前账号再读一次;如果已看不到,会拒绝并提示刷新。</p>
|
||||
{busy ? (
|
||||
<p>正在校验所选来源…</p>
|
||||
) : verified ? (
|
||||
<>
|
||||
<ul>
|
||||
{selected.map((item) => (
|
||||
<li key={item.key}>
|
||||
<span>{item.name}</span>
|
||||
<b className="ok">校验通过</b>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<small>检查于 {new Date(verified).toLocaleString('zh-CN', { hour12: false })}</small>
|
||||
</>
|
||||
) : (
|
||||
<button onClick={() => void verify()}>重新校验</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step === 4 ? (
|
||||
)}
|
||||
{step === 4 && (
|
||||
<div className="source-wizard-save">
|
||||
{message ? <p role="status">{message}</p> : null}
|
||||
{failure ? <p role="alert">{failure}</p> : null}
|
||||
{!message && !failure ? (
|
||||
<p className="hint">
|
||||
将加入{' '}
|
||||
{(kind === 'pp' ? ['Partner Portal'] : selected.map((item) => item.name)).join('、') || '(未选择)'}
|
||||
。
|
||||
</p>
|
||||
) : null}
|
||||
{loginRequired ? (
|
||||
<DingtalkSessionControl
|
||||
autoStart
|
||||
hideTrigger
|
||||
space={selected[0]?.url}
|
||||
onSuccess={() => {
|
||||
setLoginRequired(false)
|
||||
void submit(true)
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{message && <p role="status">{message}</p>}
|
||||
{pending.current.length > 0 && !authNeeded && !busy && (
|
||||
<button onClick={() => void submit([...pending.current])}>重试剩余来源</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
)}
|
||||
{failure && <p role="alert">{failure}</p>}
|
||||
{authNeeded && step !== 1 && authPanel}
|
||||
<div className="source-wizard-foot">
|
||||
<button type="button" className="ghost" onClick={() => (step === 0 ? close() : setStep(step - 1))}>
|
||||
<button
|
||||
type="button"
|
||||
className="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setVerified('')
|
||||
setFailure('')
|
||||
step === 0 ? close() : setStep(step - 1)
|
||||
}}
|
||||
>
|
||||
{step === 0 ? '取消' : '上一步'}
|
||||
</button>
|
||||
{kind === 'pp' ? (
|
||||
{kind === 'pp' && step === 1 ? (
|
||||
<button type="button" className="primary" onClick={close}>
|
||||
完成
|
||||
</button>
|
||||
) : step < 3 ? (
|
||||
<button type="button" className="primary" disabled={!canAdvance} onClick={() => setStep(step + 1)}>
|
||||
) : step < 2 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="primary"
|
||||
disabled={busy || kind === null || (step === 1 && !validAccount(credentials))}
|
||||
onClick={() => setStep(step + 1)}
|
||||
>
|
||||
下一步
|
||||
</button>
|
||||
) : step === 2 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="primary"
|
||||
disabled={busy || !selected.length}
|
||||
onClick={() => void verify()}
|
||||
>
|
||||
下一步
|
||||
</button>
|
||||
) : step === 3 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="primary"
|
||||
disabled={busy || !canAdvance}
|
||||
disabled={busy || !verified}
|
||||
onClick={() => {
|
||||
setStep(4)
|
||||
void submit()
|
||||
@@ -307,13 +451,13 @@ export function SourceWizard({
|
||||
{busy ? '正在加入…' : '保存并首次扫描'}
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="primary" onClick={close}>
|
||||
<button type="button" className="primary" disabled={busy} onClick={close}>
|
||||
完成
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } fr
|
||||
import { RoutingBindingsSection } from './RoutingBindingsSection'
|
||||
import { ProductionBindingsSection } from './ProductionBindingsSection'
|
||||
import { SourceWizard } from './SourceWizard'
|
||||
import { PPConnection } from './PPConnection'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { fetchMonitorOverview } from './monitor'
|
||||
import type { MonitorOverview } from './monitor'
|
||||
@@ -297,7 +298,12 @@ export function SystemSettingsView({
|
||||
onRegistered={onSourcesChanged}
|
||||
/>
|
||||
) : null}
|
||||
{identity?.role === 'admin' ? <DingtalkAccountStatus /> : null}
|
||||
{identity?.role === 'admin' ? (
|
||||
<>
|
||||
<DingtalkAccountStatus />
|
||||
<PPConnection />
|
||||
</>
|
||||
) : null}
|
||||
<div className="settings-source-group" id="settings-sources-pp">
|
||||
{listedConnections.length ? (
|
||||
<div className="settings-source-list">
|
||||
|
||||
@@ -65,6 +65,7 @@ export async function cancelDingtalkSession(id: string): Promise<void> {
|
||||
export interface RegisteredDingtalkSpace {
|
||||
connection_id: string
|
||||
name: string
|
||||
first_scan_queued?: boolean
|
||||
}
|
||||
|
||||
export class DingtalkRequestError extends Error {
|
||||
@@ -81,14 +82,19 @@ export class DingtalkRequestError extends Error {
|
||||
// Register a DingTalk knowledge-base space (URL or bare space id) as a new
|
||||
// source connection. Errors carry the sidecar's machine codes so the UI can
|
||||
// explain them: login_required, space_not_found, name_conflict.
|
||||
export async function registerDingtalkSpace(url: string): Promise<RegisteredDingtalkSpace> {
|
||||
export async function registerDingtalkSpace(
|
||||
url: string,
|
||||
operationID = newOperationID(),
|
||||
identity?: string
|
||||
): Promise<RegisteredDingtalkSpace> {
|
||||
const response = await fetch('/api/v1/dingtalk-spaces', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'dingtalk-space',
|
||||
'Idempotency-Key': newOperationID(),
|
||||
'Idempotency-Key': operationID,
|
||||
...(identity ? { 'X-DWS-Identity': identity } : {}),
|
||||
},
|
||||
body: JSON.stringify({ url }),
|
||||
})
|
||||
@@ -106,7 +112,11 @@ export async function registerDingtalkSpace(url: string): Promise<RegisteredDing
|
||||
/* status-only */
|
||||
}
|
||||
const friendly: Record<string, string> = {
|
||||
login_required: '钉钉扫码会话无效或已过期,请先在钉钉来源卡片上「扫码刷新会话」',
|
||||
login_required: 'DWS 授权已失效,请重新授权',
|
||||
dws_login_required: 'DWS 授权已失效,请重新授权',
|
||||
dws_unavailable: 'DWS 目录暂时不可用,请重试',
|
||||
dws_permission_denied: '当前 DWS 账号缺少目录权限',
|
||||
dws_identity_changed: 'DWS 账号或组织已变化,请重新确认来源',
|
||||
space_not_found: '未找到该知识库空间:请确认空间链接正确且当前账号有阅读权限',
|
||||
name_conflict: '该空间与已登记的来源同名',
|
||||
// 登记冲突分两种:同名来源还在用 vs 同一个登记键指向了别的空间。原因要说清,
|
||||
@@ -127,7 +137,11 @@ export async function registerDingtalkSpace(url: string): Promise<RegisteredDing
|
||||
const data = value.data
|
||||
if (typeof data.connection_id !== 'string' || typeof data.name !== 'string')
|
||||
throw new Error('invalid dingtalk space response')
|
||||
return { connection_id: data.connection_id, name: data.name }
|
||||
return {
|
||||
connection_id: data.connection_id,
|
||||
name: data.name,
|
||||
...(typeof data.first_scan_queued === 'boolean' ? { first_scan_queued: data.first_scan_queued } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function parseSession(value: unknown): DingtalkSessionView {
|
||||
|
||||
@@ -7,6 +7,7 @@ const payload = {
|
||||
knowledge_bases: [
|
||||
{
|
||||
name: 'ATOM知识库',
|
||||
registered: true,
|
||||
space_id: '9JOGOQneRgkneX4Q',
|
||||
space_type: 'orgWikiSpace',
|
||||
url: 'https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview',
|
||||
|
||||
+49
-10
@@ -1,7 +1,10 @@
|
||||
// 「系统设置 → 数据源配置」的数据源发现客户端:列出当前 dws 账号能看到的钉钉知识库与钉盘空间。
|
||||
// 只读;勾选后的登记仍走既有的 /api/v1/dingtalk-spaces(由扫码会话解析空间根目录)。
|
||||
|
||||
import { DingtalkRequestError } from './dingtalkSession'
|
||||
|
||||
export interface AvailableKnowledgeBase {
|
||||
registered?: boolean
|
||||
name: string
|
||||
space_id: string
|
||||
space_type?: string
|
||||
@@ -10,6 +13,7 @@ export interface AvailableKnowledgeBase {
|
||||
}
|
||||
|
||||
export interface AvailableDriveSpace {
|
||||
registered?: boolean
|
||||
name: string
|
||||
space_id: string
|
||||
space_type: string
|
||||
@@ -38,12 +42,17 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
export async function fetchAvailableDingtalkSources(signal?: AbortSignal): Promise<AvailableDingtalkSources> {
|
||||
const response = await fetch('/api/v1/dingtalk-spaces/available', { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) {
|
||||
// 503 是环境问题(dws 未登录/权限不足),501 是后端没接线:都要说清楚"不是没有来源"。
|
||||
if (response.status === 503)
|
||||
throw new Error('暂时列不出来:dws 未登录或缺少租户目录读权限。先刷新钉钉会话,或让管理员检查 dws 凭据。')
|
||||
if (response.status === 501) throw new Error('后端未接线:数据源发现接口不可用。')
|
||||
if (response.status === 401 || response.status === 403) throw new Error('需要管理员身份才能列举数据源。')
|
||||
throw new Error(`列举数据源失败(HTTP ${response.status})`)
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
const code = isRecord(body) && typeof body.error === 'string' ? body.error : 'request_failed'
|
||||
const hint =
|
||||
isRecord(body) && typeof body.hint === 'string'
|
||||
? body.hint
|
||||
: response.status === 501
|
||||
? '后端未接线:DWS 来源服务不可用。'
|
||||
: response.status === 401 || response.status === 403
|
||||
? '需要管理员身份才能列举数据源。'
|
||||
: `目录暂时列不出来(HTTP ${response.status})`
|
||||
throw new DingtalkRequestError(hint, code, response.status)
|
||||
}
|
||||
const payload = (await response.json()) as unknown
|
||||
const data = isRecord(payload) && isRecord(payload.data) ? payload.data : {}
|
||||
@@ -60,6 +69,7 @@ export async function fetchAvailableDingtalkSources(signal?: AbortSignal): Promi
|
||||
? [
|
||||
{
|
||||
name,
|
||||
registered: item.registered === true,
|
||||
space_id: spaceID,
|
||||
space_type: spaceType,
|
||||
url,
|
||||
@@ -77,6 +87,7 @@ export async function fetchAvailableDingtalkSources(signal?: AbortSignal): Promi
|
||||
? [
|
||||
{
|
||||
name,
|
||||
registered: item.registered === true,
|
||||
space_id: spaceID,
|
||||
space_type: spaceType,
|
||||
root_folder_id: typeof item.root_folder_id === 'string' ? item.root_folder_id : '',
|
||||
@@ -103,9 +114,8 @@ export interface DiscoveryCandidate {
|
||||
// 避免重复登记。
|
||||
export function discoveryCandidates(
|
||||
list: AvailableDingtalkSources | null,
|
||||
registeredNames: string[]
|
||||
_registeredNames: string[]
|
||||
): DiscoveryCandidate[] {
|
||||
const registered = new Set(registeredNames.map((name) => name.trim()).filter(Boolean))
|
||||
const knowledgeBases = (list?.knowledge_bases ?? []).map((item): DiscoveryCandidate => ({
|
||||
key: `kb:${item.space_id}`,
|
||||
kind: 'knowledge_base',
|
||||
@@ -113,7 +123,7 @@ export function discoveryCandidates(
|
||||
spaceID: item.space_id,
|
||||
url: item.url || driveSpaceURL(item.space_id),
|
||||
detail: item.space_type === 'myWikiSpace' ? '钉钉知识库 · 我的知识库' : '钉钉知识库 · 组织知识库',
|
||||
alreadyRegistered: registered.has(item.name.trim()),
|
||||
alreadyRegistered: item.registered === true,
|
||||
}))
|
||||
const driveSpaces = (list?.drive_spaces ?? []).map((item): DiscoveryCandidate => ({
|
||||
key: `drive:${item.space_id}`,
|
||||
@@ -122,7 +132,36 @@ export function discoveryCandidates(
|
||||
spaceID: item.space_id,
|
||||
url: driveSpaceURL(item.space_id),
|
||||
detail: item.space_type === 'mySpace' ? '钉盘 · 我的文件' : '钉盘 · 组织空间',
|
||||
alreadyRegistered: registered.has(item.name.trim()),
|
||||
alreadyRegistered: item.registered === true,
|
||||
}))
|
||||
return [...knowledgeBases, ...driveSpaces]
|
||||
}
|
||||
|
||||
export async function validateDingtalkSources(urls: string[], identity?: string): Promise<{ checked_at: string }> {
|
||||
const response = await fetch('/api/v1/dingtalk-spaces/validate', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'dingtalk-space',
|
||||
...(identity ? { 'X-DWS-Identity': identity } : {}),
|
||||
},
|
||||
body: JSON.stringify({ urls }),
|
||||
})
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const code = isRecord(body) && typeof body.error === 'string' ? body.error : 'validation_failed'
|
||||
const hint = isRecord(body) && typeof body.hint === 'string' ? body.hint : '来源校验失败,请重新读取范围'
|
||||
throw new DingtalkRequestError(hint, code, response.status)
|
||||
}
|
||||
if (
|
||||
!isRecord(body) ||
|
||||
!isRecord(body.data) ||
|
||||
body.data.valid !== true ||
|
||||
body.data.count !== urls.length ||
|
||||
typeof body.data.checked_at !== 'string' ||
|
||||
!Number.isFinite(Date.parse(body.data.checked_at))
|
||||
)
|
||||
throw new Error('未取得有效的来源校验结果')
|
||||
return { checked_at: body.data.checked_at }
|
||||
}
|
||||
|
||||
+3
-1
@@ -1,4 +1,5 @@
|
||||
export interface DWSCredentials {
|
||||
identity?: string
|
||||
authenticated: boolean
|
||||
refresh_token_valid: boolean
|
||||
status_known: boolean
|
||||
@@ -45,7 +46,7 @@ async function request(path: string, signal?: AbortSignal, method = 'GET') {
|
||||
const reason = record(payload) && typeof payload.error === 'string' ? payload.error : ''
|
||||
if (reason === 'dingtalk_discovery_unavailable')
|
||||
throw new Error('DWS 未登录、授权已过期或缺少目录权限;请先登录授权,再检查连接。')
|
||||
throw new Error(reason || `DWS 请求失败(HTTP ${response.status})`)
|
||||
throw new Error((record(payload) ? text(payload.hint) : '') || reason || `DWS 请求失败(HTTP ${response.status})`)
|
||||
}
|
||||
if (!record(payload) || !record(payload.data)) throw new Error('DWS 返回的数据格式不正确,请重试')
|
||||
return payload.data
|
||||
@@ -55,6 +56,7 @@ export async function fetchDWSCredentials(signal?: AbortSignal): Promise<DWSCred
|
||||
if (typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean')
|
||||
throw new Error('无法判断 DWS 登录状态')
|
||||
return {
|
||||
identity: text(data.identity),
|
||||
authenticated: data.authenticated,
|
||||
refresh_token_valid: data.refresh_token_valid,
|
||||
status_known: data.status_known !== false,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { readPPConnection, testPPConnection, savePPConnection } from './ppConnection'
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
describe('PP connection transport', () => {
|
||||
it('uses current draft on POST without saving or sending a placeholder password', async () => {
|
||||
const fetcher = vi.fn(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({ data: { state: 'valid', message: '目录可读', checked_at: '2026-11-17T10:00:00Z' } })
|
||||
)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const result = await testPPConnection({ base_url: 'https://api.example.invalid', username: 'example', revision: 3 })
|
||||
expect(result.state).toBe('valid')
|
||||
const [path, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit]
|
||||
expect(path).toBe('/api/v1/pp-connection/test')
|
||||
expect(init.method).toBe('POST')
|
||||
expect(JSON.parse(String(init.body))).toEqual({
|
||||
base_url: 'https://api.example.invalid',
|
||||
username: 'example',
|
||||
revision: 3,
|
||||
})
|
||||
})
|
||||
it('preserves real response errors and reads metadata only', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response(JSON.stringify({ error: '原配置保留' }), { status: 422 }))
|
||||
)
|
||||
await expect(
|
||||
savePPConnection({ base_url: 'https://api.example.invalid', username: 'example', revision: 1 })
|
||||
).rejects.toThrow('原配置保留')
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: { revision: 1, active: null, pending: null, observation: null, pending_observation: null },
|
||||
})
|
||||
)
|
||||
)
|
||||
)
|
||||
expect((await readPPConnection()).revision).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
export type PPObservation = { state: string; message: string; checked_at: string; previous?: PPObservation | null }
|
||||
export type PPMetadata = { id: string; base_url: string; username: string; password_configured: boolean }
|
||||
export type PPView = {
|
||||
revision: number
|
||||
active: PPMetadata | null
|
||||
pending: PPMetadata | null
|
||||
observation: PPObservation | null
|
||||
pending_observation: PPObservation | null
|
||||
}
|
||||
export type PPDraft = { base_url: string; username: string; password?: string; revision: number; pending_id?: string }
|
||||
const record = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null
|
||||
const states = new Set(['valid', 'auth_failed', 'permission_denied', 'incomplete', 'unavailable', 'invalid_response'])
|
||||
async function request(path: string, method: string, draft?: PPDraft, signal?: AbortSignal) {
|
||||
const response = await fetch(path, {
|
||||
method,
|
||||
signal,
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(draft ? { 'Content-Type': 'application/json', 'X-Governance-Action': 'pp-connection' } : {}),
|
||||
},
|
||||
...(draft ? { body: JSON.stringify(draft) } : {}),
|
||||
})
|
||||
const payload: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
record(payload) && typeof payload.error === 'string' ? payload.error : `PP 请求失败(HTTP ${response.status})`
|
||||
)
|
||||
if (!record(payload) || !record(payload.data)) throw new Error('PP 返回的数据格式不正确')
|
||||
return payload.data
|
||||
}
|
||||
function parseObservation(data: unknown): PPObservation | null {
|
||||
if (data === null || data === undefined) return null
|
||||
if (
|
||||
!record(data) ||
|
||||
!states.has(String(data.state)) ||
|
||||
typeof data.message !== 'string' ||
|
||||
typeof data.checked_at !== 'string' ||
|
||||
!Number.isFinite(Date.parse(data.checked_at))
|
||||
)
|
||||
throw new Error('PP 检查状态无法识别')
|
||||
return {
|
||||
state: String(data.state),
|
||||
message: data.message,
|
||||
checked_at: data.checked_at,
|
||||
...(record(data.previous) ? { previous: parseObservation({ ...data.previous, previous: null }) } : {}),
|
||||
}
|
||||
}
|
||||
function parseMetadata(data: unknown): PPMetadata | null {
|
||||
if (data === null) return null
|
||||
if (
|
||||
!record(data) ||
|
||||
typeof data.id !== 'string' ||
|
||||
typeof data.base_url !== 'string' ||
|
||||
typeof data.username !== 'string' ||
|
||||
typeof data.password_configured !== 'boolean'
|
||||
)
|
||||
throw new Error('PP 配置元数据不正确')
|
||||
return {
|
||||
id: data.id,
|
||||
base_url: data.base_url,
|
||||
username: data.username,
|
||||
password_configured: data.password_configured,
|
||||
}
|
||||
}
|
||||
function parseView(data: Record<string, unknown>): PPView {
|
||||
if (!Number.isSafeInteger(data.revision) || Number(data.revision) < 0) throw new Error('PP 配置版本不正确')
|
||||
return {
|
||||
revision: Number(data.revision),
|
||||
active: parseMetadata(data.active),
|
||||
pending: parseMetadata(data.pending),
|
||||
observation: parseObservation(data.observation),
|
||||
pending_observation: parseObservation(data.pending_observation),
|
||||
}
|
||||
}
|
||||
export async function readPPConnection(signal?: AbortSignal): Promise<PPView> {
|
||||
return parseView(await request('/api/v1/pp-connection', 'GET', undefined, signal))
|
||||
}
|
||||
export async function testPPConnection(draft: PPDraft, signal?: AbortSignal): Promise<PPObservation> {
|
||||
const result = parseObservation(await request('/api/v1/pp-connection/test', 'POST', draft, signal))
|
||||
if (!result) throw new Error('未取得 PP 检查结果')
|
||||
return result
|
||||
}
|
||||
export async function savePPConnection(draft: PPDraft, signal?: AbortSignal): Promise<PPView> {
|
||||
return parseView(await request('/api/v1/pp-connection', 'PUT', draft, signal))
|
||||
}
|
||||
@@ -38,6 +38,10 @@ export async function fetchSourceAudit(offset = 0, signal?: AbortSignal): Promis
|
||||
return data
|
||||
}
|
||||
export const sourceAuditActions: Record<string, string> = {
|
||||
credential_configured: '更新认证配置',
|
||||
credential_rejected: '认证配置校验失败',
|
||||
credential_test: '测试连接',
|
||||
dws_authorization: '钉钉授权',
|
||||
created: '添加连接',
|
||||
settings_updated: '修改配置',
|
||||
paused: '暂停自动刷新',
|
||||
|
||||
Reference in New Issue
Block a user