列表正文改为按需读取;保留完整导出、版本隔离和有效标签筛选。 验证:前端全量、Go全量及隔离PG全mirror竞态通过;覆盖首批回调、续载失败与筛选分页。
This commit is contained in:
+16
-3
@@ -191,11 +191,15 @@ function QAAIBatchControls({ batch, onChanged }: { batch: AIBatch; onChanged: ()
|
||||
export function QAAIWorkbench({
|
||||
initial,
|
||||
query,
|
||||
filteredIDs,
|
||||
filterRevision,
|
||||
onStatus,
|
||||
onRecordChanged,
|
||||
}: {
|
||||
initial?: AIStatus
|
||||
query: QAQuery | null
|
||||
filteredIDs?: string[]
|
||||
filterRevision?: number
|
||||
onStatus?: (status: AIStatus) => void
|
||||
onRecordChanged?: (id: string) => void
|
||||
}) {
|
||||
@@ -265,13 +269,22 @@ export function QAAIWorkbench({
|
||||
}
|
||||
}
|
||||
const ready = Boolean(status?.settings.verification === 'verified' && status.settings.storage_ready)
|
||||
const scope = query ? { start: query.start, end: query.end, keyword: query.keyword } : null
|
||||
const scopeKey = query ? `${query.start}:${query.end}:${query.keyword}` : 'none'
|
||||
const filtered = Boolean(query?.filters && Object.keys(query.filters).length)
|
||||
const scope = filtered
|
||||
? filteredIDs?.length
|
||||
? { ids: filteredIDs }
|
||||
: null
|
||||
: query
|
||||
? { start: query.start, end: query.end, keyword: query.keyword }
|
||||
: null
|
||||
const scopeKey = query
|
||||
? `${query.start}:${query.end}:${query.keyword}:${JSON.stringify(query.filters ?? {})}:${filteredIDs?.length ?? 'loading'}:${filterRevision ?? ''}`
|
||||
: 'none'
|
||||
return (
|
||||
<section className="qa-ai-workbench" aria-label="问答后台任务">
|
||||
<div className="qa-ai-actions">
|
||||
<span>当前已执行筛选</span>
|
||||
<QAAIRequest key={scopeKey} scope={scope} label="AI分析" disabled={!ready} onQueued={refresh} />
|
||||
<QAAIRequest key={scopeKey} scope={scope} label="AI分析" disabled={!ready || !scope} onQueued={refresh} />
|
||||
{status ? (
|
||||
<small>
|
||||
{status.worker_ready ? '执行器在线' : '执行器未在线,任务会持久保留'}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { editableFieldKeys, fetchFieldOptions } from './qaInlineFields'
|
||||
import type { FieldOptions } from './qaInlineFields'
|
||||
import type { QAQuery } from './qaOps'
|
||||
export const qualityFilterLabels = {
|
||||
coverage: '是否覆盖',
|
||||
is_correct: '是否正确',
|
||||
product_category: '产品分类',
|
||||
problem_type: '问题类型',
|
||||
root_cause: '根因分析',
|
||||
}
|
||||
export function QAFieldFilters({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: NonNullable<QAQuery['filters']>
|
||||
onChange: (value: NonNullable<QAQuery['filters']>) => void
|
||||
}) {
|
||||
const [options, setOptions] = useState<FieldOptions | null>(null),
|
||||
[error, setError] = useState(''),
|
||||
[revision, setRevision] = useState(0)
|
||||
useEffect(() => {
|
||||
const abort = new AbortController()
|
||||
setError('')
|
||||
void fetchFieldOptions(abort.signal)
|
||||
.then((v) => {
|
||||
if (!abort.signal.aborted) setOptions(v)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!abort.signal.aborted) setError(e instanceof Error ? e.message : '筛选选项读取失败')
|
||||
})
|
||||
return () => abort.abort()
|
||||
}, [revision])
|
||||
return (
|
||||
<div className="qa-field-filters" aria-label="质量字段筛选">
|
||||
{editableFieldKeys.map((key) => (
|
||||
<label key={key}>
|
||||
{qualityFilterLabels[key]}
|
||||
<select
|
||||
aria-label={'筛选' + qualityFilterLabels[key]}
|
||||
value={value[key] ?? ''}
|
||||
disabled={!options}
|
||||
onChange={(e) => {
|
||||
const next = { ...value }
|
||||
if (e.target.value) next[key] = e.target.value
|
||||
else delete next[key]
|
||||
onChange(next)
|
||||
}}
|
||||
>
|
||||
<option value="">全部</option>
|
||||
<option value="__empty__">未设置</option>
|
||||
{options?.[key].map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{key === 'is_correct'
|
||||
? ({ 是: '正确', 否: '错误', 待确认: '待确认' }[option] ?? option)
|
||||
: key === 'coverage'
|
||||
? ({ 是: '已覆盖', 否: '未覆盖', 否但不计入: '不计入' }[option] ?? option)
|
||||
: option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
<button type="button" disabled={!Object.keys(value).length} onClick={() => onChange({})}>
|
||||
清除字段筛选
|
||||
</button>
|
||||
{error ? (
|
||||
<span role="alert">
|
||||
{error}{' '}
|
||||
<button type="button" onClick={() => setRevision((v) => v + 1)}>
|
||||
重试选项
|
||||
</button>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -52,6 +52,18 @@ const props = {
|
||||
}
|
||||
|
||||
describe('QA operations workbench', () => {
|
||||
it('keeps the first rows interactive while later batches load or fail', () => {
|
||||
const prefix = { ...page, total: 2, has_more: true, next_cursor: 'next' }
|
||||
const loading = renderToStaticMarkup(<QAOperationsView {...props} page={prefix} loading={true} />)
|
||||
expect(loading).toContain('data-qa-row="fixture"')
|
||||
expect(loading).toContain('后台加载中')
|
||||
expect(loading).not.toContain('正在读取全部问答')
|
||||
const failed = renderToStaticMarkup(<QAOperationsView {...props} page={prefix} error="明确续载失败" />)
|
||||
expect(failed).toContain('未完整读取')
|
||||
expect(failed).toContain('明确续载失败')
|
||||
expect(failed).toContain('data-qa-row="fixture"')
|
||||
})
|
||||
|
||||
it('edits five fields directly in the first row without a separate review or feedback form', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAOperationsView {...props} detail={{ ...item, record_origin: 'historical_excel' }} />
|
||||
|
||||
+70
-11
@@ -9,6 +9,8 @@ import { QARegionalStatistics } from './QADepartmentStatistics'
|
||||
import { QADashboard } from './QADashboard'
|
||||
import { QAWeekly } from './QAWeekly'
|
||||
import { QAInlineFields } from './QAInlineFields'
|
||||
import { QAFieldFilters } from './QAFieldFilters'
|
||||
import { buildQAWeeklyCSV, downloadQAWeekly } from './qaWeekly'
|
||||
import { qaFieldColors, qaTagColumns } from './qaFieldColors'
|
||||
import { qualityLabels } from './qaQuality'
|
||||
import { QAWeekPicker } from './QAWeekPicker'
|
||||
@@ -169,10 +171,10 @@ export function QAOperationsView(props: ViewProps) {
|
||||
<section className="qa-ops-results" aria-label="问答记录">
|
||||
<div className="qa-ops-result-bar">
|
||||
<span>
|
||||
{props.loading
|
||||
? `正在读取全部问答…${props.progress ? `(${props.progress.loaded} / ${props.progress.total})` : ''}`
|
||||
: page
|
||||
? `共 ${page.total} 条 · 已载入 ${page.items.length} 条`
|
||||
{page
|
||||
? `共 ${page.total} 条 · 已载入 ${page.items.length} 条${props.loading ? ' · 后台加载中' : props.error || page.has_more ? ' · 未完整读取' : ''}`
|
||||
: props.loading
|
||||
? '正在读取首批问答…'
|
||||
: '尚未读取问答'}
|
||||
</span>
|
||||
<small className="qa-ops-muted">双击行查看详情</small>
|
||||
@@ -360,6 +362,10 @@ export function QAOperations() {
|
||||
const auth = useOptionalAuth()
|
||||
const canRead = auth?.identity?.role === 'admin'
|
||||
const [draft, setDraft] = useState(initialDraft)
|
||||
const [filters, setFilters] = useState<NonNullable<QAQuery['filters']>>({})
|
||||
const [exporting, setExporting] = useState(false),
|
||||
[exportError, setExportError] = useState('')
|
||||
const exportRequest = useRef<AbortController | null>(null)
|
||||
const [query, setQuery] = useState<QAQuery | null>(null)
|
||||
const [page, setPage] = useState<QARecordPage | null>(null)
|
||||
const [status, setStatus] = useState<QAStatus | null>(null)
|
||||
@@ -415,9 +421,18 @@ export function QAOperations() {
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setStatus(null)
|
||||
})
|
||||
void fetchAllQARecords({ ...query, dataset: 'master' }, controller.signal, (loaded, total) => {
|
||||
if (!controller.signal.aborted) setProgress({ loaded, total })
|
||||
})
|
||||
const publish = (result: QARecordPage) => {
|
||||
if (!controller.signal.aborted)
|
||||
setPage({ ...result, items: result.items.map((item) => freshAI.current.get(item.id) ?? item) })
|
||||
}
|
||||
void fetchAllQARecords(
|
||||
{ ...query, dataset: 'master', projection: 'summary' },
|
||||
controller.signal,
|
||||
(loaded, total) => {
|
||||
if (!controller.signal.aborted) setProgress({ loaded, total })
|
||||
},
|
||||
publish
|
||||
)
|
||||
.then((result) => {
|
||||
if (!controller.signal.aborted)
|
||||
setPage({ ...result, items: result.items.map((item) => freshAI.current.get(item.id) ?? item) })
|
||||
@@ -428,8 +443,33 @@ export function QAOperations() {
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
return () => {
|
||||
controller.abort()
|
||||
generation.current += 1
|
||||
}
|
||||
}, [query, canRead, revision, view])
|
||||
useEffect(() => {
|
||||
exportRequest.current?.abort()
|
||||
setExporting(false)
|
||||
setExportError('')
|
||||
return () => exportRequest.current?.abort()
|
||||
}, [query, view])
|
||||
const exportCSV = async () => {
|
||||
if (!query || exporting) return
|
||||
const abort = new AbortController()
|
||||
exportRequest.current = abort
|
||||
setExporting(true)
|
||||
setExportError('')
|
||||
try {
|
||||
const result = await fetchAllQARecords({ ...query, dataset: 'master', projection: 'full' }, abort.signal)
|
||||
if (!abort.signal.aborted)
|
||||
downloadQAWeekly(buildQAWeeklyCSV(result), 'DobotAI-Questions.csv', 'text/csv;charset=utf-8')
|
||||
} catch (e) {
|
||||
if (!abort.signal.aborted) setExportError(e instanceof Error ? e.message : '完整明细导出失败')
|
||||
} finally {
|
||||
if (!abort.signal.aborted) setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -445,7 +485,7 @@ export function QAOperations() {
|
||||
end = qaDateTimeToISO(draft.end)
|
||||
if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间')
|
||||
if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围')
|
||||
setQuery({ start, end, keyword: draft.keyword, cursor: '' })
|
||||
setQuery({ start, end, keyword: draft.keyword, cursor: '', filters: { ...filters } })
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '时间格式无效')
|
||||
}
|
||||
@@ -531,6 +571,7 @@ export function QAOperations() {
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
filters: { ...filters },
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) =>
|
||||
@@ -567,9 +608,10 @@ export function QAOperations() {
|
||||
onChange={(e) => setDraft({ ...draft, keyword: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button className="qa-query-action" type="submit" disabled={loading}>
|
||||
<button className="qa-query-action" type="submit">
|
||||
查询
|
||||
</button>
|
||||
<QAFieldFilters value={filters} onChange={setFilters} />
|
||||
<QAMirrorSync
|
||||
onChanged={() => {
|
||||
if (detail || detailLoading) {
|
||||
@@ -583,7 +625,23 @@ export function QAOperations() {
|
||||
/>
|
||||
</form>
|
||||
<div hidden={view !== 'records'}>
|
||||
<QAAIWorkbench query={query} onStatus={setAIStatus} onRecordChanged={refreshAIRecord} />
|
||||
<QAAIWorkbench
|
||||
query={query}
|
||||
filteredIDs={
|
||||
query?.filters && Object.keys(query.filters).length && page && !loading && !error && !page.has_more
|
||||
? page.items.map((item) => item.id)
|
||||
: undefined
|
||||
}
|
||||
filterRevision={page?.local_revision}
|
||||
onStatus={setAIStatus}
|
||||
onRecordChanged={refreshAIRecord}
|
||||
/>
|
||||
<div className="qa-ledger-export">
|
||||
<button type="button" disabled={!query || exporting} onClick={() => void exportCSV()}>
|
||||
{exporting ? '正在导出完整明细…' : '导出全部明细'}
|
||||
</button>
|
||||
{exportError ? <span role="alert">{exportError}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
@@ -621,6 +679,7 @@ export function QAOperations() {
|
||||
}}
|
||||
onQualitySaved={(fresh) => {
|
||||
if (fresh.id !== detail?.id) return
|
||||
freshAI.current.set(fresh.id, fresh)
|
||||
setDetail(fresh)
|
||||
setPage((old) =>
|
||||
old ? { ...old, items: old.items.map((item) => (item.id === fresh.id ? fresh : item)) } : old
|
||||
|
||||
@@ -29,6 +29,57 @@ const query = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T08:00:00Z', keyw
|
||||
const respond = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 })
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
describe('all QA records without manual pagination', () => {
|
||||
it('retains only the verified prefix when a later local version changes', async () => {
|
||||
const first = { ...page(['a'], 2, 'n'), local_revision: 1 },
|
||||
second = { ...page(['b'], 2), local_revision: 2 }
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(respond(first)).mockResolvedValueOnce(respond(second)))
|
||||
const batches = vi.fn()
|
||||
await expect(fetchAllQARecords(query, undefined, undefined, batches)).rejects.toThrow('本地问答已更新')
|
||||
expect(batches).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
it('carries every active quality filter and summary projection to every batch', async () => {
|
||||
const fetcher = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(respond(page(['a'], 2, 'n')))
|
||||
.mockResolvedValueOnce(respond(page(['b'], 2)))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const filters = {
|
||||
coverage: '是',
|
||||
is_correct: '否',
|
||||
product_category: 'MG400',
|
||||
problem_type: '参数',
|
||||
root_cause: '__empty__',
|
||||
}
|
||||
await fetchAllQARecords({ ...query, dataset: 'master', projection: 'summary', filters })
|
||||
for (const [url] of fetcher.mock.calls) {
|
||||
const u = new URL(String(url), 'http://localhost')
|
||||
expect(u.searchParams.get('projection')).toBe('summary')
|
||||
for (const [key, value] of Object.entries(filters)) expect(u.searchParams.get(key)).toBe(value)
|
||||
}
|
||||
})
|
||||
|
||||
it('publishes a usable first batch before the next response completes', async () => {
|
||||
let release!: (response: Response) => void
|
||||
const waiting = new Promise<Response>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(respond(page(['a'], 2, 'n')))
|
||||
.mockReturnValueOnce(waiting)
|
||||
)
|
||||
const batches = vi.fn()
|
||||
const done = fetchAllQARecords(query, undefined, undefined, batches)
|
||||
await vi.waitFor(() => expect(batches).toHaveBeenCalledTimes(1))
|
||||
expect(batches.mock.calls[0][0].items.map((r: { id: string }) => r.id)).toEqual(['a'])
|
||||
expect(batches.mock.calls[0][0].has_more).toBe(true)
|
||||
release(respond(page(['b'], 2)))
|
||||
expect((await done).items).toHaveLength(2)
|
||||
expect(batches).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('rejects incomplete, duplicate, drifting and cycling batches', async () => {
|
||||
const cases = [
|
||||
[page(['a'], 2)],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { parseQAOrganizationVersion } from './qaOps'
|
||||
import { parseQAOrganizationVersion, parseQualityFilters, qualityFiltersKey } from './qaOps'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
import type { QAOrganizationVersion, QAQuery } from './qaOps'
|
||||
import { parseQualitySummary, parseQualityRate } from './qaQuality'
|
||||
@@ -68,6 +68,7 @@ export interface DashboardRegion {
|
||||
usage_coverage: QualityRate
|
||||
}
|
||||
export interface QADashboardData {
|
||||
filters?: QAQuery['filters']
|
||||
start: string
|
||||
end: string
|
||||
keyword: string
|
||||
@@ -448,6 +449,7 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
} else if (monthly_quality.records !== 0) return bad()
|
||||
}
|
||||
return {
|
||||
filters: parseQualityFilters(v.filters),
|
||||
quality_period,
|
||||
monthly_quality,
|
||||
calendar_months,
|
||||
@@ -490,7 +492,12 @@ export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Pr
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-dashboard' },
|
||||
body: JSON.stringify({ start: query.start, end: query.end, keyword: query.keyword }),
|
||||
body: JSON.stringify({
|
||||
start: query.start,
|
||||
end: query.end,
|
||||
keyword: query.keyword,
|
||||
...(query.filters && Object.keys(query.filters).length ? { filters: query.filters } : {}),
|
||||
}),
|
||||
})
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
@@ -501,7 +508,8 @@ export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Pr
|
||||
if (
|
||||
Date.parse(data.start) !== Date.parse(query.start) ||
|
||||
Date.parse(data.end) !== Date.parse(query.end) ||
|
||||
data.keyword !== query.keyword
|
||||
data.keyword !== query.keyword ||
|
||||
qualityFiltersKey(data.filters) !== qualityFiltersKey(query.filters)
|
||||
)
|
||||
throw new Error('看板返回范围与当前查询不一致,请重新读取')
|
||||
return data
|
||||
|
||||
@@ -704,3 +704,41 @@
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-base);
|
||||
}
|
||||
|
||||
.qa-field-filters {
|
||||
display: flex;
|
||||
flex: 1 0 100%;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-ops-query .qa-field-filters label {
|
||||
flex: 1 1 140px;
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-field-filters select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 36px;
|
||||
padding: 6px 9px;
|
||||
color: var(--ink-strong);
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
}
|
||||
.qa-ledger-export {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.qa-ledger-export [role='alert'] {
|
||||
color: var(--danger-ink);
|
||||
font-size: 12px;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.qa-ops-query .qa-field-filters label {
|
||||
flex: 1 1 120px;
|
||||
}
|
||||
}
|
||||
|
||||
+32
-2
@@ -78,12 +78,14 @@ export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecor
|
||||
current.organization?.revision_id !== next.organization?.revision_id
|
||||
)
|
||||
throw new Error('通讯录或区域配置已变化,请重新查询,不能混合不同版本的分页结果')
|
||||
const ids = new Set(current.items.map((item) => item.id))
|
||||
return {
|
||||
...next,
|
||||
items: [...current.items, ...next.items.filter((item) => !current.items.some((old) => old.id === item.id))],
|
||||
items: [...current.items, ...next.items.filter((item) => !ids.has(item.id))],
|
||||
}
|
||||
}
|
||||
export interface QARecord {
|
||||
content_projection?: 'summary'
|
||||
field_edit_revision?: number
|
||||
background_tasks?: AIWorkState[]
|
||||
record_origin?: 'dobotai_2_0' | 'historical_excel'
|
||||
@@ -128,6 +130,8 @@ export interface QARecordPage {
|
||||
as_of: string
|
||||
}
|
||||
export interface QAQuery {
|
||||
projection?: 'summary' | 'full'
|
||||
filters?: Partial<Record<'coverage' | 'is_correct' | 'product_category' | 'problem_type' | 'root_cause', string>>
|
||||
dataset?: 'master'
|
||||
start: string
|
||||
end: string
|
||||
@@ -135,6 +139,25 @@ export interface QAQuery {
|
||||
cursor: string
|
||||
limit?: number
|
||||
}
|
||||
export function qualityFiltersKey(filters: QAQuery['filters']): string {
|
||||
return JSON.stringify(Object.entries(filters ?? {}).sort(([a], [b]) => a.localeCompare(b)))
|
||||
}
|
||||
export function parseQualityFilters(value: unknown): NonNullable<QAQuery['filters']> {
|
||||
if (value === undefined) return {}
|
||||
const fields = object(value),
|
||||
out: NonNullable<QAQuery['filters']> = {}
|
||||
for (const [key, v] of Object.entries(fields)) {
|
||||
if (
|
||||
!['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'].includes(key) ||
|
||||
typeof v !== 'string' ||
|
||||
!v ||
|
||||
v.length > 400
|
||||
)
|
||||
return invalid()
|
||||
out[key as keyof typeof out] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
export interface QAStatus {
|
||||
state: 'disabled' | 'unavailable' | 'blocked' | 'connected'
|
||||
code: string
|
||||
@@ -163,6 +186,7 @@ const columnKeys = new Set<string>(qaColumns.map(({ key }) => key))
|
||||
|
||||
export function parseQARecord(value: unknown): QARecord {
|
||||
const row = object(value)
|
||||
if (row.content_projection !== undefined && row.content_projection !== 'summary') return invalid()
|
||||
const feedback = object(row.feedback)
|
||||
const source = object(row.source_coverage)
|
||||
const coverage = object(row.coverage)
|
||||
@@ -182,6 +206,7 @@ export function parseQARecord(value: unknown): QARecord {
|
||||
const askerValue = text(feedback.asker_value)
|
||||
if (!['', 'up', 'down'].includes(askerValue)) return invalid()
|
||||
const item: QARecord = {
|
||||
...(row.content_projection === 'summary' ? { content_projection: 'summary' as const } : {}),
|
||||
...(row.quality === undefined
|
||||
? {}
|
||||
: {
|
||||
@@ -332,12 +357,15 @@ export async function fetchQARecords(query: QAQuery, signal?: AbortSignal): Prom
|
||||
cursor: query.cursor,
|
||||
limit: String(query.limit ?? 20),
|
||||
})
|
||||
if (query.projection) parameters.set('projection', query.projection)
|
||||
for (const [key, value] of Object.entries(query.filters ?? {})) if (value) parameters.set(key, value)
|
||||
return parseQARecordPage(await getPayload(`${qaDatasetPrefix(query.dataset)}/records?${parameters}`, signal))
|
||||
}
|
||||
export async function fetchAllQARecords(
|
||||
query: QAQuery,
|
||||
signal?: AbortSignal,
|
||||
onProgress?: (loaded: number, total: number) => void
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
onPage?: (page: QARecordPage) => void
|
||||
): Promise<QARecordPage> {
|
||||
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
|
||||
let page = await fetchQARecords({ ...query, cursor: '', limit: 100 }, signal)
|
||||
@@ -345,6 +373,7 @@ export async function fetchAllQARecords(
|
||||
const ids = new Set(page.items.map((item) => item.id))
|
||||
const cursors = new Set<string>()
|
||||
onProgress?.(ids.size, total)
|
||||
onPage?.(page)
|
||||
while (page.has_more) {
|
||||
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
|
||||
const cursor = page.next_cursor
|
||||
@@ -358,6 +387,7 @@ export async function fetchAllQARecords(
|
||||
}
|
||||
page = mergeQAPages(page, next)
|
||||
onProgress?.(ids.size, total)
|
||||
onPage?.(page)
|
||||
}
|
||||
if (ids.size !== total) throw new Error('全量读取数量不完整,请重试,未将部分记录当作全部结果')
|
||||
return page
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildQAWeeklyCSV } from './qaWeekly'
|
||||
import { parseQualityFilters, qualityFiltersKey } from './qaOps'
|
||||
import type { QARecordPage, QARecord } from './qaOps'
|
||||
describe('quality filter and full-export contracts', () => {
|
||||
it('compares filters independently of property ordering and rejects unknown fields', () => {
|
||||
expect(qualityFiltersKey({ coverage: '是', is_correct: '否' })).toBe(
|
||||
qualityFiltersKey({ is_correct: '否', coverage: '是' })
|
||||
)
|
||||
expect(() => parseQualityFilters({ tenant: 'x' })).toThrow()
|
||||
expect(() => parseQualityFilters({ coverage: 4 })).toThrow()
|
||||
})
|
||||
it('rejects a complete-count page of truncated previews as a full export', () => {
|
||||
const page = {
|
||||
has_more: false,
|
||||
total: 1,
|
||||
items: [{ id: 'fixture', content_projection: 'summary' } as QARecord],
|
||||
} as QARecordPage
|
||||
expect(() => buildQAWeeklyCSV(page)).toThrow('预览')
|
||||
})
|
||||
})
|
||||
@@ -35,6 +35,8 @@ function csvCell(value: unknown) {
|
||||
return '"' + safe.replace(/"/g, '""') + '"'
|
||||
}
|
||||
export function buildQAWeeklyCSV(page: QARecordPage): string {
|
||||
if (page.items.some((row) => row.content_projection === 'summary'))
|
||||
throw Error('列表仅为预览,请重新读取完整明细后导出')
|
||||
if (page.has_more || page.total !== page.items.length || new Set(page.items.map((r) => r.id)).size !== page.total)
|
||||
throw Error('明细未完整读取,未导出部分数据')
|
||||
const csv =
|
||||
|
||||
Reference in New Issue
Block a user