feat(qaops): 完成详情下拉与每周自动保存草稿
build / build (push) Successful in 1m7s

详情使用共享主表字典,稀疏修改所选字段并保留原始问答及旧复核审计。
月周统计提供文本和下拉双入口;每租户每周一份持久草稿,按技能六节双语模板真实预填。
加入幂等自动保存、冲突保留、未知响应重试、切周及离开保护和schema58非破坏降级保护。

验证:完整make verify、隔离PostgreSQL全mirror竞态回归、真实恢复库浏览器验收通过。
浏览器实测字段精确读回、月周双输入、模板预填、MD/CSV、自动保存、冲突、失败重试与API重启恢复。
未连接或改写DobotAI生产源库,未运行付费模型;提交时尚未部署。
This commit is contained in:
姚章浩
2026-10-20 05:41:57 +08:00
parent 154b0b62ad
commit 87f97a2f9b
47 changed files with 2587 additions and 180 deletions
+19 -36
View File
@@ -2,11 +2,12 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import type { DepartmentStatisticsSnapshot, DepartmentStatisticsQuery } from './qaDepartmentStatistics'
import { fetchDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentTree, selectDepartmentBranch, subtreeIDs, defaultDepartmentCollapsed } from './qaRegionSelection'
import { currentQAWeek, qaWeek } from './qaWeeks'
import { currentQAWeekValue } from './qaWeeks'
import { bindOrganizationDepartments } from './qaOrg'
import type { RegionDefinition } from './qaOrg'
import { QARegions } from './QARegions'
import './qaDepartmentStatistics.css'
import { QAPeriodInput } from './QAPeriodInput'
export interface DepartmentStatisticsViewProps {
data: DepartmentStatisticsSnapshot
selected?: string[]
@@ -165,10 +166,7 @@ export function DepartmentRegionBinding({
</div>
)
}
const currentWeekValue = () => {
const w = currentQAWeek()
return `${w.year}-W${String(w.week).padStart(2, '0')}`
}
const currentWeekValue = currentQAWeekValue
export function QARegionalStatistics({ onSaved }: { onSaved?: () => void } = {}) {
const [period, setPeriod] = useState<'all' | 'month' | 'week'>('all'),
[month, setMonth] = useState(currentMonth),
@@ -325,39 +323,24 @@ export function QARegionalStatistics({ onSaved }: { onSaved?: () => void } = {})
</select>
</label>
{period === 'month' ? (
<label>
统计月份
<input
aria-label="部门统计月份"
type="month"
min="2000-01"
max={currentMonth()}
value={month}
onChange={(e) => setMonth(e.target.value)}
/>
</label>
<QAPeriodInput
kind="month"
label="统计月份"
ariaLabel="部门统计月份"
value={month}
max={currentMonth()}
onChange={setMonth}
/>
) : null}
{period === 'week' ? (
<label>
统计周次(北京时间周一至周日)
<input
aria-label="部门统计周次"
type="week"
min="2000-W01"
max={currentWeekValue()}
value={week}
onChange={(e) => setWeek(e.target.value)}
/>
<small>
{(() => {
try {
return qaWeek(Number(week.slice(0, 4)), Number(week.slice(6))).label
} catch {
return '请选择有效自然周'
}
})()}
</small>
</label>
<QAPeriodInput
kind="week"
label="统计周次(北京时间周一至周日)"
ariaLabel="部门统计周次"
value={week}
max={currentWeekValue()}
onChange={setWeek}
/>
) : null}
<label>
部门
+144
View File
@@ -0,0 +1,144 @@
import { useEffect, useRef, useState } from 'react'
import './qaPeriodInput.css'
import type { QARecord } from './qaOps'
import { qaColumns } from './qaOps'
import { editableFieldKeys, editableFieldValue, fetchFieldOptions, saveInlineField } from './qaInlineFields'
import type { EditableField, FieldOptions } from './qaInlineFields'
import { newOperationID } from './operationKey'
import { qaFieldColors } from './qaFieldColors'
export function QAInlineFields({
record,
onSaved,
onReload,
}: {
record: QARecord
onSaved: (record: QARecord) => void
onReload: () => void
}) {
const [options, setOptions] = useState<FieldOptions | null>(null),
[error, setError] = useState(''),
[notice, setNotice] = useState(''),
[saving, setSaving] = useState(false),
[reloadOptions, setReloadOptions] = useState(0)
const [pending, setPending] = useState<{
record: QARecord
field: EditableField
value: string
nonce: string
} | null>(null)
const writing = useRef<AbortController | null>(null)
useEffect(() => {
const c = new AbortController()
setError('')
void fetchFieldOptions(c.signal)
.then(setOptions)
.catch((e) => {
if (!c.signal.aborted) setError(e instanceof Error ? e.message : '主表选项读取失败')
})
return () => c.abort()
}, [reloadOptions])
useEffect(() => () => writing.current?.abort(), [])
const save = async (p: NonNullable<typeof pending>) => {
if (writing.current) return
const c = new AbortController()
writing.current = c
setSaving(true)
setError('')
setNotice('')
try {
const fresh = await saveInlineField(p.record, p.field, p.value, p.nonce, c.signal)
if (!c.signal.aborted) {
setPending(null)
onSaved(fresh)
setNotice('已保存')
}
} catch (e) {
if (!c.signal.aborted) setError(e instanceof Error ? e.message : '字段保存失败,选择尚未确认')
} finally {
writing.current = null
if (!c.signal.aborted) setSaving(false)
}
}
return (
<div className="qa-inline-fields">
<div className="qa-detail-quality" aria-label="固定质量字段">
{editableFieldKeys.map((field) => {
const value = pending?.field === field ? pending.value : editableFieldValue(record, field)
const rootNotNeeded = field === 'root_cause' && editableFieldValue(record, 'is_correct') === '是'
return (
<div key={field} data-quality-field={field}>
<label>
<span>{qaColumns.find((c) => c.key === field)!.label}</span>
<select
aria-label={`修改${qaColumns.find((c) => c.key === field)!.label}`}
title="选择后自动保存"
value={rootNotNeeded ? '' : value}
disabled={
saving || !!pending || !options || !record.record_origin || !record.quality || rootNotNeeded
}
style={qaFieldColors(field, value || '—')}
onChange={(e) => {
if (e.target.value === editableFieldValue(record, field)) return
try {
const next = { record, field, value: e.target.value, nonce: newOperationID() }
setPending(next)
void save(next)
} catch (e) {
setError(e instanceof Error ? e.message : '无法生成保存标识')
}
}}
>
<option value="" disabled>
{rootNotNeeded ? '无需根因' : '未设置'}
</option>
{value && !options?.[field].includes(value) ? (
<option value={value} disabled>
{value}
</option>
) : null}
{options?.[field].map((v) => (
<option key={v} value={v}>
{v}
</option>
))}
</select>
</label>
</div>
)
})}
</div>
{saving || notice ? (
<p className="qa-inline-save" role="status" aria-live="polite">
{saving ? '保存中…' : notice}
</p>
) : null}
{error ? (
<p role="alert" className="error-banner">
{error}{' '}
{pending ? (
<>
<button type="button" disabled={saving} onClick={() => void save(pending)}>
重试保存
</button>
<button
type="button"
disabled={saving}
onClick={() => {
setPending(null)
setError('')
onReload()
}}
>
放弃并重读
</button>
</>
) : (
<button type="button" onClick={() => setReloadOptions((v) => v + 1)}>
重试读取选项
</button>
)}
</p>
) : null}
</div>
)
}
+9
View File
@@ -52,6 +52,15 @@ const props = {
}
describe('QA operations workbench', () => {
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' }} />
)
const drawer = html.slice(html.indexOf('<aside'))
expect((drawer.match(/<select/g) ?? []).length).toBe(5)
for (const copy of ['人工复核与留档', '保存复核', '复核理由', '用户反馈', '质量留档/人工复核未配置'])
expect(drawer).not.toContain(copy)
})
it('shows each persisted AI task in the existing operation cell and explains positive master coverage', () => {
const withTasks = {
...item,
+22 -35
View File
@@ -8,7 +8,7 @@ import { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering'
import { QARegionalStatistics } from './QADepartmentStatistics'
import { QADashboard } from './QADashboard'
import { QAWeekly } from './QAWeekly'
import { QAQualityEditor } from './QAQuality'
import { QAInlineFields } from './QAInlineFields'
import { qaFieldColors, qaTagColumns } from './qaFieldColors'
import { qualityLabels } from './qaQuality'
import { QAWeekPicker } from './QAWeekPicker'
@@ -272,16 +272,12 @@ export function QAOperationsView(props: ViewProps) {
</button>
</header>
{detail ? (
<div className="qa-detail-quality" aria-label="固定质量字段">
{(['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'] as const).map((key) => (
<div key={key} data-quality-field={key}>
<span>{qaColumns.find((column) => column.key === key)!.label}</span>
<strong className="qa-field-tag" style={qaFieldColors(key, qaCellValue(detail, key) ?? '—')}>
{qaCellValue(detail, key) ?? '—'}
</strong>
</div>
))}
</div>
<QAInlineFields
key={detail.id}
record={detail}
onSaved={props.onQualitySaved ?? (() => {})}
onReload={props.onReloadDetail ?? (() => {})}
/>
) : null}
{props.detailLoading ? <p role="status">正在读取完整问答…</p> : null}
{props.detailError ? (
@@ -334,28 +330,6 @@ export function QAOperationsView(props: ViewProps) {
?.map((task) => task.updated_at)
.join(':')}
/>
{detail.quality ? (
<QAQualityEditor
key={detail.id}
recordId={detail.id}
dataset={detail.record_origin ? 'master' : undefined}
quality={detail.quality}
onSaved={props.onQualitySaved ?? (() => {})}
onReload={props.onReloadDetail ?? (() => {})}
/>
) : (
<p className="qa-ops-muted">质量留档/人工复核未配置。</p>
)}
<h4>用户反馈</h4>
<p>
提问人:
{detail.feedback.asker_value === 'up'
? '点赞'
: detail.feedback.asker_value === 'down'
? '点踩'
: '无反馈'}
;全部反馈:赞 {detail.feedback.up} / 踩 {detail.feedback.down}
</p>
<h4>引用知识</h4>
<pre>{JSON.stringify(detail.references, null, 2)}</pre>
<details>
@@ -379,6 +353,10 @@ function initialDraft() {
export function QAOperations() {
const [view, setView] = useState<QAOpsView>('records')
const weeklyBeforeLeave = useRef<(() => Promise<boolean>) | null>(null)
const registerWeeklyLeave = useCallback((guard: (() => Promise<boolean>) | null) => {
weeklyBeforeLeave.current = guard
}, [])
const auth = useOptionalAuth()
const canRead = auth?.identity?.role === 'admin'
const [draft, setDraft] = useState(initialDraft)
@@ -528,7 +506,16 @@ export function QAOperations() {
</p>
) : (
<>
<QAOperationsTabs view={view} onChange={setView} />
<QAOperationsTabs
view={view}
onChange={(next) => {
if (view === 'weekly' && next !== 'weekly' && weeklyBeforeLeave.current)
void weeklyBeforeLeave.current().then((ok) => {
if (ok) setView(next)
})
else setView(next)
}}
/>
{queryView ? (
<>
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
@@ -608,7 +595,7 @@ export function QAOperations() {
}}
/>
) : view === 'weekly' ? (
<QAWeekly query={query} />
<QAWeekly onBeforeLeave={registerWeeklyLeave} />
) : view === 'dashboard' ? (
<QADashboard
query={query}
+17
View File
@@ -0,0 +1,17 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect, vi } from 'vitest'
import { QAPeriodInput } from './QAPeriodInput'
describe('one period value with two input methods', () => {
it('offers a text input and dropdown for both months and ISO weeks', () => {
for (const kind of ['month', 'week'] as const) {
const value = kind === 'month' ? '2026-10' : '2026-W43'
const html = renderToStaticMarkup(
<QAPeriodInput kind={kind} label="统计周期" ariaLabel="测试周期" value={value} max={value} onChange={vi.fn()} />
)
expect(html).toContain('type="text"')
expect(html).toContain('<select')
expect(html).toContain(`value="${value}"`)
expect(html).toContain('测试周期下拉选择')
}
})
})
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useId, useMemo, useState } from 'react'
import type { QAPeriodKind } from './qaPeriodInput'
import { periodInputOptions, validPeriodInput } from './qaPeriodInput'
import { qaWeek } from './qaWeeks'
import './qaPeriodInput.css'
export interface QAPeriodInputProps {
kind: QAPeriodKind
label: string
ariaLabel: string
value: string
max: string
onChange: (value: string) => void
disabled?: boolean
}
export function QAPeriodInput(p: QAPeriodInputProps) {
const id = useId(),
[text, setText] = useState(p.value),
[error, setError] = useState('')
useEffect(() => {
setText(p.value)
setError('')
}, [p.value, p.kind])
const options = useMemo(() => {
const values = periodInputOptions(p.kind, p.max)
if (validPeriodInput(p.kind, p.value, p.max) && !values.includes(p.value)) values.push(p.value)
return values
}, [p.kind, p.max, p.value])
const apply = () => {
if (text === p.value) return
if (!validPeriodInput(p.kind, text, p.max)) {
setError(
`请输入有效的${p.kind === 'month' ? 'YYYY-MM月份' : 'YYYY-Www自然周'},最早2000年、不晚于${p.max};仍显示${p.value}的结果`
)
return
}
setError('')
p.onChange(text)
}
return (
<div className="qa-period-input">
<label htmlFor={id}>{p.label}</label>
<div className="qa-period-combo">
<input
id={id}
type="text"
aria-label={p.ariaLabel}
aria-describedby={`${id}-hint`}
aria-invalid={!!error}
autoComplete="off"
spellCheck={false}
value={text}
disabled={p.disabled}
placeholder={p.kind === 'month' ? 'YYYY-MM' : 'YYYY-Www'}
onChange={(e) => {
setText(e.target.value)
setError('')
}}
onBlur={apply}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
apply()
}
if (e.key === 'Escape') {
setText(p.value)
setError('')
}
}}
/>
<select
aria-label={`${p.ariaLabel}下拉选择`}
value=""
disabled={p.disabled}
onChange={(e) => {
const value = e.target.value
if (!value) return
setText(value)
setError('')
p.onChange(value)
}}
>
<option value="" disabled>
选择
</option>
{options.map((v) => (
<option key={v} value={v}>
{p.kind === 'week' ? `${v} ${qaWeek(Number(v.slice(0, 4)), Number(v.slice(6))).label}` : v}
</option>
))}
</select>
</div>
<small id={`${id}-hint`} role={error ? 'alert' : undefined}>
{error ||
(text !== p.value
? '尚未应用,按回车或移开输入框确认'
: p.kind === 'week'
? qaWeek(Number(p.value.slice(0, 4)), Number(p.value.slice(6))).label
: '可下拉选择,也可直接输入')}
</small>
</div>
)
}
+255 -79
View File
@@ -1,97 +1,273 @@
import { useEffect, useRef, useState } from 'react'
import { useDeferredValue, useEffect, useState, useSyncExternalStore } from 'react'
import type { QAQuery } from './qaOps'
import { fetchAllQARecords } from './qaOps'
import { fetchQADashboardQuality } from './qaDashboard'
import { fetchQAMirrorStatus } from './qaMirror'
import { buildQAWeeklyDraft, downloadQAWeekly } from './qaWeekly'
import type { QAWeeklyDraft } from './qaWeekly'
import { currentQAWeekValue, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
import { WeeklyDraftEditorModel } from './qaWeeklyDrafts'
import { weeklyTransport } from './qaWeeklyDraftAPI'
import { buildQAWeeklyCSV, downloadQAWeekly } from './qaWeekly'
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
export function QAWeekly({ query }: { query: QAQuery | null }) {
const [draft, setDraft] = useState<QAWeeklyDraft | null>(null),
[loading, setLoading] = useState(false),
[error, setError] = useState('')
const request = useRef<AbortController | null>(null)
import { QAPeriodInput } from './QAPeriodInput'
import './qaWeeklyEditor.css'
type LeaveGuard = (() => Promise<boolean>) | null
interface Props {
query?: QAQuery | null
onBeforeLeave?: (guard: LeaveGuard) => void
}
export function QAWeekly({ onBeforeLeave }: Props) {
const [model] = useState(() => new WeeklyDraftEditorModel(currentQAWeekValue(), weeklyTransport))
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot)
const [mode, setMode] = useState<'edit' | 'preview' | 'both'>('both'),
[replaceConfirm, setReplaceConfirm] = useState(false),
[reloadConfirm, setReloadConfirm] = useState(false),
[periodReset, setPeriodReset] = useState(0),
[exporting, setExporting] = useState(false),
[exportError, setExportError] = useState('')
const preview = useDeferredValue(state.text)
useEffect(() => {
request.current?.abort()
setDraft(null)
setError('')
setLoading(false)
return () => request.current?.abort()
}, [query])
const generate = async () => {
if (!query || loading) return
request.current?.abort()
const controller = new AbortController()
request.current = controller
setLoading(true)
setDraft(null)
setError('')
void model.initialize()
const unload = (e: BeforeUnloadEvent) => {
if (model.dirty || model.uncertainPrefill) {
e.preventDefault()
e.returnValue = ''
}
}
window.addEventListener('beforeunload', unload)
return () => {
window.removeEventListener('beforeunload', unload)
if (model.dirty && !model.uncertainPrefill) void model.beforeLeave().finally(() => model.dispose())
else model.dispose()
}
}, [model])
useEffect(() => {
onBeforeLeave?.(() => model.beforeLeave())
return () => onBeforeLeave?.(null)
}, [model, onBeforeLeave])
const blocked = state.busy || state.loading || !state.document || model.uncertainPrefill
const status = state.loading
? 'loading'
: state.saving
? 'saving'
: state.busy
? 'working'
: state.error
? 'error'
: model.dirty
? 'dirty'
: state.document?.revision
? 'saved'
: 'empty'
const source = state.document?.seed
const generate = () => {
setReplaceConfirm(false)
setReloadConfirm(false)
void model.prefill()
}
const csv = async () => {
if (exporting) return
setExporting(true)
setExportError('')
try {
const before = await fetchQAMirrorStatus(controller.signal)
if (!before.ready || before.blocked) throw Error('本地同步未就绪,暂不能生成周报')
const [page, quality] = await Promise.all([
fetchAllQARecords(query, controller.signal),
fetchQADashboardQuality(query, controller.signal),
])
const after = await fetchQAMirrorStatus(controller.signal)
if (!after.ready || after.blocked || before.revision !== after.revision || page.local_revision !== after.revision)
throw Error('本地副本在生成期间已更新,请重新生成')
const result = buildQAWeeklyDraft(page, query, quality, new Date().toISOString())
if (!controller.signal.aborted) setDraft(result)
const range = qaWeekQueryRange(Number(state.week.slice(0, 4)), Number(state.week.slice(6)))
const start = typeof source?.start === 'string' ? source.start : qaDateTimeToISO(range.start),
end = typeof source?.end === 'string' ? source.end : qaDateTimeToISO(range.end)
const page = await fetchAllQARecords({ dataset: 'master', start, end, keyword: '', cursor: '' })
downloadQAWeekly(buildQAWeeklyCSV(page), `DobotAI-Questions-${state.week}.csv`, 'text/csv;charset=utf-8')
} catch (e) {
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '周报生成失败')
setExportError(e instanceof Error ? e.message : '明细导出失败')
} finally {
if (!controller.signal.aborted) setLoading(false)
setExporting(false)
}
}
const suffix = query ? new Date(Date.parse(query.start) + 8 * 60 * 60 * 1000).toISOString().slice(0, 10) : 'draft'
return (
<section className="qa-weekly" aria-label="周报生成">
<header className="qa-weekly-toolbar">
<div>
<h3>周报生成</h3>
{query ? (
<span>
{new Date(query.start).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })} 至{' '}
{new Date(Date.parse(query.end) - 1).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })}
</span>
) : null}
<section className="qa-weekly qa-weekly-editor" aria-label="周报生成" data-weekly-week={state.week}>
<header className="qa-weekly-editor-header">
<h3>周报草稿</h3>
<QAPeriodInput
key={`${state.week}:${periodReset}`}
kind="week"
label="周报周次"
ariaLabel="周报周次"
value={state.week}
max={currentQAWeekValue()}
disabled={state.busy || state.loading}
onChange={(week) => {
setReplaceConfirm(false)
setReloadConfirm(false)
setExportError('')
void model.switchWeek(week).then((ok) => {
if (!ok) setPeriodReset((v) => v + 1)
})
}}
/>
<div className="qa-weekly-editor-actions">
{replaceConfirm ? (
<>
<button type="button" className="qa-weekly-prefill" onClick={() => setReplaceConfirm(false)}>
取消
</button>
<button type="button" onClick={generate}>
确认替换预填
</button>
</>
) : (
<button
type="button"
className="qa-weekly-prefill"
disabled={blocked || state.errorKind === 'conflict'}
onClick={() => {
if (state.document?.revision || state.text) setReplaceConfirm(true)
else generate()
}}
>
{state.document?.revision ? '重新预填数据' : '生成并预填草稿'}
</button>
)}
<button
type="button"
disabled={blocked || !model.dirty || state.saving || state.errorKind === 'conflict'}
onClick={() => void model.beforeLeave()}
>
立即保存
</button>
<button
type="button"
disabled={!state.document}
onClick={() =>
downloadQAWeekly(state.text, `DobotAI_KB_Weekly_Report_${state.week}.md`, 'text/markdown;charset=utf-8')
}
>
下载 MD
</button>
<button type="button" disabled={!state.document || exporting || state.busy} onClick={() => void csv()}>
{exporting ? '导出中…' : '下载明细 CSV'}
</button>
</div>
<button type="button" onClick={() => void generate()} disabled={loading || !query}>
{loading ? '正在生成…' : '生成周报草稿'}
</button>
{draft ? (
<>
<span className="qa-weekly-badge">草稿 · {draft.questions} 条</span>
<button
type="button"
onClick={() =>
downloadQAWeekly(draft.markdown, `DobotAI-问答周报-${suffix}.md`, 'text/markdown;charset=utf-8')
}
>
下载 MD
</button>
<button
type="button"
onClick={() => downloadQAWeekly(draft.csv, `DobotAI-问题明细-${suffix}.csv`, 'text/csv;charset=utf-8')}
>
下载明细 CSV
</button>
</>
) : null}
</header>
{error ? (
<div className="qa-weekly-editor-toolbar">
<div className="qa-weekly-mode" aria-label="编辑与预览">
{(['edit', 'preview', 'both'] as const).map((value) => (
<button type="button" key={value} aria-pressed={mode === value} onClick={() => setMode(value)}>
{{ edit: '编辑', preview: '预览', both: '对照' }[value]}
</button>
))}
</div>
<span role="status" aria-live="polite" className="qa-weekly-editor-status" data-weekly-save-state={status}>
自动保存 ·{' '}
{
{
loading: '正在读取草稿…',
saving: '保存中…',
working: '正在处理…',
error: '未保存或尚未确认',
dirty: '待保存',
saved: '已保存',
empty: '尚未创建',
}[status]
}
{status === 'saved' && state.document?.updated_at
? ` · ${new Date(state.document.updated_at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })}`
: ''}
</span>
</div>
{replaceConfirm ? (
<p className="qa-ops-warning">将先保存当前文字,再用最新统计替换正文;旧保存版本保留。请确认后继续。</p>
) : null}
{state.error ? (
<div role="alert" className="error-banner">
{state.error}
{state.errorKind === 'load' ? (
<button type="button" disabled={state.busy} onClick={() => void model.reload()}>
重试读取
</button>
) : state.errorKind === 'save' ? (
<button type="button" disabled={state.saving || state.busy} onClick={() => void model.beforeLeave()}>
重试保存
</button>
) : state.errorKind === 'prefill' ? (
<button type="button" disabled={state.busy} onClick={generate}>
重试确认预填
</button>
) : null}
{reloadConfirm ? (
<>
<button type="button" className="qa-weekly-reload" onClick={() => setReloadConfirm(false)}>
取消
</button>
<button
type="button"
disabled={state.saving || state.busy}
onClick={() => {
setReloadConfirm(false)
void model.reload()
}}
>
放弃本地修改并读取
</button>
</>
) : (
<button
type="button"
className="qa-weekly-reload"
disabled={state.busy || state.saving}
onClick={() => setReloadConfirm(true)}
>
重新读取服务器版本
</button>
)}
</div>
) : null}
{exportError ? (
<p role="alert" className="error-banner">
{error}
{exportError}
</p>
) : null}
{draft ? (
<article className="qa-weekly-preview">
<QAAnswerMarkdown answer={draft.markdown} />
</article>
) : (
<div className="qa-weekly-empty">{loading ? '正在汇总本地问答…' : '尚未生成周报。'}</div>
)}
<div className="qa-weekly-editor-layout" data-mode={mode}>
{mode !== 'preview' ? (
<div className="qa-weekly-writing">
<label htmlFor="qa-weekly-body">
周报草稿正文 <small>Markdown</small>
</label>
<textarea
id="qa-weekly-body"
aria-label="周报草稿正文"
value={state.text}
disabled={blocked}
spellCheck={false}
placeholder="生成并预填草稿,或直接输入。英文完整部分在上,中文在下;输入后自动保存。"
onChange={(e) => model.setText(e.target.value)}
onKeyDown={(e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
e.preventDefault()
void model.beforeLeave()
}
}}
/>
</div>
) : null}
{mode !== 'edit' ? (
<article className="qa-weekly-preview" aria-label="周报预览">
{preview ? <QAAnswerMarkdown answer={preview} /> : <p className="qa-ops-muted">尚无草稿正文。</p>}
</article>
) : null}
</div>
{source && source.source === 'governance-master' ? (
<details className="qa-weekly-source">
<summary>预填来源</summary>
<p>
治理正式总表 · {String(source.week)} · 截至{' '}
{typeof source.end === 'string'
? new Date(source.end).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
: '—'}{' '}
·{' '}
{{ 'live-week': '当周实时质量指标', 'frozen-week': '已冻结周指标', 'reported-history': '历史上报指标' }[
String(source.quality_source)
] ?? '指标来源未确认'}
</p>
<p>
问题总数与新增是可编辑的系统统计建议;区域采用已保存配置及当前通讯录。未做新的FAQ调整,重点与英文文字请自行填写。草稿不会自动发送。
</p>
</details>
) : null}
</section>
)
}
+15
View File
@@ -0,0 +1,15 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect } from 'vitest'
import { QAWeekly } from './QAWeekly'
describe('weekly report editor surface', () => {
it('provides a weekly document editor, automatic-save status and a preview without an external-send action', () => {
const html = renderToStaticMarkup(<QAWeekly query={null} />)
expect(html).toContain('<textarea')
expect(html).toContain('周报草稿正文')
expect(html).toContain('自动保存')
expect(html).toContain('周报周次下拉选择')
expect(html).toContain('预览')
expect(html).not.toContain('发送周报')
expect(html).not.toContain('发布周报')
})
})
+73
View File
@@ -0,0 +1,73 @@
import { fetchQARecord, getPayload, qaCellValue } from './qaOps'
import type { QARecord } from './qaOps'
export const editableFieldKeys = ['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'] as const
export type EditableField = (typeof editableFieldKeys)[number]
export type FieldOptions = Record<EditableField, string[]>
export function parseFieldOptions(raw: unknown): FieldOptions {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw Error('主表选项读取失败')
const v = raw as Record<string, unknown>
if (v.version !== 'qa-master-options-v1' || !v.fields || typeof v.fields !== 'object' || Array.isArray(v.fields))
throw Error('主表选项版本无效')
const fields = v.fields as Record<string, unknown>
if (Object.keys(fields).length !== editableFieldKeys.length) throw Error('主表选项不完整')
const result = {} as FieldOptions
for (const key of editableFieldKeys) {
const values = fields[key]
if (
!Array.isArray(values) ||
!values.length ||
values.some((v) => typeof v !== 'string' || !v.trim()) ||
new Set(values).size !== values.length
)
throw Error('主表选项不完整')
result[key] = values as string[]
}
return result
}
export async function fetchFieldOptions(signal?: AbortSignal) {
return parseFieldOptions(await getPayload('/api/v1/qa-ops/master/field-options', signal))
}
export function editableFieldValue(record: QARecord, field: EditableField): string {
if (field === 'root_cause' && qaCellValue(record, 'is_correct') === '是') return ''
const value = qaCellValue(record, field) ?? ''
return field === 'coverage' && value === '不计入' ? '否但不计入' : value
}
export async function saveInlineField(
record: QARecord,
field: EditableField,
value: string,
nonce: string,
signal?: AbortSignal
): Promise<QARecord> {
if (!record.record_origin || !record.quality) throw Error('此记录暂不可修改,请重新读取')
const q = record.quality
const raw = await getPayload(`/api/v1/qa-ops/master/records/${encodeURIComponent(record.id)}/fields`, signal, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-master-fields' },
body: JSON.stringify({
input_hash: q.input_hash,
input_epoch: q.input_epoch,
base_revision: record.field_edit_revision ?? 0,
base_review_revision: q.revision,
nonce,
fields: { [field]: value },
}),
})
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw Error('字段保存回执无效,请重试读取')
const receipt = raw as Record<string, unknown>
if (
!Number.isSafeInteger(receipt.saved_revision) ||
Number(receipt.saved_revision) < 1 ||
typeof receipt.replayed !== 'boolean'
)
throw Error('字段保存回执无效,请重试读取')
const fresh = await fetchQARecord(record.id, signal, 'master')
if (
fresh.field_edit_revision !== receipt.saved_revision ||
fresh.quality?.input_hash !== q.input_hash ||
fresh.quality.revision !== q.revision ||
editableFieldValue(fresh, field) !== value
)
throw Error('保存后字段再次变化,未将旧结果标为成功,请重新读取核对')
return fresh
}
+18 -1
View File
@@ -84,6 +84,7 @@ export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecor
}
}
export interface QARecord {
field_edit_revision?: number
background_tasks?: AIWorkState[]
record_origin?: 'dobotai_2_0' | 'historical_excel'
master_fields?: Partial<Record<QAColumn, string>>
@@ -215,6 +216,7 @@ export function parseQARecord(value: unknown): QARecord {
if (typeof row.is_correct !== 'boolean' && row.is_correct !== null) return invalid()
item.is_correct = row.is_correct
}
if (row.field_edit_revision !== undefined) item.field_edit_revision = count(row.field_edit_revision)
if (row.record_origin !== undefined) {
if (row.record_origin !== 'dobotai_2_0' && row.record_origin !== 'historical_excel') return invalid()
item.record_origin = row.record_origin
@@ -291,6 +293,16 @@ export function parseQARecordPage(value: unknown): QARecordPage {
}
}
export class QARequestError extends Error {
constructor(
message: string,
public readonly status: number
) {
super(message)
this.name = 'QARequestError'
}
}
export async function getPayload(
path: string,
signal?: AbortSignal,
@@ -300,7 +312,10 @@ export async function getPayload(
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
const payload = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null
throw new Error(typeof payload?.error === 'string' ? payload.error : `问答数据读取失败(HTTP ${response.status})`)
throw new QARequestError(
typeof payload?.error === 'string' ? payload.error : `问答数据读取失败(HTTP ${response.status})`,
response.status
)
}
return object(raw).data
}
@@ -399,6 +414,8 @@ const qaAskedAtFormatter = new Intl.DateTimeFormat('zh-CN', {
})
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (column === 'root_cause' && item.field_edit_revision && item.quality?.effective.correctness === 'correct')
return null
if (column === 'trigger_person') return triggerPersonName(item.master_fields?.trigger_person ?? item.trigger_person)
const reviewedQuality =
+89
View File
@@ -0,0 +1,89 @@
.qa-period-input {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
max-width: 100%;
font-size: 13px;
}
.qa-period-combo {
display: flex;
align-items: stretch;
width: 240px;
max-width: 100%;
border: 1px solid #d7e0eb;
border-radius: 8px;
background: #fff;
overflow: hidden;
}
.qa-period-combo input {
min-width: 0;
width: 100%;
flex: 1;
border: 0 !important;
border-radius: 0 !important;
background: transparent;
padding: 8px 10px;
font: inherit;
}
.qa-period-combo select {
width: 74px;
min-width: 74px;
border: 0 !important;
border-left: 1px solid #e3e9f0 !important;
border-radius: 0 !important;
background: #f5f8fc;
padding: 7px 5px;
font: inherit;
cursor: pointer;
}
.qa-period-combo:focus-within {
outline: 2px solid #83b6f4;
outline-offset: 1px;
}
.qa-period-input small {
font-size: 12px;
color: #64748b;
max-width: 360px;
white-space: normal;
}
.qa-period-input small[role='alert'] {
color: #b42318;
}
.qa-period-combo input[aria-invalid='true'] {
background: #fff4f2;
}
.qa-inline-fields {
flex: none;
min-width: 0;
}
.qa-inline-fields .qa-detail-quality label {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.qa-inline-fields .qa-detail-quality select {
min-width: 0;
width: 100%;
max-width: 100%;
border: 1px solid #d7e0eb;
border-radius: 6px;
padding: 6px 4px;
font: inherit;
font-weight: 600;
cursor: pointer;
}
.qa-inline-fields .qa-detail-quality select:disabled {
cursor: default;
opacity: 0.75;
}
.qa-inline-save {
margin: 2px 18px 6px;
font-size: 12px;
color: #35634c;
}
.qa-inline-fields > .error-banner {
margin: 4px 18px 8px;
font-size: 12px;
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest'
import { validPeriodInput, periodInputOptions } from './qaPeriodInput'
describe('typed or dropdown natural periods', () => {
it('accepts canonical months and real cross-year weeks and rejects incomplete, future or impossible inputs', () => {
expect(validPeriodInput('month', '2026-02', '2026-10')).toBe(true)
expect(validPeriodInput('week', '2020-W53', '2021-W01')).toBe(true)
for (const value of ['', '2026-1', '2026-00', '2026-13', '2027-01', ' 2026-02', '1999-12'])
expect(validPeriodInput('month', value, '2026-10')).toBe(false)
for (const value of ['', '2021-W53', '2021-W1', '2021-W00', '2026-W44', '2020-W+1', '2020-W53 '])
expect(validPeriodInput('week', value, '2026-W43')).toBe(false)
})
it('offers selectable periods across year boundaries without replacing the typed value with an invalid date', () => {
expect(periodInputOptions('week', '2021-W01').slice(0, 2)).toEqual(['2021-W01', '2020-W53'])
expect(periodInputOptions('month', '2026-01').slice(0, 2)).toEqual(['2026-01', '2025-12'])
expect(periodInputOptions('week', '2021-W53')).toEqual([])
})
})
+44
View File
@@ -0,0 +1,44 @@
import { qaWeek, currentQAWeek, qaWeekValue } from './qaWeeks'
export type QAPeriodKind = 'month' | 'week'
export function validPeriodInput(kind: QAPeriodKind, value: string, max?: string): boolean {
const pattern = kind === 'month' ? /^[0-9]{4}-[0-9]{2}$/ : /^[0-9]{4}-W[0-9]{2}$/
if (!pattern.test(value)) return false
const year = Number(value.slice(0, 4))
if (year < 2000 || year > 9998) return false
if (kind === 'month') {
const month = Number(value.slice(5))
if (month < 1 || month > 12) return false
} else {
try {
qaWeek(year, Number(value.slice(6)))
} catch {
return false
}
}
return !max || (validPeriodInput(kind, max) && value <= max)
}
export function periodInputOptions(kind: QAPeriodKind, max: string): string[] {
if (!validPeriodInput(kind, max)) return []
const result: string[] = []
if (kind === 'month') {
let year = Number(max.slice(0, 4)),
month = Number(max.slice(5))
for (let i = 0; i < 36 && year >= 2000; i++) {
result.push(`${year}-${String(month).padStart(2, '0')}`)
month--
if (month === 0) {
year--
month = 12
}
}
} else {
const start = qaWeek(Number(max.slice(0, 4)), Number(max.slice(6))).start
const monday = Date.parse(`${start}:00Z`)
for (let i = 0; i < 156; i++) {
const p = currentQAWeek(new Date(monday - i * 7 * 86400000))
if (p.year < 2000) break
result.push(qaWeekValue(p))
}
}
return result
}
+13 -6
View File
@@ -24,6 +24,18 @@ function csvCell(value: unknown) {
const safe = /^[\t\r\n]|^\s*[=+\-@]/.test(v) ? "'" + v : v
return '"' + safe.replace(/"/g, '""') + '"'
}
export function buildQAWeeklyCSV(page: QARecordPage): string {
if (page.has_more || page.total !== page.items.length || new Set(page.items.map((r) => r.id)).size !== page.total)
throw Error('明细未完整读取,未导出部分数据')
const csv =
'\ufeff' +
[
qaColumns.map((c) => csvCell(c.label)).join(','),
...page.items.map((row) => qaColumns.map((c) => csvCell(qaCellValue(row, c.key))).join(',')),
].join('\r\n')
return csv
}
export function buildQAWeeklyDraft(
page: QARecordPage,
query: QAQuery,
@@ -106,12 +118,7 @@ export function buildQAWeeklyDraft(
]
.filter(Boolean)
.join('\n\n') + '\n'
const csv =
'\ufeff' +
[
qaColumns.map((c) => csvCell(c.label)).join(','),
...page.items.map((row) => qaColumns.map((c) => csvCell(qaCellValue(row, c.key))).join(',')),
].join('\r\n')
const csv = buildQAWeeklyCSV(page)
return {
markdown: md.replace(/\|\n\n\|/g, '|\n|'),
csv,
+54
View File
@@ -0,0 +1,54 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { parseWeeklyDocument, weeklyTransport } from './qaWeeklyDraftAPI'
afterEach(() => vi.unstubAllGlobals())
const empty = { week: '2026-W41', revision: 0, markdown: '', seed: {}, updated_at: null }
describe('weekly document protocol', () => {
it('verifies an exact GET after POST and refuses a newer conflicting head', async () => {
const document = { ...empty, revision: 1, markdown: '用户正文', updated_at: '2026-10-19T10:00:00Z' }
const fetch = vi
.fn()
.mockResolvedValueOnce(
new Response(JSON.stringify({ data: { draft: document, replayed: false } }), { status: 200 })
)
.mockResolvedValueOnce(new Response(JSON.stringify({ data: document }), { status: 200 }))
vi.stubGlobal('fetch', fetch)
expect(
await weeklyTransport.write(empty.week, {
base_revision: 0,
nonce: 'fixture_client_weekly_0001',
markdown: document.markdown,
})
).toEqual(document)
expect(fetch.mock.calls).toHaveLength(2)
expect(fetch.mock.calls[0][1].method).toBe('POST')
expect(fetch.mock.calls[1][1].method ?? 'GET').toBe('GET')
fetch
.mockResolvedValueOnce(
new Response(JSON.stringify({ data: { draft: document, replayed: true } }), { status: 200 })
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ data: { ...document, revision: 2, markdown: 'another editor' } }), {
status: 200,
})
)
await expect(
weeklyTransport.write(empty.week, {
base_revision: 0,
nonce: 'fixture_client_weekly_0001',
markdown: document.markdown,
})
).rejects.toMatchObject({ status: 409 })
})
it('refuses foreign weeks, fabricated saved content and invalid revisions rather than showing false success', () => {
expect(parseWeeklyDocument(empty, empty.week)).toEqual(empty)
for (const value of [
{ ...empty, week: '2026-W40' },
{ ...empty, revision: -1 },
{ ...empty, revision: 0, markdown: 'invented persisted content' },
{ ...empty, revision: 1, updated_at: null },
{ ...empty, seed: [] },
{ ...empty, markdown: 9 },
])
expect(() => parseWeeklyDocument(value, empty.week)).toThrow()
})
})
+63
View File
@@ -0,0 +1,63 @@
import type { WeeklyDocument, WeeklyTransport } from './qaWeeklyDrafts'
import { validPeriodInput } from './qaPeriodInput'
import { getPayload, QARequestError } from './qaOps'
import type { WeeklyWriteRequest, WeeklyPrefillRequest } from './qaWeeklyDrafts'
const invalid = (): never => {
throw Error('草稿响应无效,未展示或标记为已保存')
}
export function parseWeeklyDocument(value: unknown, week: string): WeeklyDocument {
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid()
const v = value as Record<string, unknown>
if (
v.week !== week ||
!validPeriodInput('week', week) ||
typeof v.revision !== 'number' ||
!Number.isSafeInteger(v.revision) ||
v.revision < 0 ||
typeof v.markdown !== 'string' ||
new TextEncoder().encode(v.markdown).length > 256 * 1024 ||
!v.seed ||
typeof v.seed !== 'object' ||
Array.isArray(v.seed)
)
return invalid()
if (v.revision === 0) {
if (v.markdown !== '' || v.updated_at !== null || Object.keys(v.seed).length) return invalid()
} else if (typeof v.updated_at !== 'string' || !Number.isFinite(Date.parse(v.updated_at))) return invalid()
return {
week,
revision: v.revision,
markdown: v.markdown,
seed: v.seed as Record<string, unknown>,
updated_at: v.updated_at as string | null,
}
}
const endpoint = (week: string) => `/api/v1/qa-ops/master/weekly-drafts/${encodeURIComponent(week)}`
async function read(week: string) {
return parseWeeklyDocument(await getPayload(endpoint(week)), week)
}
async function save(week: string, q: WeeklyWriteRequest | WeeklyPrefillRequest, prefill: boolean) {
const raw = await getPayload(endpoint(week) + (prefill ? '/prefill' : ''), undefined, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-weekly-draft' },
body: JSON.stringify(q),
})
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return invalid()
const receipt = raw as Record<string, unknown>,
draft = parseWeeklyDocument(receipt.draft, week)
if (
typeof receipt.replayed !== 'boolean' ||
draft.revision !== q.base_revision + 1 ||
(!prefill && draft.markdown !== (q as WeeklyWriteRequest).markdown)
)
return invalid()
const current = await read(week)
if (current.revision !== draft.revision || current.markdown !== draft.markdown)
throw new QARequestError('本周草稿在保存后又发生变化;你的文字仍保留,请核对服务器版本', 409)
return current
}
export const weeklyTransport: WeeklyTransport = {
read,
write: (week, q) => save(week, q, false),
prefill: (week, q) => save(week, q, true),
}
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { WeeklyDraftEditorModel } from './qaWeeklyDrafts'
import type { WeeklyDocument, WeeklyWriteRequest } from './qaWeeklyDrafts'
const empty: WeeklyDocument = { week: '2026-W41', revision: 0, markdown: '', seed: {}, updated_at: null }
const saved = (q: WeeklyWriteRequest): WeeklyDocument => ({
...empty,
revision: q.base_revision + 1,
markdown: q.markdown,
updated_at: '2026-10-19T10:00:00Z',
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
describe('weekly draft autosave model', () => {
it('retains input and reports a safe failure if an operation identifier cannot be created', async () => {
const write = vi.fn()
const model = new WeeklyDraftEditorModel(empty.week, { read: async () => empty, write, prefill: vi.fn() })
await model.initialize()
model.setText('不可丢失的输入')
vi.stubGlobal('crypto', undefined)
expect(await model.flush()).toBe(false)
expect(model.state.text).toBe('不可丢失的输入')
expect(model.state.errorKind).toBe('save')
expect(write).not.toHaveBeenCalled()
model.dispose()
})
it('does not regenerate an existing draft on opening and saves edited text before explicit replacement', async () => {
const initial = { ...empty, revision: 1, markdown: '原草稿', updated_at: '2026-10-19T10:00:00Z' }
const write = vi.fn(async (_week: string, q: WeeklyWriteRequest) => saved(q)),
prefill = vi.fn(async (week: string, q: { base_revision: number; nonce: string }) => ({
...initial,
week,
revision: q.base_revision + 1,
markdown: '新预填模板',
}))
const model = new WeeklyDraftEditorModel(empty.week, { read: async () => initial, write, prefill })
await model.initialize()
expect(prefill).not.toHaveBeenCalled()
model.setText('用户原稿的最后输入')
expect(await model.prefill()).toBe(true)
expect(write.mock.calls[0][1].markdown).toBe('用户原稿的最后输入')
expect(prefill.mock.calls[0][1].base_revision).toBe(2)
expect(model.state.text).toBe('新预填模板')
expect(model.state.document?.revision).toBe(3)
model.dispose()
})
it('saves outstanding text before switching weeks and restores each week independently', async () => {
const documents = new Map<string, WeeklyDocument>([
[empty.week, empty],
[
'2026-W40',
{ ...empty, week: '2026-W40', revision: 4, markdown: '上周原稿', updated_at: '2026-10-19T10:00:00Z' },
],
])
const read = vi.fn(async (week: string) => documents.get(week)!),
write = vi.fn(async (week: string, q: WeeklyWriteRequest) => {
const value = { ...saved(q), week }
documents.set(week, value)
return value
})
const model = new WeeklyDraftEditorModel(empty.week, { read, write, prefill: vi.fn() })
await model.initialize()
model.setText('本周未保存输入')
expect(await model.switchWeek('2026-W40')).toBe(true)
expect(write.mock.calls[0][1].markdown).toBe('本周未保存输入')
expect(model.state.text).toBe('上周原稿')
expect(await model.switchWeek(empty.week)).toBe(true)
expect(model.state.text).toBe('本周未保存输入')
model.dispose()
})
it('retries the identical uncertain request before sending newer keystrokes and blocks week changes on failure', async () => {
const write = vi
.fn<(_: string, q: WeeklyWriteRequest) => Promise<WeeklyDocument>>()
.mockRejectedValueOnce(Error('网络断开'))
.mockImplementation(async (_week, q) => saved(q))
const model = new WeeklyDraftEditorModel(empty.week, { read: async () => empty, write, prefill: vi.fn() })
await model.initialize()
model.setText('original')
expect(await model.flush()).toBe(false)
const request = write.mock.calls[0][1]
expect(model.state.errorKind).toBe('save')
model.setText('newer input after failure')
expect(await model.flush()).toBe(true)
expect(write.mock.calls[1][1]).toEqual(request)
expect(write.mock.calls[2][1].base_revision).toBe(1)
expect(write.mock.calls[2][1].markdown).toBe('newer input after failure')
expect(write.mock.calls[2][1].nonce).not.toBe(request.nonce)
expect(model.state.document?.revision).toBe(2)
model.dispose()
})
it('debounces continuous typing and persists the latest exact text, not the initial keystroke', async () => {
vi.useFakeTimers()
const write = vi.fn(async (_week: string, q: WeeklyWriteRequest) => saved(q))
const model = new WeeklyDraftEditorModel(empty.week, { read: async () => empty, write, prefill: vi.fn() })
await model.initialize()
model.setText('first')
await vi.advanceTimersByTimeAsync(500)
model.setText('最后输入 / last edit')
await vi.advanceTimersByTimeAsync(799)
expect(write).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1)
expect(write).toHaveBeenCalledTimes(1)
expect(write.mock.calls[0][1].markdown).toBe('最后输入 / last edit')
expect(model.state.document?.markdown).toBe('最后输入 / last edit')
expect(model.state.error).toBe('')
model.dispose()
})
})
+229
View File
@@ -0,0 +1,229 @@
import { newOperationID } from './operationKey'
export interface WeeklyDocument {
week: string
revision: number
markdown: string
seed: Record<string, unknown>
updated_at: string | null
}
export interface WeeklyWriteRequest {
base_revision: number
nonce: string
markdown: string
}
export interface WeeklyPrefillRequest {
base_revision: number
nonce: string
}
export interface WeeklyTransport {
read: (week: string) => Promise<WeeklyDocument>
write: (week: string, q: WeeklyWriteRequest) => Promise<WeeklyDocument>
prefill: (week: string, q: WeeklyPrefillRequest) => Promise<WeeklyDocument>
}
export interface WeeklyEditorState {
week: string
document: WeeklyDocument | null
text: string
loading: boolean
busy: boolean
saving: boolean
error: string
errorKind: '' | 'load' | 'save' | 'conflict' | 'prefill'
}
const errorText = (e: unknown) => (e instanceof Error ? e.message : '草稿操作失败,请保留文字并重试')
const conflict = (e: unknown) => !!e && typeof e === 'object' && 'status' in e && e.status === 409
export class WeeklyDraftEditorModel {
private snapshot: WeeklyEditorState
private listeners = new Set<() => void>()
private timer: ReturnType<typeof setTimeout> | null = null
private pending: WeeklyWriteRequest | null = null
private prefillPending: WeeklyPrefillRequest | null = null
get uncertainPrefill() {
return !!this.prefillPending
}
private flight: Promise<boolean> | null = null
private generation = 0
private disposed = false
constructor(
week: string,
private transport: WeeklyTransport
) {
this.snapshot = {
week,
document: null,
text: '',
loading: false,
busy: false,
saving: false,
error: '',
errorKind: '',
}
}
get state() {
return this.snapshot
}
get dirty() {
return !!this.state.document && (this.state.text !== this.state.document.markdown || !!this.pending)
}
getSnapshot = () => this.snapshot
subscribe = (listener: () => void) => {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
private update(change: Partial<WeeklyEditorState>) {
this.snapshot = { ...this.snapshot, ...change }
for (const listener of this.listeners) listener()
}
private stopTimer() {
if (this.timer !== null) {
clearTimeout(this.timer)
this.timer = null
}
}
private schedule() {
this.stopTimer()
if (this.disposed || !this.dirty || this.state.error || this.state.loading || this.state.busy || this.state.saving)
return
this.timer = setTimeout(() => {
this.timer = null
void this.saveOne()
}, 800)
}
async initialize() {
const generation = ++this.generation
this.disposed = false
this.update({ loading: true, error: '', errorKind: '' })
try {
const document = await this.transport.read(this.state.week)
if (generation !== this.generation) return
this.pending = null
this.update({ document, text: document.markdown })
} catch (e) {
if (generation === this.generation) this.update({ error: errorText(e), errorKind: 'load' })
} finally {
if (generation === this.generation) this.update({ loading: false })
}
}
setText(text: string) {
if (this.state.busy || this.state.loading || this.prefillPending || !this.state.document) return
this.update({ text })
this.schedule()
}
private async saveOne(): Promise<boolean> {
if (this.flight) return this.flight
if (this.state.errorKind === 'conflict') return false
const document = this.state.document
if (!document || !this.dirty) return true
if (!this.pending) {
try {
this.pending = { base_revision: document.revision, nonce: newOperationID(), markdown: this.state.text }
} catch (e) {
this.update({ error: errorText(e), errorKind: 'save' })
return false
}
}
const request = this.pending,
week = this.state.week
this.flight = Promise.resolve().then(async () => {
this.update({ saving: true, error: '', errorKind: '' })
try {
const fresh = await this.transport.write(week, request)
if (fresh.week !== week || fresh.markdown !== request.markdown || fresh.revision !== request.base_revision + 1)
throw Error('保存版本或正文不匹配,请重新读取核对')
this.pending = null
this.update({ document: fresh })
return true
} catch (e) {
this.update({ error: errorText(e), errorKind: conflict(e) ? 'conflict' : 'save' })
return false
} finally {
this.update({ saving: false })
this.flight = null
this.schedule()
}
})
return this.flight
}
async prefill() {
if (this.state.busy || this.state.loading || !this.state.document) return false
this.update({ busy: true })
this.stopTimer()
try {
if (!this.prefillPending) {
if (!(await this.flush())) return false
this.prefillPending = { base_revision: this.state.document!.revision, nonce: newOperationID() }
}
const request = this.prefillPending,
week = this.state.week
this.update({ error: '', errorKind: '' })
const document = await this.transport.prefill(week, request)
if (document.week !== week || document.revision !== request.base_revision + 1)
throw Error('预填版本无效,尚未确认保存')
this.prefillPending = null
this.pending = null
this.update({ document, text: document.markdown })
return true
} catch (e) {
if (conflict(e)) this.prefillPending = null
this.update({ error: errorText(e), errorKind: conflict(e) ? 'conflict' : 'prefill' })
return false
} finally {
this.update({ busy: false })
}
}
async beforeLeave() {
if (this.state.busy) return false
this.update({ busy: true })
try {
return await this.flush()
} finally {
this.update({ busy: false })
}
}
async switchWeek(week: string) {
if (week === this.state.week) return true
if (this.state.busy) return false
this.update({ busy: true })
try {
if (!(await this.flush())) return false
this.stopTimer()
this.pending = null
this.prefillPending = null
this.update({ week, document: null, text: '' })
await this.initialize()
return !this.state.error
} finally {
this.update({ busy: false })
}
}
async reload() {
if (this.state.busy) return false
this.update({ busy: true })
try {
this.stopTimer()
if (this.flight) await this.flight
this.pending = null
this.prefillPending = null
await this.initialize()
return !this.state.error
} finally {
this.update({ busy: false })
}
}
async flush() {
this.stopTimer()
if (this.prefillPending || this.state.errorKind === 'conflict') return false
do {
if (!(await this.saveOne())) return false
} while (this.dirty)
return true
}
dispose() {
this.disposed = true
this.generation++
this.stopTimer()
this.listeners.clear()
}
}
+176
View File
@@ -0,0 +1,176 @@
.qa-weekly.qa-weekly-editor {
display: flex;
flex-direction: column;
gap: 12px;
min-height: 0;
overflow: hidden;
}
.qa-weekly-editor-header {
display: flex;
align-items: center;
gap: 18px;
flex-wrap: wrap;
}
.qa-weekly-editor-header h3 {
margin: 0;
font-size: 18px;
color: #17324d;
}
.qa-weekly-editor-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.qa-weekly-reload {
min-width: 168px;
}
.qa-weekly-prefill {
min-width: 144px;
}
.qa-weekly-editor-toolbar {
display: flex;
align-items: center;
gap: 16px;
justify-content: space-between;
flex-wrap: wrap;
}
.qa-weekly-mode {
display: flex;
gap: 4px;
}
.qa-weekly-mode button[aria-pressed='true'] {
background: #eaf3ff;
color: #155cb5;
border-color: #a3c7f3;
}
.qa-weekly-editor-status {
font-size: 13px;
color: #64748b;
}
.qa-weekly-editor-status[data-weekly-save-state='saved'] {
color: #2d704d;
}
.qa-weekly-editor-status[data-weekly-save-state='error'] {
color: #b42318;
}
.qa-weekly-editor-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
flex: 1;
min-height: 320px;
overflow: hidden;
border: 1px solid #dce4ed;
border-radius: 10px;
background: #fff;
}
.qa-weekly-editor-layout[data-mode='edit'],
.qa-weekly-editor-layout[data-mode='preview'] {
grid-template-columns: minmax(0, 1fr);
}
.qa-weekly-writing {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.qa-weekly-writing > label {
padding: 10px 16px;
background: #f5f8fc;
border-bottom: 1px solid #e3e9f0;
font-size: 13px;
font-weight: 600;
color: #344b66;
}
.qa-weekly-writing > label small {
font-weight: 400;
color: #728298;
margin-left: 8px;
}
.qa-weekly-writing textarea {
flex: 1;
min-height: 260px;
width: 100%;
min-width: 0;
border: 0;
outline-offset: -3px;
border-radius: 0;
resize: none;
box-sizing: border-box;
padding: 16px;
font:
13px/1.8 ui-monospace,
SFMono-Regular,
Consolas,
monospace;
color: #263c52;
background: #fff;
tab-size: 2;
}
.qa-weekly-writing textarea:disabled {
background: #f6f8fb;
color: #6c7a8a;
}
.qa-weekly-editor-layout .qa-weekly-preview {
margin: 0;
border: 0;
border-left: 1px solid #e3e9f0;
border-radius: 0;
padding: 16px;
overflow: auto;
min-width: 0;
min-height: 0;
max-height: none;
}
.qa-weekly-editor-layout[data-mode='preview'] .qa-weekly-preview {
border-left: 0;
}
.qa-weekly-source {
font-size: 12px;
color: #66778c;
}
.qa-weekly-source p {
margin: 7px 0;
overflow-wrap: anywhere;
}
.qa-weekly-source summary {
cursor: pointer;
}
.qa-weekly-editor > .error-banner {
margin: 0;
}
.qa-weekly-editor > .error-banner button {
margin-left: 8px;
}
.qa-weekly-editor .qa-period-input {
min-width: 210px;
}
@media (max-width: 900px) {
.qa-weekly-editor-header {
gap: 10px;
}
.qa-weekly-editor-actions {
gap: 6px;
}
.qa-weekly-editor-layout[data-mode='both'] {
display: flex;
flex-direction: column;
overflow: auto;
}
.qa-weekly-editor-layout[data-mode='both'] .qa-weekly-writing {
min-height: 360px;
flex: none;
}
.qa-weekly-editor-layout[data-mode='both'] .qa-weekly-preview {
min-height: 260px;
overflow: visible;
border-left: 0;
border-top: 1px solid #e3e9f0;
}
.qa-weekly-editor-header .qa-period-input {
width: 100%;
}
.qa-weekly-editor-actions {
width: 100%;
}
}
+7
View File
@@ -9,6 +9,13 @@ export interface QAWeek {
const day = 86_400_000
const dateOnly = (value: number) => new Date(value).toISOString().slice(0, 10)
export function qaWeekValue(value: Pick<QAWeek, 'year' | 'week'>): string {
return `${value.year}-W${String(value.week).padStart(2, '0')}`
}
export function currentQAWeekValue(now = new Date()): string {
return qaWeekValue(currentQAWeek(now))
}
export function currentQAWeek(now = new Date()): QAWeek {
const beijing = new Date(now.getTime() + 8 * 3_600_000)
beijing.setUTCHours(0, 0, 0, 0)