Compare commits

...

2 Commits

Author SHA1 Message Date
姚章浩 90901a4458 feat(qa-ops): 默认本周快捷查询并全量展示固定字段
build / build (push) Successful in 1m1s
新增本周直接查询按钮,所选范围自动分批读取并校验总数、重复与游标完整性;删除手动加载更多,固定展示完整字段,空列不隐藏,不伪造译文或评估。

验证:全量、固定列及本周入口回归先红后绿;完整make verify通过,前端273通过;真实只读源浏览器默认及快捷查询均639条全部唯一展示,14必需字段按序,右侧字段可达、手机无外溢、JS异常0。无新增迁移或源库写入。
2026-10-18 16:32:16 +08:00
姚章浩 3566f208e0 feat(qa-ops): 增加北京时间自然周年份与周次筛选
build / build (push) Successful in 1m8s
按确认口径展示周次及起止日期,处理跨年、52/53周和本周截至当前。保留自定义时间及查询操作,固定UTC+8边界,不改后端源查询。

验证:目标日期、非法53周、北京时间解析、本周截止及渲染回归均先红后绿;前端266通过,完整make verify成功;洛杉矶时区真实浏览器核对查询UTC边界、切年、自定义和390px布局通过,JS异常0。
2026-10-18 16:10:24 +08:00
10 changed files with 443 additions and 59 deletions
+4
View File
@@ -4,6 +4,10 @@
### Added
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
+26 -3
View File
@@ -50,17 +50,40 @@ const props = {
}
describe('QA operations workbench', () => {
it('shows populated columns in required order and keeps false/downvotes visible', () => {
it('shows all required columns even when empty and keeps false/downvotes visible', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
expect(html).toContain('原始问题')
expect(html.indexOf('AI答案')).toBeLessThan(html.indexOf('是否覆盖'))
expect(html.indexOf('是否正确')).toBeLessThan(html.indexOf('提问时间'))
expect(html).toContain('否(点踩)')
expect(html).toContain('是否正确')
expect(html).not.toContain('<th>部门</th>')
expect(html).not.toContain('<th>产品分类</th>')
expect(html).toContain('<th>部门</th>')
expect([...html.matchAll(/<th>(.*?)<\/th>/g)].slice(0, 14).map((match) => match[1])).toEqual([
'中文问题',
'AI答案',
'是否覆盖',
'是否正确',
'产品分类',
'问题类型',
'根因分析',
'提问时间',
'提问人',
'原始问题',
'语言',
'流程触发人员信息',
'部门',
'区域',
])
expect(html).toContain('<th>产品分类</th>')
expect(html).not.toContain('<script>not executable</script>')
})
it('never shows a load-more control for the all-records table', () => {
const html = renderToStaticMarkup(
<QAOperationsView {...props} page={{ ...page, total: 2, has_more: true, next_cursor: 'next' }} />
)
expect(html).not.toContain('加载更多')
expect(html).not.toContain('空列按整个筛选结果隐藏')
})
it('distinguishes an unavailable source from a successful empty query', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} page={null} error="只读源不可用" />)
expect(html).toContain('role="alert"')
+55 -54
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import type { FormEvent } from 'react'
import { useOptionalAuth } from './auth'
import { fetchQARecord, fetchQARecords, fetchQAStatus, mergeQAPages, qaCellValue, qaColumns } from './qaOps'
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
import './qaOps.css'
import { QARegions } from './QARegions'
@@ -10,6 +10,8 @@ import { QAMonthly } from './QAMonthly'
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
import { qualityLabels } from './qaQuality'
import { usageLabels } from './qaUsage'
import { QAWeekPicker } from './QAWeekPicker'
import { currentQAWeek, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
interface ViewProps {
onQualitySaved?: (record: QARecord) => void
@@ -23,7 +25,7 @@ interface ViewProps {
detailError: string | null
onSelect: (id: string) => void
onCloseDetail: () => void
onLoadMore: () => void
progress?: { loaded: number; total: number }
onRetry: () => void
}
const stateLabels = { disabled: '未配置', unavailable: '连接不可用', blocked: '接入被阻断', connected: '已连接' }
@@ -42,14 +44,18 @@ const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', unc
export function QAOperationsView(props: ViewProps) {
const page = props.page
const columns = qaColumns.filter(({ key }) => page?.columns.includes(key))
const columns = qaColumns
const detail = props.detail
const showDrawer = Boolean(detail || props.detailLoading || props.detailError)
return (
<section className="qa-ops-results" aria-label="问答记录">
<div className="qa-ops-result-bar">
<span>
{props.loading ? '正在读取…' : page ? `共 ${page.total} 条 · 已显示 ${page.items.length} 条` : '尚未读取问答'}
{props.loading
? `正在读取全部问答…${props.progress ? `(${props.progress.loaded} / ${props.progress.total})` : ''}`
: page
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
: '尚未读取问答'}
</span>
<span className="qa-ops-source">
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
@@ -132,14 +138,8 @@ export function QAOperationsView(props: ViewProps) {
) : null}
{page ? (
<footer className="qa-ops-page-bar">
<span>本次读取:{stamp(page.as_of)} · 空列按整个筛选结果隐藏</span>
{page.has_more ? (
<button type="button" onClick={props.onLoadMore} disabled={props.loading}>
{props.loading ? '读取中…' : '加载更多'}
</button>
) : page.items.length > 0 ? (
<span>已显示全部</span>
) : null}
<span>本次读取:{stamp(page.as_of)} · 固定显示完整字段,左右滚动查看;— 表示暂无数据</span>
<span>{page.items.length === page.total ? '已全部展示' : '全量读取尚未完成'}</span>
</footer>
) : null}
{showDrawer ? (
@@ -290,12 +290,10 @@ export function QAOperationsView(props: ViewProps) {
)
}
function localInput(value: Date): string {
return new Date(value.getTime() - value.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
}
function initialDraft() {
const end = new Date()
return { start: localInput(new Date(end.getTime() - 7 * 24 * 3600_000)), end: localInput(end), keyword: '' }
const current = currentQAWeek()
const { year, week, start, end } = qaWeekQueryRange(current.year, current.week)
return { year, week: week as number | null, start, end, keyword: '' }
}
export function QAOperations() {
@@ -314,16 +312,15 @@ export function QAOperations() {
const [detail, setDetail] = useState<QARecord | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState<string | null>(null)
const generation = useRef(0)
const [progress, setProgress] = useState<{ loaded: number; total: number } | undefined>()
const detailRequest = useRef<AbortController | null>(null)
const moreRequest = useRef<AbortController | null>(null)
const returnFocus = useRef<HTMLElement | null>(null)
useEffect(() => {
if (!canRead || query) return
setQuery({
start: new Date(draft.start).toISOString(),
end: new Date(draft.end).toISOString(),
start: qaDateTimeToISO(draft.start),
end: qaDateTimeToISO(draft.end),
keyword: draft.keyword,
cursor: '',
})
@@ -333,18 +330,16 @@ export function QAOperations() {
if (!query || !canRead) return
if (view !== 'records') {
setLoading(false)
moreRequest.current?.abort()
detailRequest.current?.abort()
setDetail(null)
return
}
const controller = new AbortController()
generation.current += 1
moreRequest.current?.abort()
detailRequest.current?.abort()
setLoading(true)
setError(null)
setPage(null)
setProgress(undefined)
setDetail(null)
setDetailError(null)
setDetailLoading(false)
@@ -353,7 +348,9 @@ export function QAOperations() {
.catch(() => {
if (!controller.signal.aborted) setStatus(null)
})
void fetchQARecords(query, controller.signal)
void fetchAllQARecords(query, controller.signal, (loaded, total) => {
if (!controller.signal.aborted) setProgress({ loaded, total })
})
.then((result) => {
if (!controller.signal.aborted) setPage(result)
})
@@ -369,7 +366,6 @@ export function QAOperations() {
useEffect(
() => () => {
detailRequest.current?.abort()
moreRequest.current?.abort()
},
[]
)
@@ -377,10 +373,11 @@ export function QAOperations() {
const submit = (event: FormEvent) => {
event.preventDefault()
try {
const start = new Date(draft.start),
end = new Date(draft.end)
if (!(start < end)) throw new Error('开始时间必须早于结束时间')
setQuery({ start: start.toISOString(), end: end.toISOString(), keyword: draft.keyword, cursor: '' })
const start = qaDateTimeToISO(draft.start),
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: '' })
} catch (reason) {
setError(reason instanceof Error ? reason.message : '时间格式无效')
}
@@ -409,25 +406,6 @@ export function QAOperations() {
setDetailLoading(false)
returnFocus.current?.focus()
}
const loadMore = async () => {
if (!query || !page?.has_more || loading) return
const currentGeneration = generation.current
const controller = new AbortController()
moreRequest.current = controller
setLoading(true)
setError(null)
try {
const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal)
if (!controller.signal.aborted && currentGeneration === generation.current) {
setPage(mergeQAPages(page, result))
}
} catch (reason) {
if (!controller.signal.aborted && currentGeneration === generation.current)
setError(reason instanceof Error ? reason.message : '翻页失败')
} finally {
if (!controller.signal.aborted && currentGeneration === generation.current) setLoading(false)
}
}
return (
<section className="qa-ops" aria-label="问答运营">
<header className="qa-ops-header">
@@ -470,22 +448,45 @@ export function QAOperations() {
) : (
<>
<form className="qa-ops-query" onSubmit={submit}>
{view === 'records' ? (
<QAWeekPicker
year={draft.year}
week={draft.week}
onCurrentWeek={() => {
const current = initialDraft()
setDraft({ ...current, keyword: draft.keyword })
setQuery({
start: qaDateTimeToISO(current.start),
end: qaDateTimeToISO(current.end),
keyword: draft.keyword,
cursor: '',
})
}}
onChange={(year, week) => {
setDraft((old) => {
if (week === null) return { ...old, year, week }
const { start, end } = qaWeekQueryRange(year, week)
return { ...old, year, week, start, end }
})
}}
/>
) : null}
<label>
开始时间
开始时间(北京时间)
<input
type="datetime-local"
required
value={draft.start}
onChange={(event) => setDraft({ ...draft, start: event.target.value })}
onChange={(event) => setDraft({ ...draft, start: event.target.value, week: null })}
/>
</label>
<label>
结束时间(不含)
结束时间(北京时间,不含)
<input
type="datetime-local"
required
value={draft.end}
onChange={(event) => setDraft({ ...draft, end: event.target.value })}
onChange={(event) => setDraft({ ...draft, end: event.target.value, week: null })}
/>
</label>
<label className="qa-ops-keyword">
@@ -543,7 +544,7 @@ export function QAOperations() {
}}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
progress={progress}
onRetry={() => setRevision((value) => value + 1)}
/>
)}
+27
View File
@@ -0,0 +1,27 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { QAWeekPicker } from './QAWeekPicker'
describe('QA week picker', () => {
it('offers a one-click current-week shortcut', () => {
const html = renderToStaticMarkup(<QAWeekPicker year={2026} week={40} onChange={vi.fn()} />)
expect(html).toContain('>本周</button>')
})
it('shows a year and numbered weeks with visible inclusive date ranges', () => {
const html = renderToStaticMarkup(<QAWeekPicker year={2026} week={40} onChange={vi.fn()} />)
expect(html).toContain('aria-label="年份"')
expect(html).toContain('2026年')
expect(html).toContain('aria-label="周次"')
expect(html).toContain('value="40" selected=""')
expect(html).toContain('第40周(09-28 到 10-04)')
expect(html).toContain('第53周(2026-12-28 到 2027-01-03)')
expect(html).toContain('北京时间')
expect(html).toContain('周一至周日')
})
it('preserves custom range mode and does not offer invalid week 53', () => {
const html = renderToStaticMarkup(<QAWeekPicker year={2027} week={null} onChange={vi.fn()} />)
expect(html).toContain('value="" selected=""')
expect(html).toContain('自定义时间')
expect(html).not.toContain('第53周')
})
})
+56
View File
@@ -0,0 +1,56 @@
import { currentQAWeek, qaWeek, qaWeeksInYear } from './qaWeeks'
interface Props {
year: number
week: number | null
onChange: (year: number, week: number | null) => void
onCurrentWeek?: () => void
}
export function QAWeekPicker({ year, week, onChange, onCurrentWeek }: Props) {
const currentYear = currentQAWeek().year
const firstYear = Math.min(currentYear - 5, year)
const lastYear = Math.max(currentYear + 1, year)
return (
<div className="qa-week-picker" role="group" aria-label="按周选择">
<label>
年份
<select
aria-label="年份"
value={year}
onChange={(event) => {
const nextYear = Number(event.target.value)
onChange(nextYear, Math.min(week ?? 1, qaWeeksInYear(nextYear)))
}}
>
{Array.from({ length: lastYear - firstYear + 1 }, (_, i) => firstYear + i)
.reverse()
.map((value) => (
<option key={value} value={value}>
{value}年
</option>
))}
</select>
</label>
<label>
周次
<select
aria-label="周次"
value={week ?? ''}
onChange={(event) => onChange(year, event.target.value === '' ? null : Number(event.target.value))}
>
<option value="">自定义时间</option>
{Array.from({ length: qaWeeksInYear(year) }, (_, i) => i + 1).map((value) => (
<option key={value} value={value}>
{qaWeek(year, value).label}
</option>
))}
</select>
</label>
<button className="qa-week-current" type="button" onClick={onCurrentWeek}>
本周
</button>
<span className="qa-ops-muted">北京时间 · 周一至周日 · 本周截至当前</span>
</div>
)
}
+88
View File
@@ -0,0 +1,88 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchAllQARecords } from './qaOps'
const row = (id: string) => ({
id,
status: 'succeeded',
question: '明确合成问题',
answer: '明确合成答案',
asked_at: '2026-10-14T03:00:00Z',
time_source: 'request_message.created_at',
asker: '合成夹具',
trigger_person: '',
department: '',
region: '',
references: [],
media: [],
source_coverage: { verdict: '', reason_code: '', evaluator_version: '' },
feedback: { asker_value: '', up: 0, down: 0 },
coverage: { state: 'pending', rule_version: 'fixture-rule' },
})
const page = (ids: string[], total: number, cursor = '') => ({
items: ids.map(row),
columns: [],
total,
has_more: Boolean(cursor),
next_cursor: cursor,
as_of: '2026-10-14T04:00:00Z',
})
const query = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T08:00:00Z', keyword: '%_原文', cursor: 'stale-cursor' }
const respond = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 })
afterEach(() => vi.unstubAllGlobals())
describe('all QA records without manual pagination', () => {
it('rejects incomplete, duplicate, drifting and cycling batches', async () => {
const cases = [
[page(['a'], 2)],
[page(['a'], 2, 'n'), page(['a'], 2)],
[page(['a'], 2, 'n'), page(['b'], 3)],
[page(['a'], 3, 'n'), page(['b'], 3, 'n')],
]
for (const pages of cases) {
const fetcher = vi.fn()
pages.forEach((data) => fetcher.mockResolvedValueOnce(respond(data)))
vi.stubGlobal('fetch', fetcher)
await expect(fetchAllQARecords(query)).rejects.toThrow()
}
})
it('surfaces a later source failure instead of returning the first batch', async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce(respond(page(['a'], 2, 'n')))
.mockResolvedValueOnce(new Response(JSON.stringify({ error: '明确合成源不可用' }), { status: 503 }))
vi.stubGlobal('fetch', fetcher)
await expect(fetchAllQARecords(query)).rejects.toThrow('明确合成源不可用')
})
it('accepts a genuinely empty complete scope', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(respond(page([], 0))))
expect((await fetchAllQARecords(query)).items).toEqual([])
})
it('does not start or continue requests after cancellation', async () => {
const controller = new AbortController()
controller.abort()
const fetcher = vi.fn().mockResolvedValue(respond(page([], 0)))
vi.stubGlobal('fetch', fetcher)
await expect(fetchAllQARecords(query, controller.signal)).rejects.toMatchObject({ name: 'AbortError' })
expect(fetcher).not.toHaveBeenCalled()
})
it('reads every transport batch and verifies final count before returning', async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce(respond(page(['a', 'b'], 3, 'next')))
.mockResolvedValueOnce(respond(page(['c'], 3)))
vi.stubGlobal('fetch', fetcher)
const progress = vi.fn()
const result = await fetchAllQARecords(query, undefined, progress)
expect(result.items.map((r) => r.id)).toEqual(['a', 'b', 'c'])
expect(result.has_more).toBe(false)
expect(result.total).toBe(3)
expect(progress.mock.calls).toEqual([
[2, 3],
[3, 3],
])
const urls = fetcher.mock.calls.map((call) => new URL(String(call[0]), 'http://localhost'))
expect(urls.map((url) => url.searchParams.get('cursor'))).toEqual(['', 'next'])
expect(
urls.every((url) => url.searchParams.get('limit') === '100' && url.searchParams.get('keyword') === query.keyword)
).toBe(true)
})
})
+29 -1
View File
@@ -163,7 +163,8 @@
color: var(--ink-mute);
font-size: 12px;
}
.qa-ops-query input {
.qa-ops-query input,
.qa-week-picker select {
min-height: 36px;
min-width: 0;
padding: 7px 10px;
@@ -172,6 +173,24 @@
border-radius: var(--r-sm);
background: var(--bg-panel);
}
.qa-week-picker {
display: flex;
flex-wrap: wrap;
align-items: end;
flex-basis: 100%;
min-width: 0;
gap: 12px;
}
.qa-week-picker label {
min-width: 0;
}
.qa-week-picker select {
max-width: 100%;
font: inherit;
}
.qa-week-picker > span {
padding-bottom: 8px;
}
.qa-ops-keyword {
flex: 1;
min-width: 170px;
@@ -183,8 +202,17 @@
background: var(--c-run);
border: 1px solid var(--c-run);
}
.qa-ops-query .qa-week-current {
color: var(--ink-strong);
background: var(--bg-panel);
border-color: var(--border-strong);
}
.qa-ops-query .qa-week-current:hover {
background: var(--bg-soft);
}
.qa-ops button:focus-visible,
.qa-ops input:focus-visible,
.qa-ops select:focus-visible,
.qa-ops-table-scroll:focus-visible {
outline: 2px solid var(--c-run);
outline-offset: 2px;
+34 -1
View File
@@ -259,6 +259,35 @@ export async function fetchQARecords(query: QAQuery, signal?: AbortSignal): Prom
})
return parseQARecordPage(await getPayload(`/api/v1/qa-ops/records?${parameters}`, signal))
}
export async function fetchAllQARecords(
query: QAQuery,
signal?: AbortSignal,
onProgress?: (loaded: number, total: number) => void
): Promise<QARecordPage> {
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
let page = await fetchQARecords({ ...query, cursor: '', limit: 100 }, signal)
const total = page.total
const ids = new Set(page.items.map((item) => item.id))
const cursors = new Set<string>()
onProgress?.(ids.size, total)
while (page.has_more) {
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
const cursor = page.next_cursor
if (cursors.has(cursor) || ids.size >= total) throw new Error('全量读取游标异常,请重新查询')
cursors.add(cursor)
const next = await fetchQARecords({ ...query, cursor, limit: 100 }, signal)
if (next.total !== total) throw new Error('查询总数已变化,请重新查询,未将部分记录当作全部结果')
for (const item of next.items) {
if (ids.has(item.id)) throw new Error('全量读取出现重复记录,请重新查询')
ids.add(item.id)
}
page = mergeQAPages(page, next)
onProgress?.(ids.size, total)
}
if (ids.size !== total) throw new Error('全量读取数量不完整,请重试,未将部分记录当作全部结果')
return page
}
export async function fetchQARecord(id: string, signal?: AbortSignal): Promise<QARecord> {
return parseQARecord(await getPayload(`/api/v1/qa-ops/records/${encodeURIComponent(id)}`, signal))
}
@@ -283,6 +312,9 @@ export async function fetchQAStatus(signal?: AbortSignal): Promise<QAStatus> {
}
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (column === 'question_chinese')
return item.question_chinese || (/\p{Script=Han}/u.test(item.question) ? item.question : '待翻译')
if (column === 'language') return item.language || '未识别'
const f = item.quality?.effective
if (f) {
if (column === 'coverage')
@@ -309,6 +341,7 @@ export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (item.feedback.up || item.feedback.down) return `其他人:赞 ${item.feedback.up} / 踩 ${item.feedback.down}`
return null
}
if (column === 'asked_at') return new Date(item.asked_at).toLocaleString('zh-CN', { hour12: false })
if (column === 'asked_at')
return new Date(item.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
return item[column] || null
}
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest'
import { currentQAWeek, qaDateTimeToISO, qaWeek, qaWeeksInYear, qaWeekQueryRange } from './qaWeeks'
describe('QA natural-week query ranges', () => {
it('caps the in-progress week at now but leaves completed weeks intact', () => {
const now = new Date('2026-10-18T06:00:00Z')
expect(qaWeekQueryRange(2026, 42, now).end).toBe('2026-10-18T14:00')
expect(qaWeekQueryRange(2026, 40, now).end).toBe('2026-10-05T00:00')
expect(qaWeekQueryRange(2026, 53, now).start).toBe('2026-12-28T00:00')
})
it('resolves the current ISO week at the Beijing midnight boundary', () => {
expect(currentQAWeek(new Date('2026-10-18T15:59:00Z'))).toMatchObject({ year: 2026, week: 42 })
expect(currentQAWeek(new Date('2026-10-18T16:01:00Z'))).toMatchObject({ year: 2026, week: 43 })
expect(currentQAWeek(new Date('2027-01-01T12:00:00Z'))).toMatchObject({ year: 2026, week: 53 })
})
it('converts Beijing form input to UTC without relying on the browser timezone', () => {
expect(qaDateTimeToISO('2026-09-28T00:00')).toBe('2026-09-27T16:00:00.000Z')
expect(qaDateTimeToISO('2026-10-05T00:00')).toBe('2026-10-04T16:00:00.000Z')
for (const input of ['', '2026-02-30T00:00', '2026-10-04', '2026-10-04T24:00', 'invalid']) {
expect(() => qaDateTimeToISO(input)).toThrow()
}
})
it('counts only the valid weeks for each year', () => {
expect(qaWeeksInYear(2026)).toBe(53)
expect(qaWeeksInYear(2027)).toBe(52)
expect(qaWeeksInYear(2020)).toBe(53)
expect(qaWeeksInYear(2021)).toBe(52)
})
it('shows week dates inclusively and queries through the exclusive next Monday', () => {
expect(qaWeek(2026, 40)).toEqual({
year: 2026,
week: 40,
start: '2026-09-28T00:00',
end: '2026-10-05T00:00',
label: '第40周(09-28 到 10-04)',
})
})
it('rejects nonexistent weeks instead of spilling into the next year', () => {
expect(() => qaWeek(2027, 53)).toThrow()
for (const week of [0, -1, 54, 1.5, Number.NaN]) expect(() => qaWeek(2026, week)).toThrow()
for (const year of [0, 2026.5, Number.NaN]) expect(() => qaWeek(year, 1)).toThrow()
})
it('keeps the ISO week-year and shows years on crossing ranges', () => {
expect(qaWeek(2026, 1)).toMatchObject({
start: '2025-12-29T00:00',
end: '2026-01-05T00:00',
label: '第1周(2025-12-29 到 2026-01-04)',
})
expect(qaWeek(2026, 53)).toMatchObject({
start: '2026-12-28T00:00',
end: '2027-01-04T00:00',
label: '第53周(2026-12-28 到 2027-01-03)',
})
expect(qaWeek(2024, 9)).toMatchObject({ start: '2024-02-26T00:00', end: '2024-03-04T00:00' })
})
})
+67
View File
@@ -0,0 +1,67 @@
export interface QAWeek {
year: number
week: number
start: string
end: string
label: string
}
const day = 86_400_000
const dateOnly = (value: number) => new Date(value).toISOString().slice(0, 10)
export function currentQAWeek(now = new Date()): QAWeek {
const beijing = new Date(now.getTime() + 8 * 3_600_000)
beijing.setUTCHours(0, 0, 0, 0)
beijing.setUTCDate(beijing.getUTCDate() + 3 - ((beijing.getUTCDay() + 6) % 7))
const year = beijing.getUTCFullYear()
const week = Math.floor((beijing.getTime() - firstMonday(year)) / (7 * day)) + 1
return qaWeek(year, week)
}
export function qaDateTimeToISO(value: string): string {
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) throw new Error('时间格式无效')
const parsed = new Date(`${value}:00+08:00`)
if (
!Number.isFinite(parsed.getTime()) ||
new Date(parsed.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) !== value
) {
throw new Error('时间格式无效')
}
return parsed.toISOString()
}
export function qaWeekQueryRange(year: number, week: number, now = new Date()): QAWeek {
const range = qaWeek(year, week)
if (
Date.parse(qaDateTimeToISO(range.start)) < now.getTime() &&
now.getTime() < Date.parse(qaDateTimeToISO(range.end))
) {
return { ...range, end: new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) }
}
return range
}
const firstMonday = (year: number) => {
const jan4 = new Date(Date.UTC(year, 0, 4))
return jan4.getTime() - ((jan4.getUTCDay() + 6) % 7) * day
}
export function qaWeeksInYear(year: number): number {
if (!Number.isInteger(year) || year < 1900 || year > 9998) throw new Error('年份无效')
return (firstMonday(year + 1) - firstMonday(year)) / (7 * day)
}
export function qaWeek(year: number, week: number): QAWeek {
if (!Number.isInteger(week) || week < 1 || week > qaWeeksInYear(year)) throw new Error('周次无效')
const start = firstMonday(year) + (week - 1) * 7 * day
const first = dateOnly(start)
const last = dateOnly(start + 6 * day)
const crossYear = first.slice(0, 4) !== String(year) || last.slice(0, 4) !== String(year)
return {
year,
week,
start: `${first}T00:00`,
end: `${dateOnly(start + 7 * day)}T00:00`,
label: `第${week}周(${crossYear ? first : first.slice(5)} 到 ${crossYear ? last : last.slice(5)})`,
}
}