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 export function fieldChoices(field: EditableField, choices: string[], coverage: string): string[] { return field === 'is_correct' && coverage !== '否' ? choices.filter((value) => value !== '待确认') : choices } export function parseFieldOptions(raw: unknown): FieldOptions { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw Error('主表选项读取失败') const v = raw as Record 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 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 { 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 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 }