Compare commits

..
Author SHA1 Message Date
long a89f3d38fd fix(iam): preserve origin on cross-platform form handoffs 2026-10-30 12:00:31 +08:00
long a32e167f8b fix(iam): expose scoped account metadata and avoid duplicate notices 2026-10-30 11:50:55 +08:00
long 27cab30c48 fix(iam): keep revocation core active when new flows are disabled 2026-10-29 20:38:08 +08:00
long 3f3b4b400a fix(iam): preserve deployed consultation clock and release provenance 2026-10-29 19:13:19 +08:00
long 70d0bca0db docs(iam): record live-base release gate and fixed source config 2026-10-29 18:52:14 +08:00
long 7cbc679287 fix(iam): align cross-app proofs and add native IAM target launch 2026-10-29 18:49:32 +08:00
long dcb0db8275 feat(iam): add guarded identity management and ERP launch source 2026-10-29 17:34:55 +08:00
long bcd42a5c39 feat(followup-audio): separate uploader-only recording delete permission 2026-10-12 16:36:47 +08:00
long 11306e6314 fix(followup-audio): handle unsigned zero menu sort during permission migration 2026-10-12 15:18:37 +08:00
long 8f7544c1ad feat(followup-audio): add independent assignable recording permission 2026-10-12 15:14:19 +08:00
long 86041042b9 feat(followup-audio): normalize extraction to record field contracts 2026-10-12 14:34:31 +08:00
long 9e3aa9fc61 feat(followup-audio): confirm role corrections and reextract cached transcripts 2026-10-12 12:24:34 +08:00
long 2dfec801e7 fix(followup-audio): keep entry visible during capability failures 2026-10-12 11:02:13 +08:00
long 14e1722291 feat(followup-audio): soft delete unadopted recordings and expose extraction doubts 2026-10-12 10:39:12 +08:00
long 70ddc1a70a feat(followup-audio): inline review with serialized draft autosave 2026-10-12 09:30:43 +08:00
long fc91908cf9 fix(followup-audio): preserve roles chosen before first audio file 2026-10-10 15:03:06 +08:00
long b4acad8510 feat(followup-audio): review full dialogue and bind roles before extraction 2026-10-10 14:25:03 +08:00
long f015b26ae1 Merge human-reviewed followup business workflow 2026-10-10 11:42:08 +08:00
long 91aa1cb595 feat: enable explicitly authorized human-reviewed clinical adoption 2026-10-10 11:42:08 +08:00
gr 0349ec0fbd 和不满 2026-10-10 10:58:56 +08:00
gr 68b412495d 更新 2026-10-10 10:55:32 +08:00
long 55979da912 Merge explicit GPT text channel integration 2026-10-10 10:28:29 +08:00
long 228d93ac3b feat: bind explicitly authorized HTTP text extraction channel 2026-10-10 10:28:28 +08:00
long 4704b32807 Merge followup extraction provider preference fix 2026-10-09 18:09:13 +08:00
long 73be0ecedf fix: honor configured followup extraction model preference 2026-10-09 18:09:12 +08:00
long 6ccef86dd0 Merge followup audio flow review fixes 2026-10-09 17:46:25 +08:00
long e762a367da fix: preserve confirmed followup snapshots and expand flow checks 2026-10-09 17:46:25 +08:00
long 91f56931fd Merge followup audio draft request fix 2026-10-09 17:13:28 +08:00
long 9185c6db04 fix: preserve typed followup audio review request payloads 2026-10-09 17:13:21 +08:00
long 5884e000ff Merge follow-up audio preview with isolated Dify ASR 2026-10-09 16:12:11 +08:00
long 4d0af7f3f4 feat: add scoped read-only audio preview and isolated Dify transport 2026-10-09 16:10:59 +08:00
long 27772bec61 Merge commit '5706e9a6a51227ebf798df46fabcbabf83f91ab2' into codex/followup-audio 2026-10-09 14:51:44 +08:00
Your Name 5706e9a6a5 更新 2026-10-09 14:13:57 +08:00
Your Name 51d8fd409e 更新 2026-10-09 09:36:17 +08:00
Your Name 88b94c2fc6 修复古籍索引安装脚本兼容旧版 Git 2026-10-09 09:16:03 +08:00
Your Name 637c2f1ff2 更新 2026-10-09 09:09:54 +08:00
Your Name 19ea2dadeb 更新 2026-10-08 18:03:11 +08:00
Your Name 4dac39c4c2 更新 2026-10-08 16:32:50 +08:00
long a20d3565af feat: preserve stereo channels and require reviewed speaker roles 2026-10-08 16:15:41 +08:00
Your Name 67c374d899 更新 2026-10-08 15:49:53 +08:00
long 13948f5982 feat: add durable ASR-to-patient extraction and guarded review 2026-10-08 15:08:42 +08:00
Your Name 1c9b093e08 更新 2026-10-08 14:12:44 +08:00
long 8bb4bd07ae ops: add isolated ASR deployment and safe GPU test handoff 2026-10-08 12:42:01 +08:00
long fea33285e8 feat: configure audio providers and add local sample acceptance 2026-10-07 18:15:32 +08:00
gr 5543f45850 更新 2026-09-30 14:35:46 +08:00
long 70be2fc70f feat: add reviewed follow-up audio patient enrichment 2026-09-29 15:44:30 +08:00
gr 3cdc812f2b ;rgb:0000/0000/0000
更新
2026-09-28 14:53:47 +08:00
gr 71304f356d i
Merge branch 'master' into 9-28
2026-09-28 14:20:46 +08:00
gr 694c83dc7d 更新 2026-09-28 14:18:12 +08:00
957 changed files with 3828342 additions and 588 deletions
+3
View File
@@ -0,0 +1,3 @@
# The bundled GB18030 source files must retain their original bytes.
server/knowledge/tcm-ancient-books/*.txt -text -diff
server/knowledge/tcm-ancient-books/*.baiduyun.downloading* -text -diff
+3
View File
@@ -28,6 +28,9 @@ app/.test-tmp-stream/
/.codex
/.agents
/server/.spool
# Generated ancient-books search indexes; the source corpus is tracked.
/server/knowledge/tcm-ancient-books-index.json
/server/knowledge/tcm-ancient-books-index/
/server/.claude
/.spool
TUICallKit-Vue3/.env
+206
View File
@@ -0,0 +1,206 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate, compileStyleAsync } = require('@vue/compiler-sfc')
const sourceFlag = process.argv.indexOf('--source')
const filename = sourceFlag >= 0 ? path.resolve(process.argv[sourceFlag + 1]) : path.join(__dirname, '../src/views/tcm/diagnosis/components/DailyMatrix.vue')
const source = fs.readFileSync(filename, 'utf8')
const { descriptor, errors } = parse(source, { filename })
assert.deepEqual(errors, [], 'actual SFC parses')
const script = compileScript(descriptor, { id: 'daily-record-test' })
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'daily-record-test', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [], 'actual template compiles')
const calls = []
const pending = { window: null, notes: null, bloodEdit: null }
const api = new Proxy({}, { get(_target, name) {
return (...args) => {
calls.push({ name, args: JSON.parse(JSON.stringify(args)) })
if (name === 'diagnosisTrackingWindow') return pending.window ? pending.window(...args) : Promise.resolve({})
if (name === 'diagnosisTrackingNotes') return pending.notes ? pending.notes(...args) : Promise.resolve([])
if (name === 'bloodRecordEdit' && pending.bloodEdit) return pending.bloodEdit(...args)
return Promise.resolve(true)
}
} })
const thresholdSource = fs.readFileSync(path.join(__dirname, '../src/utils/blood-thresholds.ts'), 'utf8')
const thresholdExports = {}
vm.runInNewContext(ts.transpileModule(thresholdSource, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText, { exports: thresholdExports })
const moduleObject = { exports: {} }
const lifecycle = { mounted: [], unmounted: [] }
const runtime = { ...vue, onMounted: fn => lifecycle.mounted.push(fn), onUnmounted: fn => lifecycle.unmounted.push(fn) }
vm.runInNewContext(ts.transpileModule(script.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText, {
exports: moduleObject.exports, module: moduleObject, console, Date, Map, window: { addEventListener() {}, removeEventListener() {} },
require(name) {
if (name === 'vue') return runtime
if (name === '@/api/tcm') return api
if (name === '@/utils/perm') return { hasPermission: () => true }
if (name === '@/utils/blood-thresholds') return thresholdExports
if (name === '@/utils/feedback') return { default: { msgWarning: message => calls.push({ name: 'warning', message }) } }
if (name === 'vue-echarts' || name.endsWith('.vue')) return { default: {} }
throw new Error(`Unexpected import: ${name}`)
}
}, { filename })
const props = vue.reactive({ diagnosisId: 7, patientId: 70, age: 50, readOnly: false, patientName: '合成测试' })
let exposed
const scope = vue.effectScope()
const state = scope.run(() => moduleObject.exports.default.setup(props, { expose(value) { exposed = value } }))
const date = '2026-09-20'
const blood = [
{ id: 103, diagnosis_id: 7, record_date: date, record_time: '19:30', fasting_blood_sugar: 7.1, record_time_estimated: 1, record_time_period: 'evening', record_time_text: '昨晚', followup_audio_task_id: 80, remark: '晚间原始行' },
{ id: 102, diagnosis_id: 7, record_date: date, record_time: '08:30', fasting_blood_sugar: 7.1, source: 1, remark: '早间原始行' },
{ id: 101, diagnosis_id: 7, record_date: date, record_time: '07:00', postprandial_blood_sugar: 8.4, remark: '独立原始行' }
]
const diet = [ { id: 201, record_date: date, breakfast_foods: '鸡蛋', breakfast_images: ['fixture-a.png'] }, { id: 202, record_date: date, lunch_foods: '豆腐', lunch_images: ['fixture-b.png'] } ]
const exercise = [ { id: 301, record_date: date, exercise_type: '散步', duration: 20, intensity: 1, images: ['fixture-c.png'] }, { id: 302, record_date: date, exercise_type: '散步', duration: 20, intensity: 1 } ]
function fixtures() {
state.bloodRecords.value = structuredClone(blood)
state.dietRecords.value = structuredClone(diet)
state.exerciseRecords.value = structuredClone(exercise)
}
function rowCount(map) { const rows = map.value.get(date); return Array.isArray(rows) ? rows.length : rows ? 1 : 0 }
function observe() {
fixtures()
state.handleCellClick('fasting', date)
return { bloodRows: rowCount(state.bloodByDate), dietRows: rowCount(state.dietByDate), exerciseRows: rowCount(state.exerciseByDate), dayDetailOpen: !!state.dayDetailVisible?.value, implicitBloodEditId: state.bloodForm.value.id || null, fastingCell: state.getCell('fasting', date).value }
}
async function main() {
for (const style of descriptor.styles) {
const result = await compileStyleAsync({ source: style.content, filename, id: 'daily-record-test', scoped: style.scoped, preprocessLang: style.lang })
assert.deepEqual(result.errors, [], 'actual styles compile')
}
const canonicalFlag = process.argv.indexOf('--canonical-fixture')
if (canonicalFlag >= 0) {
const fixture = JSON.parse(fs.readFileSync(process.argv[canonicalFlag + 1], 'utf8'))
assert.equal(fixture.synthetic, true)
assert.equal(fixture.source, 'real-disposable-mysql-apply')
for (const alias of ['breakfast', 'lunch', 'dinner']) assert.equal(fixture.diet_columns.includes(alias), false)
const actual = { ...fixture.diet_model, record_date: new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date(Number(fixture.diet_model.record_date) * 1000)) }
state.dietRecords.value = [actual]
state.openDietRecord(actual, actual.record_date)
for (const meal of ['breakfast', 'lunch', 'dinner']) {
assert.equal(state.dietForm.value[`${meal}_foods`], actual[`${meal}_foods`], 'real adopted meal opens in existing edit input')
assert.deepEqual(JSON.parse(JSON.stringify(state.dietForm.value[`${meal}_images`])), actual[`${meal}_images`])
assert.equal(state.getCell(meal, actual.record_date).value, '✓')
}
state.dietForm.value.note = 'only synthetic note changed'
await state.submitDiet()
const payload = calls.findLast(x => x.name === 'dietRecordEdit').args[0]
for (const meal of ['breakfast', 'lunch', 'dinner']) {
assert.equal(payload[`${meal}_foods`], actual[`${meal}_foods`], 'submit preserves untouched canonical meals')
assert.deepEqual(payload[`${meal}_images`], actual[`${meal}_images`], 'submit preserves images')
assert.equal(meal in payload, false, 'no extraction alias leaks to existing edit API')
}
console.log('DAILY_RECORDS_CANONICAL_MYSQL PASS actual_model=1 edit_inputs=1 canonical_payload=1 preserved_images=1')
}
if (process.argv.includes('--observe')) { console.log(JSON.stringify(observe())); scope.stop(); return }
assert.deepEqual(observe(), { bloodRows: 3, dietRows: 2, exerciseRows: 2, dayDetailOpen: true, implicitBloodEditId: null, fastingCell: '7.1 / 7.1' })
assert.equal(state.dayBloodRecords.value.length, 3, 'all same-day blood rows present')
assert.equal(state.dayDietRecords.value.length, 2, 'all diet rows present')
assert.equal(state.dayExerciseRecords.value.length, 2, 'identical exercise rows remain separate')
assert.equal(state.recordTimeLabel(blood[0]), '19:30')
assert.equal(state.recordTimePeriodLabel(blood[0]), '晚上')
assert.equal(state.recordTimeLabel(diet[0]), '未记录具体时间', 'do not invent times for old diet rows')
assert.match(descriptor.template.content, /v-for="record in dayBloodRecords"/)
assert.match(descriptor.template.content, /v-for="record in dayDietRecords"/)
assert.match(descriptor.template.content, /v-for="record in dayExerciseRecords"/)
assert.match(descriptor.template.content, /估计时间/)
assert.match(descriptor.template.content, /record\.record_time_text/)
state.openBloodRecord(blood[0], date)
assert.equal(state.bloodForm.value.id, 103)
assert.equal(state.bloodForm.value.postprandial_blood_sugar, 0, 'no field from another row merged into edit')
state.bloodForm.value.remark = '只改备注'
await state.submitBlood()
let sent = calls.findLast(x => x.name === 'bloodRecordEdit').args[0]
assert.equal(sent.id, 103)
assert.equal(sent.record_time_estimated, 1, 'unmodified time retains estimate')
assert.equal(sent.record_time_text, '昨晚')
assert.equal(sent.followup_audio_task_id, 80, 'keep provenance')
state.openBloodRecord(blood[0], date)
state.bloodForm.value.record_time = '20:05'
await state.submitBlood()
sent = calls.findLast(x => x.name === 'bloodRecordEdit').args[0]
assert.equal(sent.record_time_estimated, 0, 'manual time correction clears estimate')
assert.equal(sent.record_time_period, '')
assert.equal(sent.record_time_text, '')
assert.equal(sent.followup_audio_task_id, 80)
state.openBloodRecord({ ...blood[0], record_time: '19:30:25' }, date)
state.bloodForm.value.record_time = '19:30'
await state.submitBlood()
sent = calls.findLast(x => x.name === 'bloodRecordEdit').args[0]
assert.equal(sent.record_time_estimated, 0, 'seconds correction must not retain estimated time')
assert.equal(state.recordTimeLabel({ record_time: '19:30:25' }), '19:30:25', 'precise original seconds remain visible')
state.openBloodRecord(undefined, date)
await state.submitBlood()
sent = calls.findLast(x => x.name === 'bloodRecordAdd').args[0]
assert.equal(sent.id, '')
assert.equal('record_time_estimated' in sent, false, 'legacy manual add does not require migration columns')
state.openDietRecord(diet[1], date)
assert.equal(state.dietForm.value.id, 202)
state.dietForm.value.lunch_images.push('fixture-new.png')
assert.equal(diet[1].lunch_images.length, 1, 'edit image arrays cloned')
await state.submitDiet()
assert.equal(calls.findLast(x => x.name === 'dietRecordEdit').args[0].id, 202)
state.openExerciseRecord(exercise[1], date)
await state.submitExercise()
assert.equal(calls.findLast(x => x.name === 'exerciseRecordEdit').args[0].id, 302)
fixtures()
props.readOnly = true
state.dayDetailVisible.value = false
state.handleCellClick('exercise', date)
assert.equal(state.dayDetailVisible.value, true, 'readonly viewers can inspect actual rows')
state.bloodDialogVisible.value = false
state.openBloodRecord(blood[0], date)
assert.equal(state.bloodDialogVisible.value, false, 'readonly cannot edit')
props.readOnly = false
const windows = []
pending.window = params => new Promise(resolve => windows.push({ params, resolve }))
const oldFetch = state.fetchTracking()
props.diagnosisId = 8
await vue.nextTick()
assert.equal(state.dayDetailVisible.value, false, 'patient switch closes prior details')
assert.equal(state.bloodRecords.value.length, 0, 'patient switch immediately clears old rows')
assert.equal(windows.length, 2)
assert.equal(windows[0].params.id, 7)
assert.equal(windows[1].params.id, 8)
windows[1].resolve({ blood_records: [{ id: 888, record_date: date }] })
await new Promise(resolve => setImmediate(resolve))
windows[0].resolve({ blood_records: blood })
await oldFetch
assert.equal(state.bloodRecords.value[0].id, 888, 'late old-patient fetch cannot overwrite new data')
assert.deepEqual(calls.filter(x => x.name === 'diagnosisTrackingNotes').slice(-2).map(x => x.args[0].diagnosis_id), [8, 7], 'both sequential requests use their own bound identity')
let releaseEdit
pending.bloodEdit = () => new Promise(resolve => { releaseEdit = resolve })
pending.window = null
state.openBloodRecord({ ...blood[0], diagnosis_id: 8 }, date)
const oldSubmit = state.submitBlood()
props.diagnosisId = 9
await vue.nextTick()
state.bloodDialogVisible.value = true
releaseEdit(true)
await oldSubmit
assert.equal(state.bloodDialogVisible.value, true, 'late old-patient submit cannot close new dialog')
// Single-flight guard prevents duplicate submissions of the same manual form.
state.bloodSubmitting.value = true
const callCount = calls.length
await state.submitBlood()
assert.equal(calls.length, callCount)
state.bloodSubmitting.value = false
const unmountedWindows = []
pending.window = () => new Promise(resolve => unmountedWindows.push(resolve))
const unmountedFetch = state.fetchTracking()
for (const unmount of lifecycle.unmounted) unmount()
unmountedWindows[0]({ blood_records: blood })
await unmountedFetch
assert.notEqual(state.bloodRecords.value[0]?.id, 103, 'unmounted request cannot repopulate component')
scope.stop()
assert.equal(typeof exposed.refresh, 'function')
console.log('DailyMatrix actual SFC setup/template/style: 3 blood + 2 diet + 2 exercise rows, exact edit IDs, time metadata, readonly detail, stale isolation: PASS')
}
main().catch(error => { scope.stop(); console.error(error); process.exitCode = 1 })
+157
View File
@@ -0,0 +1,157 @@
import request from '@/utils/request'
export type FollowupKind = 'diagnosis' | 'blood' | 'diet' | 'exercise' | 'tracking_note'
export type FollowupValue = string | number | boolean | null | Array<string | number>
export type FollowupValues = Record<string, FollowupValue>
export interface FollowupField {
key: string
label: string
type: 'text' | 'number' | 'select' | 'multiselect' | 'date'
options?: Array<{ label: string; value: string | number }>
readonly?: boolean
}
export type FollowupFields = Record<FollowupKind, FollowupField[]>
export type FollowupAudioChannel = 0 | 1
export type FollowupChannelRoles = 'unconfirmed' | 'left_service' | 'right_service'
export interface FollowupTranscriptSegment {
id: string
start_ms: number
end_ms: number
text: string
channel?: FollowupAudioChannel
}
export interface FollowupCapabilities {
enabled: boolean
audio_verified: boolean
preview_only?: boolean
preview_ready?: boolean
manual_review_enabled?: boolean
manual_review_ready?: boolean
can_review?: boolean
test_scope_allowed?: boolean
can_upload: boolean
can_apply: boolean
can_daily: boolean
models: Array<{ value: string; label: string }>
limits: { max_bytes: number; max_seconds: number; chunk_bytes: number }
fields: FollowupFields
}
export interface FollowupReviewItem {
id: string
kind: FollowupKind
values: FollowupValues
record_date: string | null
record_time: string | null
time_period: string | null
time_estimated: boolean
time_text: string
date_text: string
evidence: Array<{ text: string; start_ms?: number; end_ms?: number; segment_id?: string; position_type?: 'segment'; channel?: FollowupAudioChannel }>
needs_review: boolean
selected: boolean
target_id: number | null
current_values: FollowupValues
expected_hash: string
conflict: boolean
possible_duplicate: boolean
candidates?: Array<{
id: number
values: FollowupValues
record_time: string | null
time_estimated: boolean
time_period: string | null
delete_time?: number | null
}>
}
export interface FollowupTaskSummary {
id: number
diagnosis_id: number
file_name: string
recorded_at: string
status: string
stage: string
error_code: string
error_message: string
version: number
created_at: number | string
expires_at: number | string
can_delete?: boolean
delete_block_reason?: string
can_retry: boolean
audio_available: boolean
preview_only?: boolean
transcript_available?: boolean
pipeline_progress?: { transcribed: number; total: number }
}
export interface FollowupTaskDetail extends FollowupTaskSummary {
extraction_revision?: number
extraction_channel_roles?: FollowupChannelRoles
can_reextract?: boolean
reextract_block_reason?: string
role_check?: {
conflict: boolean
suggested_roles: FollowupChannelRoles
message: string
evidence: Array<{ channel: FollowupAudioChannel; start_ms: number; end_ms: number; text: string }>
}
summary: string
transcript: string
transcript_segments?: FollowupTranscriptSegment[]
channel_roles?: FollowupChannelRoles
uncertainties: unknown[]
items: FollowupReviewItem[]
fields?: FollowupFields
applied_items: unknown[]
review_refreshed?: boolean
}
interface Envelope<T> { code: number; msg?: string; data: T }
export class FollowupAudioError extends Error {
constructor(message: string, public readonly code = '') { super(message); this.name = 'FollowupAudioError' }
}
const options = { isTransformResponse: false, ignoreCancelToken: true, isOpenRetry: false, retryCount: 0 }
const base = '/tcm.followupAudio/'
function unwrap<T>(response: Envelope<T>): T {
if (response.code !== 1) {
const data = response.data
const code = data && typeof data === 'object' && 'code' in data ? String(data.code) : ''
throw new FollowupAudioError(response.msg || '回访录音请求失败,请刷新任务状态后确认', code)
}
return response.data
}
async function get<T>(name: string, params: Record<string, number>, signal?: AbortSignal): Promise<T> {
return unwrap(await request.get<Envelope<T>>({ url: base + name, params, signal }, options))
}
async function post<T>(name: string, data: unknown, signal?: AbortSignal): Promise<T> {
return unwrap(await request.post<Envelope<T>>({ url: base + name, data, signal, timeout: 120000 }, options))
}
export const followupAudioCapabilities = (diagnosisId: number, signal?: AbortSignal) => get<FollowupCapabilities>('capabilities', { diagnosis_id: diagnosisId }, signal)
export const followupAudioLists = (diagnosisId: number, signal?: AbortSignal) => get<{ items: FollowupTaskSummary[] }>('lists', { diagnosis_id: diagnosisId }, signal)
export const followupAudioDetail = (id: number, signal?: AbortSignal) => get<FollowupTaskDetail>('detail', { id }, signal)
export const followupAudioUploadSession = (data: { diagnosis_id: number; file_name: string; total_bytes: number }, signal?: AbortSignal) => post<{ upload_id: string; chunk_bytes: number }>('uploadSession', data, signal)
export async function followupAudioUploadChunk(uploadId: string, index: number, file: Blob, signal?: AbortSignal) {
const data = new FormData()
data.append('upload_id', uploadId)
data.append('index', String(index))
data.append('file', file, `chunk-${index}`)
return unwrap(await request.post<Envelope<{ index: number; received: boolean }>>({
url: base + 'uploadChunk', data, signal, timeout: 120000,
headers: { 'Content-Type': 'multipart/form-data' }
}, options))
}
export const followupAudioUploadComplete = (uploadId: string, signal?: AbortSignal) => post<{ upload_id: string; duration_seconds: number; sha256: string }>('uploadComplete', { upload_id: uploadId }, signal)
export const followupAudioCreate = (data: { diagnosis_id: number; upload_id: string; recorded_at: string; model_key: string; channel_roles?: FollowupChannelRoles }, signal?: AbortSignal) => post<{ task_id: number; status: string; reused?: boolean; reuse_message?: string }>('create', data, signal)
export const followupAudioSaveDraft = (data: { id: number; version: number; items: FollowupReviewItem[]; channel_roles?: FollowupChannelRoles }, signal?: AbortSignal) => post<FollowupTaskDetail>('saveDraft', data, signal)
export const followupAudioApply = (data: { id: number; version: number; items: FollowupReviewItem[] }, signal?: AbortSignal) => post<{ id: number; status: 'applied'; applied_items: unknown[] }>('apply', data, signal)
export const followupAudioReextract = (data: { id: number; version: number; channel_roles: Exclude<FollowupChannelRoles, 'unconfirmed'> }, signal?: AbortSignal) => post<FollowupTaskDetail>('reextract', data, signal)
export const followupAudioDelete = (data: { id: number; version: number }, signal?: AbortSignal) => post<{ id: number; status: 'deleted'; version: number }>('delete', data, signal)
export const followupAudioRetry = (id: number, signal?: AbortSignal) => post<{ id: number; status: string }>('retry', { id }, signal)
/** The existing request interceptor puts the token in a header, never in the audio URL. */
export async function followupAudioBlob(id: number, signal?: AbortSignal): Promise<Blob> {
const blob = await request.get<Blob>({ url: base + 'audio', params: { id }, responseType: 'blob', signal, timeout: 120000 }, options)
if (blob.type.includes('json')) {
const response: Envelope<unknown> = JSON.parse(await blob.text())
unwrap(response)
throw new FollowupAudioError('录音响应不是音频文件')
}
return blob
}
+37
View File
@@ -0,0 +1,37 @@
import request from '@/utils/request'
export type IdentityOperation = {
kind: 'bind' | 'create_and_bind' | 'unbind' | 'rebind' | 'reconcile'
user_id: number
employee_id?: string
expected_version?: number
new_employee?: { username: string; display_name: string; email?: string }
reason: string
}
const prefix = '/iam/v2'
const opts = { isOpenRetry: false, ignoreCancelToken: true }
export const iamGet = (path: string, params?: Record<string, unknown>): Promise<any> =>
request.get({ url: prefix + path, params, withCredentials: true }, opts)
export const iamPost = (
path: string,
params: Record<string, unknown> = {},
key = crypto.randomUUID()
): Promise<any> =>
request.post(
{ url: prefix + path, params, headers: { 'Idempotency-Key': key }, withCredentials: true },
opts
)
export const identityError = (e: any): string =>
({
REAUTH_REQUIRED: '请先验证当前账号密码,或通过企业微信重新登录。',
ACCOUNT_MISMATCH: '两端账号不一致,请确认身份后重新发起。',
NOT_LINKED: '当前账号还未关联 IAM。',
NOT_AUTHORIZED: 'IAM 尚未授予目标应用访问权限。',
BINDING_CONFLICT: '关联已变更,请刷新后重新确认。',
PROTECTED_ACCOUNT_REVIEW_REQUIRED: '敏感账号需要双侧近期管理员核验,请由统一身份平台审核。',
SERVICE_UNAVAILABLE: '统一身份服务暂时不可用,状态未确认,请稍后重试。',
FEATURE_DISABLED: 'IAM 关联管理尚未启用。',
FORBIDDEN: '没有当前操作权限或目标超出数据范围。',
TRANSACTION_EXPIRED: '验证已过期或已经使用,请重新发起。'
})[e?.error?.code as string] ||
e?.error?.code ||
'操作未完成,请刷新状态后重试。'
+33
View File
@@ -0,0 +1,33 @@
<template>
<el-button v-if="enabled" text :loading="busy" @click="launch">进入甄美 ERP ↗</el-button>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
const enabled = ref(false),
busy = ref(false)
onMounted(async () => {
try {
const status = await iamGet('/status')
enabled.value = !!status.enabled && status.launch_enabled === true
} catch {
enabled.value = false
}
})
async function launch() {
const tab = window.open('about:blank', '_blank')
if (tab) tab.opener = null
busy.value = true
try {
const r = await iamPost('/launch/start')
if (tab) tab.location.href = r.url
else ElMessage.warning('请允许新标签页后再试。')
} catch (e) {
tab?.close()
ElMessage.warning(identityError(e))
} finally {
busy.value = false
}
}
</script>
+137
View File
@@ -0,0 +1,137 @@
<template>
<el-card v-if="status?.enabled || error" class="mt-4" shadow="never">
<template #header
><strong>统一身份 IAM</strong
><el-button class="float-right" text @click="refresh">刷新状态</el-button></template
>
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-4" />
<p>
关联状态:<el-tag :type="linked ? 'success' : 'info'">{{
linked ? '已关联' : status.binding?.state === 'revoked' ? '关联已撤销' : '未关联'
}}</el-tag>
</p>
<p v-if="status.employee" class="my-3">
IAM 员工:{{ status.employee.displayName }}({{ status.employee.username }})
</p>
<p class="my-3 text-gray-500">
关联只确认同一人的身份,不会复制业务角色或自动授予其他平台权限。
</p>
<el-alert
v-if="!linked && status.protected_account"
class="mb-4"
type="warning"
:closable="false"
title="此账号属于敏感账号,请由本地管理员在 IAM 关联管理发起单人中央复核,不使用个人自助绑定。"
/>
<div class="flex flex-wrap gap-3">
<el-button @click="reauthVisible = true">验证当前身份</el-button>
<el-button @click="wecomRelogin">企业微信重新登录</el-button>
<el-button
v-if="!linked && !status.protected_account && status.management_enabled"
type="primary"
:loading="busy"
@click="navigate('/self-link/start')"
>关联已有 IAM 账号</el-button
>
<el-button
v-if="linked && status.management_enabled && status.employee?.passwordSetupPending"
type="primary"
:loading="busy"
@click="navigate('/password-setup')"
>设置 IAM 登录密码</el-button
>
<el-button v-if="linked && status.launch_enabled" :loading="busy" @click="launch">进入甄美 ERP ↗</el-button>
</div>
<el-dialog
v-model="reauthVisible"
title="验证当前 ZYT 身份"
width="420px"
:close-on-click-modal="false"
>
<el-form @submit.prevent="reauth"
><el-form-item label="当前密码"
><el-input
v-model="password"
type="password"
show-password
autocomplete="current-password"
@keyup.enter="reauth" /></el-form-item
></el-form>
<p class="text-gray-500">
仅验证当前账号,验证有效期 5 分钟。密码不会被保存或传给 IAM。
</p>
<template #footer
><el-button @click="cancelReauth">取消</el-button
><el-button type="primary" :loading="busy" @click="reauth"
>验证</el-button
></template
>
</el-dialog>
</el-card>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
import useUserStore from '@/stores/modules/user'
const status = ref<any>({ enabled: false }),
error = ref(''),
busy = ref(false),
reauthVisible = ref(false),
password = ref('')
const linked = computed(() => status.value?.binding?.state === 'verified')
async function refresh() {
try {
status.value = await iamGet('/status')
error.value = ''
} catch (e) {
error.value = identityError(e)
}
}
function cancelReauth() {
reauthVisible.value = false
password.value = ''
}
async function reauth() {
busy.value = true
try {
await iamPost('/reauth', { password: password.value })
reauthVisible.value = false
await refresh()
} catch (e) {
error.value = identityError(e)
} finally {
password.value = ''
busy.value = false
}
}
async function navigate(path: string) {
busy.value = true
try {
const r = await iamPost(path)
window.location.assign(r.url)
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
async function launch() {
const tab = window.open('about:blank', '_blank')
if (tab) tab.opener = null
busy.value = true
try {
const r = await iamPost('/launch/start')
if (tab) tab.location.href = r.url
else error.value = '请允许浏览器打开新标签页后再试。'
} catch (e) {
tab?.close()
error.value = identityError(e)
} finally {
busy.value = false
}
}
async function wecomRelogin() {
await useUserStore().logout()
}
onMounted(refresh)
</script>
@@ -22,6 +22,7 @@
</div>
</div>
<div class="flex">
<iam-launch />
<div class="navbar-item" v-if="!isMobile">
<el-tooltip
class="box-item"
@@ -52,6 +53,7 @@
</template>
<script setup lang="ts">
import IamLaunch from '@/components/iam-v2/launch.vue'
import { useFullscreen } from '@vueuse/core'
import useAppStore from '@/stores/modules/app'
+1 -1
View File
@@ -81,7 +81,7 @@ const defaultPath = PageEnum.INDEX
const changePasswordPath = '/change-password'
const bindWorkWechatPath = '/bind-work-wechat'
// 免登录白名单
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403, '/iam/launch']
router.beforeEach(async (to, from, next) => {
document.title = to.meta.title ?? config.title
const userStore = useUserStore()
+5
View File
@@ -23,6 +23,11 @@ export const LAYOUT = () => Promise.resolve(Layout)
export const INDEX_ROUTE_NAME = Symbol()
export const constantRoutes: Array<RouteRecordRaw> = [
{
path: '/iam/launch',
component: () => import('@/views/account/iam-launch.vue'),
meta: { title: '统一身份进入甄养堂', hideTab: true }
},
{
path: '/:pathMatch(.*)*',
component: () => import('@/views/error/404.vue')
+15 -1
View File
@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { getUserInfo, iamLogin, login, logout, workWechatLogin } from '@/api/user'
import { iamPost } from '@/api/iam-v2'
import { TOKEN_KEY } from '@/enums/cacheEnums'
import { PageEnum } from '@/enums/pageEnum'
import router, { filterAsyncRoutes } from '@/router'
@@ -14,6 +15,7 @@ export interface UserState {
routes: RouteRecordRaw[]
perms: string[]
isPaw: number // 0=需要修改密码,1=正常
serverTimeOffsetMs: number
}
const useUserStore = defineStore({
@@ -27,7 +29,8 @@ const useUserStore = defineStore({
// 权限
perms: [],
// 是否需要修改密码
isPaw: 1
isPaw: 1,
serverTimeOffsetMs: 0
}),
getters: {},
actions: {
@@ -36,6 +39,7 @@ const useUserStore = defineStore({
this.userInfo = {}
this.perms = []
this.isPaw = 1
this.serverTimeOffsetMs = 0
},
login(playload: any) {
const { account, password } = playload
@@ -83,6 +87,14 @@ const useUserStore = defineStore({
})
})
},
async iamLaunchLogin(ticket: string) {
const data = await iamPost('/launch/exchange', { ticket })
this.resetState()
this.token = data.token
this.isPaw = data.is_paw ?? 1
cache.set(TOKEN_KEY, data.token)
return data
},
async iamLogin(ticket: string) {
const data = await iamLogin(ticket)
this.token = data.token
@@ -95,6 +107,8 @@ const useUserStore = defineStore({
getUserInfo()
.then((data) => {
this.userInfo = data.user
const serverTime = Number(data.user?.web_consultation_policy?.server_time)
this.serverTimeOffsetMs = serverTime > 0 ? serverTime * 1000 - Date.now() : 0
this.perms = data.permissions
this.routes = filterAsyncRoutes(data.menu)
// 更新 isPaw 状态
+93
View File
@@ -0,0 +1,93 @@
<template>
<main class="min-h-screen flex items-center justify-center bg-page p-6">
<el-card class="w-full max-w-xl" shadow="never">
<h1 class="text-xl font-semibold mb-4">统一身份进入甄养堂</h1>
<p v-if="busy" class="text-gray-500">正在核验同一身份,请稍候…</p>
<el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
<p class="text-gray-500 my-4">
已有 ZYT 账号将进行一致性检查。系统不会自动替换当前已登录的人。
</p>
<div v-if="error" class="flex flex-wrap gap-3">
<el-button v-if="restartUrl" type="primary" @click="back"
>返回 IAM 重新发起</el-button
>
<el-button v-if="restartUrl" :loading="busy" @click="switchAccount"
>退出当前 ZYT 身份并返回 IAM</el-button
>
<router-link to="/login"><el-button>使用原登录方式</el-button></router-link>
</div>
</el-card>
</main>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
import useUserStore from '@/stores/modules/user'
import { clearAuthInfo } from '@/utils/auth'
import feedback from '@/utils/feedback'
const route = useRoute(),
router = useRouter(),
store = useUserStore()
const busy = ref(true),
error = ref(''),
restartUrl = ref('')
let handled = false
const text = (v: unknown) => (typeof v === 'string' ? v : '')
function back() {
if (restartUrl.value) window.location.assign(restartUrl.value)
}
async function switchAccount() {
await feedback.confirm(
'确认退出当前浏览器的 ZYT 身份?其他平台和其他浏览器不受影响。请回 IAM 重新发起。'
)
busy.value = true
try {
await iamPost('/launch/reset')
clearAuthInfo()
back()
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
onMounted(async () => {
if (handled) return
handled = true
const ticket = text(route.query.ticket),
source = text(route.query.source),
intent = text(route.query.intent),
issue = text(route.query.iam_error)
// Strip one-use material before any network/async work; never retain it in history.
window.history.replaceState(window.history.state, '', window.location.pathname)
try {
const config = await iamGet('/launch/config', { source })
restartUrl.value = config.restart_url || ''
if (!config.enabled) throw { error: { code: 'FEATURE_DISABLED' } }
if (issue) throw { error: { code: issue } }
if (ticket) {
const result = await store.iamLaunchLogin(ticket)
await router.replace(
result.is_paw === 0
? '/change-password'
: result.need_bind_work_wechat
? '/bind-work-wechat'
: '/'
)
} else {
if (
!['iam-admin', 'iam-portal'].includes(source) ||
!/^[A-Za-z0-9_-]{32,256}$/.test(intent)
)
throw { error: { code: 'INVALID_REQUEST' } }
const result = await iamPost('/launch/prepare', { source, intent })
window.location.assign(result.url)
}
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
})
</script>
@@ -0,0 +1,636 @@
<template>
<div class="identity-management">
<el-card shadow="never">
<div class="flex items-center justify-between mb-4">
<div>
<h2 class="text-xl font-semibold">IAM 关联管理</h2>
<p class="text-gray-500 mt-2">
保留历史本地账号、业务角色与数据;只管理统一身份关联。
</p>
</div>
<el-button @click="reauthVisible = true">验证管理员身份</el-button>
</div>
<el-alert
v-if="error"
:title="error"
type="warning"
show-icon
:closable="false"
class="mb-4"
/>
<el-alert
v-if="!enabled"
title="IAM v2 尚未启用,原有业务与登录方式保持不变。"
type="info"
:closable="false"
/>
<el-form v-if="enabled" inline class="mt-4" @submit.prevent="reload">
<el-form-item label="本地账号"
><el-input
v-model="query.q"
placeholder="账号或姓名"
clearable
@keyup.enter="reload"
/></el-form-item>
<el-form-item label="关联状态"
><el-select v-model="query.state" clearable class="!w-40"
><el-option
v-for="(label, key) in states"
:key="key"
:label="label"
:value="key" /></el-select
></el-form-item>
<el-form-item
><el-button type="primary" @click="reload">查询</el-button
><el-button :disabled="!can('batch')" @click="batchVisible = true"
>批量预检</el-button
></el-form-item
>
</el-form>
<el-table v-if="enabled" v-loading="loading" :data="rows" row-key="id">
<el-table-column prop="id" label="ID" width="70" />
<el-table-column prop="account" label="本地账号" min-width="140" />
<el-table-column prop="name" label="姓名" min-width="120" />
<el-table-column label="本地状态" width="110"
><template #default="{ row }"
><el-tag :type="row.disable ? 'danger' : 'success'">{{
row.disable ? '停用' : row.root ? '敏感账号' : '正常'
}}</el-tag></template
></el-table-column
>
<el-table-column label="IAM 员工" min-width="180"
><template #default="{ row }"
>{{ row.iam.employee?.displayName || '—' }}
<div class="text-xs text-gray-500">
{{ row.iam.employee?.username }}
</div></template
></el-table-column
>
<el-table-column label="关联状态" width="130"
><template #default="{ row }"
><el-tag :type="row.iam.state === 'verified' ? 'success' : 'info'">{{
states[row.iam.state] || row.iam.state
}}</el-tag>
<div class="text-xs">
版本 {{ row.iam.binding?.version ?? '—' }}
</div></template
></el-table-column
>
<el-table-column label="操作" min-width="210"
><template #default="{ row }">
<el-button
link
type="primary"
:disabled="
(!!row.root && !reviewAllowed) ||
row.iam.state === 'verified' ||
!can(row.iam.state === 'revoked' ? 'rebind' : 'bind')
"
@click="open(row, 'bind')"
>关联</el-button
>
<el-button
link
type="primary"
:disabled="
(!!row.root && !reviewAllowed) ||
row.iam.state === 'verified' ||
!can('create') ||
(row.iam.state === 'revoked' && !can('rebind'))
"
@click="open(row, 'create_and_bind')"
>创建并关联</el-button
>
<el-dropdown @command="(kind: string) => more(row, kind)"
><el-button link>更多</el-button
><template #dropdown
><el-dropdown-menu>
<el-dropdown-item
command="rebind"
:disabled="(!!row.root && !reviewAllowed) || !can('rebind')"
>换绑</el-dropdown-item
>
<el-dropdown-item
command="unbind"
:disabled="(!!row.root && !reviewAllowed) || !can('unbind')"
>解绑</el-dropdown-item
>
<el-dropdown-item command="audit">审计记录</el-dropdown-item>
</el-dropdown-menu></template
></el-dropdown
>
</template></el-table-column
>
</el-table>
<el-pagination
v-if="enabled"
class="mt-4 justify-end"
layout="total, prev, pager, next"
:total="total"
v-model:current-page="query.page"
:page-size="20"
@current-change="load"
/>
</el-card>
<el-drawer
v-model="drawer"
:title="titles[operation.kind]"
size="min(680px, 94vw)"
:close-on-click-modal="false"
>
<el-steps :active="step" finish-status="success" align-center
><el-step title="核对本地账号" /><el-step title="核对 IAM 身份" /><el-step
title="确认变更"
/></el-steps>
<section class="mt-8">
<template v-if="step === 0"
><h3 class="text-lg mb-4">{{ selected?.name }} · {{ selected?.account }}</h3>
<p>本地 ID:{{ selected?.id }}</p>
<p class="my-3">
当前关联:{{ selected?.iam.employee?.displayName || '未关联' }}(版本
{{ selected?.iam.binding?.version ?? '无' }})
</p>
<el-alert
title="本次操作不改变本地密码、角色、部门或历史数据;人员同名不代表同一身份。"
type="info"
:closable="false"
/></template>
<template v-if="step === 1">
<el-form v-if="operation.kind === 'create_and_bind'" label-position="top"
><el-form-item label="IAM 登录名"
><el-input
v-model="newEmployee.username"
maxlength="64" /></el-form-item
><el-form-item label="姓名"
><el-input
v-model="newEmployee.display_name"
maxlength="100" /></el-form-item
><el-form-item label="邮箱(可选)"
><el-input v-model="newEmployee.email" /></el-form-item
><el-alert
title="使用正常员工开户流程,默认应用授权遵循 IAM 当前策略。不会生成共享初始密码;本人首次使用需设置 IAM 密码。"
type="info"
:closable="false"
/></el-form>
<template v-else-if="operation.kind !== 'unbind'"
><el-input
v-model="identityQuery"
placeholder="搜索 IAM 登录名或姓名"
@keyup.enter="searchIdentities"
><template #append
><el-button @click="searchIdentities">搜索</el-button></template
></el-input
><el-table
class="mt-4"
:data="identities"
highlight-current-row
@current-change="choose"
><el-table-column label="选择" width="70"
><template #default="{ row }"
><el-radio
:model-value="operation.employee_id"
:value="row.id"
@change="choose(row)"
><span /></el-radio></template></el-table-column
><el-table-column prop="username" label="IAM 登录名" /><el-table-column
prop="displayName"
label="姓名" /><el-table-column
prop="status"
label="状态" /></el-table
></template>
<el-alert
v-else
title="解绑后跨平台快捷登录停止,相关来源/业务会话撤销,历史数据和本地账号保留。自动开户不会恢复已撤销关联。"
type="warning"
:closable="false"
/>
</template>
<template v-if="step === 2"
><el-descriptions :column="1" border
><el-descriptions-item label="本地账号"
>{{ selected?.account }} #{{ selected?.id }}</el-descriptions-item
><el-descriptions-item label="变更类型">{{
titles[operation.kind]
}}</el-descriptions-item
><el-descriptions-item label="原 IAM 员工">{{
selected?.iam.employee?.username || '无'
}}</el-descriptions-item
><el-descriptions-item label="目标 IAM 员工">{{
operation.kind === 'unbind'
? '解除关联'
: operation.kind === 'create_and_bind'
? newEmployee.username
: chosenIdentity?.username
}}</el-descriptions-item
><el-descriptions-item label="预期版本">{{
operation.expected_version ?? '首次关联'
}}</el-descriptions-item></el-descriptions
><el-input
class="mt-4"
v-model="operation.reason"
:disabled="!!submittedPayload"
type="textarea"
:rows="3"
maxlength="500"
placeholder="必填:核对方式和变更原因,将写入审计记录"
/><el-checkbox class="mt-4" v-model="confirmed"
>我已核对本地账号与 IAM 员工为同一人,理解会话撤销影响</el-checkbox
></template
>
<el-alert
v-if="drawerError"
class="mt-4"
:title="drawerError"
type="error"
:closable="false"
/>
<el-alert
v-if="result"
class="mt-4"
:title="`操作 ${result.id}:${result.status}${result.error?.code ? ' · ' + identityError(result) : ''}`"
:type="result.status === 'succeeded' ? 'success' : 'warning'"
:closable="false"
/>
<div v-if="result?.reviewUrl" class="mt-4">
<a
:href="result.reviewUrl"
target="_blank"
rel="noopener noreferrer"
class="text-primary"
>中央复核 ↗</a
>
<p class="text-gray-500 mt-2">
由中央管理员完成近期验证并批准后,重试原操作;原目标、版本和原因保持不变。
</p>
</div>
<el-button
v-if="result && result.status !== 'succeeded'"
class="mt-4"
@click="refreshOperation"
>查询同一操作状态</el-button
>
</section>
<template #footer
><el-button @click="drawer = false">关闭</el-button
><el-button v-if="step > 0" :disabled="!!submittedPayload" @click="step--"
>上一步</el-button
><el-button
v-if="step < 2"
type="primary"
:disabled="step === 1 && !validIdentity"
@click="step++"
>下一步</el-button
><el-button
v-else
type="primary"
:loading="busy"
:disabled="
!confirmed || !operation.reason.trim() || result?.status === 'succeeded'
"
@click="submit"
>{{
result?.reviewUrl
? '完成中央复核后重试原操作'
: '确认' + titles[operation.kind]
}}</el-button
></template
>
</el-drawer>
<el-dialog v-model="reauthVisible" title="近期管理员身份验证" width="420px"
><el-input
v-model="password"
type="password"
show-password
placeholder="当前 ZYT 账号密码"
autocomplete="current-password"
@keyup.enter="reauth"
/>
<p class="mt-4 text-gray-500">
有效期 5 分钟。敏感目标还需中央管理员审核,此处不会越过审核。
</p>
<template #footer
><el-button type="primary" :loading="busy" @click="reauth"
>验证</el-button
></template
></el-dialog
>
<el-drawer v-model="auditVisible" title="关联审计" size="min(760px, 94vw)"
><el-table :data="audits"
><el-table-column prop="occurredAt" label="时间" min-width="170" /><el-table-column
prop="action"
label="操作" /><el-table-column label="操作人"
><template #default="{ row }">{{
typeof row.actor === 'string' ? row.actor : JSON.stringify(row.actor)
}}</template></el-table-column
><el-table-column prop="reason" label="原因" /></el-table
></el-drawer>
<el-dialog
v-model="batchVisible"
title="批量预检与确认"
width="min(920px, 94vw)"
:close-on-click-modal="false"
>
<el-alert
title="先预检,不会创建账号或修改绑定。仅选择 ready 项后显式确认;敏感账号与冲突项跳过。每批最多 100 条。"
type="info"
:closable="false"
/>
<el-input
v-model="batchText"
class="mt-4"
type="textarea"
:rows="7"
placeholder='[{"kind":"bind","user_id":42,"employee_id":"员工ID","reason":"核对后历史关联"}]'
/>
<el-button class="mt-4" :loading="busy" @click="preflight">只读预检</el-button>
<el-table
v-if="preview"
class="mt-4"
:data="preview.items"
@selection-change="(items: any[]) => (selectedIndexes = items.map((x) => x.index))"
><el-table-column
type="selection"
:selectable="(row: any) => row.status === 'ready'" /><el-table-column
prop="externalAccountId"
label="本地 ID" /><el-table-column prop="status" label="状态" /><el-table-column
prop="message"
label="结果"
/></el-table>
<el-checkbox v-if="preview" v-model="batchConfirmed" class="mt-4"
>确认仅执行已选择项目({{ selectedIndexes.length }} 条)</el-checkbox
>
<section v-if="job" class="mt-4">
<h3>任务 {{ job.id }} · {{ job.status }}</h3>
<el-table :data="job.items"
><el-table-column prop="externalAccountId" label="本地账号" /><el-table-column
prop="status"
label="状态"
/><el-table-column label="结果"
><template #default="{ row }">{{
row.error?.message || row.error?.code || '—'
}}</template></el-table-column
></el-table
><el-button @click="refreshJob">刷新任务</el-button
><el-button
:disabled="
!job.items?.some((x: any) => ['failed', 'pending'].includes(x.status))
"
@click="retryJob"
>只重试失败/待处理项</el-button
>
</section>
<template #footer
><el-button @click="batchVisible = false">关闭</el-button
><el-button
type="primary"
:loading="busy"
:disabled="
!preview?.previewId || !batchConfirmed || !selectedIndexes.length || !!job
"
@click="submitBatch"
>确认执行</el-button
></template
>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { iamGet, iamPost, identityError, type IdentityOperation } from '@/api/iam-v2'
const states: Record<string, string> = {
verified: '已关联',
unlinked: '未关联',
revoked: '已撤销',
pending: '待确认',
conflict: '冲突',
unknown: '待核验'
}
const titles: Record<string, string> = {
bind: '关联',
create_and_bind: '创建并关联',
rebind: '换绑',
unbind: '解绑',
reconcile: '对账'
}
const enabled = ref(false),
reviewAllowed = ref(false),
managementEnabled = ref(false),
caps = ref<string[]>([]),
rows = ref<any[]>([]),
total = ref(0),
loading = ref(false),
busy = ref(false),
error = ref('')
const query = reactive({ q: '', state: '', page: 1, pageSize: 20 })
const drawer = ref(false),
step = ref(0),
selected = ref<any>(null),
identities = ref<any[]>([]),
identityQuery = ref(''),
chosenIdentity = ref<any>(null),
confirmed = ref(false),
drawerError = ref(''),
result = ref<any>(null)
const submittedPayload = ref<Record<string, unknown> | null>(null)
const operation = reactive<IdentityOperation>({ kind: 'bind', user_id: 0, reason: '' }),
newEmployee = reactive({ username: '', display_name: '', email: '' })
let operationKey = crypto.randomUUID(),
batchKey = crypto.randomUUID()
const reauthVisible = ref(false),
password = ref(''),
auditVisible = ref(false),
audits = ref<any[]>([])
const batchVisible = ref(false),
batchText = ref(''),
preview = ref<any>(null),
selectedIndexes = ref<number[]>([]),
batchConfirmed = ref(false),
job = ref<any>(null)
const can = (c: string) => caps.value.includes(c) && (c === 'read' || managementEnabled.value)
const validIdentity = computed(
() =>
operation.kind === 'unbind' ||
(operation.kind === 'create_and_bind'
? !!newEmployee.username.trim() && !!newEmployee.display_name.trim()
: !!operation.employee_id)
)
async function load() {
loading.value = true
try {
const r = await iamGet('/accounts', query)
rows.value = r.items
total.value = r.total
error.value = ''
} catch (e) {
error.value = identityError(e)
} finally {
loading.value = false
}
}
function reload() {
query.page = 1
void load()
}
function open(row: any, kind: IdentityOperation['kind']) {
if (kind === 'bind' && row.iam.state === 'revoked') kind = 'rebind'
selected.value = row
Object.assign(operation, {
kind,
user_id: row.id,
employee_id: undefined,
expected_version: row.iam.binding?.version,
reason: ''
})
Object.assign(newEmployee, { username: '', display_name: row.name, email: '' })
drawer.value = true
step.value = 0
confirmed.value = false
drawerError.value = ''
result.value = null
submittedPayload.value = null
chosenIdentity.value = null
identities.value = []
operationKey = crypto.randomUUID()
}
async function more(row: any, kind: string) {
if (kind === 'audit') {
try {
audits.value = (await iamGet(`/accounts/${row.id}/audit`)).items
auditVisible.value = true
} catch (e) {
error.value = identityError(e)
}
} else open(row, kind as IdentityOperation['kind'])
}
async function searchIdentities() {
try {
identities.value = (
await iamGet('/identities', { q: identityQuery.value, page: 1, pageSize: 20 })
).items
} catch (e) {
drawerError.value = identityError(e)
}
}
function choose(row: any) {
if (row?.status === 'active') {
chosenIdentity.value = row
operation.employee_id = row.id
}
}
async function submit() {
busy.value = true
try {
if (!submittedPayload.value) {
submittedPayload.value = JSON.parse(
JSON.stringify({
...operation,
...(operation.kind === 'create_and_bind'
? { new_employee: { ...newEmployee } }
: {})
})
)
}
result.value = await iamPost('/operations', submittedPayload.value!, operationKey)
drawerError.value = ''
await load()
} catch (e) {
drawerError.value = identityError(e)
} finally {
busy.value = false
}
}
async function refreshOperation() {
try {
result.value = await iamGet(`/operations/${result.value.id}`)
await load()
} catch (e) {
drawerError.value = identityError(e)
}
}
async function reauth() {
busy.value = true
try {
await iamPost('/reauth', { password: password.value })
reauthVisible.value = false
ElMessage.success('身份已验证,有效期 5 分钟')
await load()
} catch (e) {
error.value = identityError(e)
} finally {
password.value = ''
busy.value = false
}
}
async function preflight() {
busy.value = true
preview.value = null
job.value = null
batchConfirmed.value = false
selectedIndexes.value = []
try {
const items = JSON.parse(batchText.value)
if (!Array.isArray(items) || items.length < 1 || items.length > 100) throw Error('input')
preview.value = await iamPost('/batch/preflight', { items })
batchKey = crypto.randomUUID()
} catch (e) {
error.value = e instanceof SyntaxError ? '批量输入必须是 JSON 数组。' : identityError(e)
} finally {
busy.value = false
}
}
async function submitBatch() {
busy.value = true
try {
job.value = await iamPost(
'/batch',
{ preview_id: preview.value.previewId, indexes: selectedIndexes.value },
batchKey
)
await load()
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
async function refreshJob() {
try {
job.value = await iamGet(`/jobs/${job.value.id}`)
await load()
} catch (e) {
error.value = identityError(e)
}
}
async function retryJob() {
busy.value = true
try {
job.value = await iamPost(`/jobs/${job.value.id}/retry`)
await load()
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
onMounted(async () => {
try {
const s = await iamGet('/status')
enabled.value = s.enabled
caps.value = s.management_capabilities || []
reviewAllowed.value = s.protected_review_operator === true
managementEnabled.value = s.management_enabled === true
if (enabled.value && can('read')) await load()
} catch (e) {
error.value = identityError(e)
}
})
</script>
<style scoped>
.identity-management p {
line-height: 1.7;
}
.identity-management :deep(.el-steps) {
margin-bottom: 24px;
}
</style>
@@ -68,7 +68,11 @@
'is-high': getCell(row.key, date).isHigh,
'is-patient-self': getCell(row.key, date).isPatientSelf && getCell(row.key, date).hasRecord
}"
:role="isCellClickable(row.key, date) ? 'button' : undefined"
:tabindex="isCellClickable(row.key, date) ? 0 : undefined"
@click="handleCellClick(row.key, date)"
@keydown.enter="handleCellClick(row.key, date)"
@keydown.space.prevent="handleCellClick(row.key, date)"
>
<template v-if="row.key === 'tracking' && getTrackingContent(date)">
<el-tooltip placement="top" effect="light" :show-after="150">
@@ -90,6 +94,9 @@
</template>
<template v-else-if="getCell(row.key, date).value">
<span>{{ getCell(row.key, date).value }}</span>
<span v-if="getDayRecordCount(row.key, date) > 1" class="daily-matrix__record-count">
{{ getDayRecordCount(row.key, date) }}条
</span>
<span v-if="getCell(row.key, date).isHigh" class="daily-matrix__cell-up">↑</span>
<el-tooltip
v-if="getCell(row.key, date).isPatientSelf"
@@ -100,7 +107,10 @@
<span class="daily-matrix__cell-patient">自录</span>
</el-tooltip>
</template>
<template v-else>—</template>
<template v-else>
<span v-if="getDayRecordCount(row.key, date) > 0" class="daily-matrix__record-count">查看{{ getDayRecordCount(row.key, date) }}条</span>
<span v-else>—</span>
</template>
</div>
</template>
</el-table-column>
@@ -109,6 +119,7 @@
<div class="daily-matrix__chart">
<div class="daily-matrix__section-title">血糖趋势</div>
<p class="daily-matrix__hint">按日展示最新有效血糖值;点击表格查看当天全部原始记录。</p>
<v-charts
v-if="bloodTrendHasData"
class="daily-matrix__chart-canvas"
@@ -128,6 +139,84 @@
/>
</div>
<el-drawer v-model="dayDetailVisible" :title="`${detailDate} 日常记录明细`" size="min(640px, 100vw)">
<p class="daily-matrix__hint">每张卡片是一条独立记录;相同数值也不会合并。请在对应记录上点击编辑。</p>
<section class="daily-matrix__detail-section">
<div class="daily-matrix__detail-heading">
<h3>血糖血压 · {{ dayBloodRecords.length }}条</h3>
<el-button v-if="canEditDailyRecord" link type="primary" @click="openBloodRecord(undefined, detailDate)">新增一条</el-button>
</div>
<el-empty v-if="!dayBloodRecords.length" description="当天暂无血糖血压记录" :image-size="48" />
<article v-for="record in dayBloodRecords" :key="record.id" class="daily-matrix__detail-record">
<header class="daily-matrix__detail-heading">
<strong>{{ recordTimeLabel(record) }} <small>#{{ record.id }}</small></strong>
<el-button v-if="canEditDailyRecord" link type="primary" @click="openBloodRecord(record, detailDate)">编辑此条</el-button>
</header>
<div class="daily-matrix__detail-tags">
<el-tag v-if="Number(record.record_time_estimated) === 1" type="warning" size="small">估计时间</el-tag>
<el-tag v-if="record.record_time_period" type="info" size="small">时段:{{ recordTimePeriodLabel(record) }}</el-tag>
<el-tag v-if="record.followup_audio_task_id" size="small">随访录音</el-tag>
<span v-if="Number(record.source) === 1" class="daily-matrix__cell-patient">患者自录</span>
</div>
<p v-if="record.record_time_text" class="daily-matrix__time-evidence">时间原文:{{ record.record_time_text }}</p>
<dl class="daily-matrix__detail-fields">
<template v-for="field in bloodDetailFields(record)" :key="field.label">
<dt>{{ field.label }}</dt><dd>{{ field.value }}</dd>
</template>
</dl>
</article>
</section>
<section class="daily-matrix__detail-section">
<div class="daily-matrix__detail-heading">
<h3>饮食 · {{ dayDietRecords.length }}条</h3>
<el-button v-if="canEditDailyRecord" link type="primary" @click="openDietRecord(undefined, detailDate)">新增一条</el-button>
</div>
<el-empty v-if="!dayDietRecords.length" description="当天暂无饮食记录" :image-size="48" />
<article v-for="record in dayDietRecords" :key="record.id" class="daily-matrix__detail-record">
<header class="daily-matrix__detail-heading">
<strong>{{ recordTimeLabel(record) }} <small>#{{ record.id }}</small></strong>
<el-button v-if="canEditDailyRecord" link type="primary" @click="openDietRecord(record, detailDate)">编辑此条</el-button>
</header>
<dl class="daily-matrix__detail-fields">
<template v-for="meal in mealFields" :key="meal.key">
<dt>{{ meal.label }}</dt>
<dd>
{{ record[`${meal.key}_foods`] || record[meal.key] || '—' }}
<div v-if="record[`${meal.key}_images`]?.length" class="daily-matrix__detail-images">
<el-image v-for="(url, index) in record[`${meal.key}_images`]" :key="`${url}-${index}`"
:src="url" :preview-src-list="record[`${meal.key}_images`]" :initial-index="index" preview-teleported fit="cover" />
</div>
</dd>
</template>
<dt>备注</dt><dd>{{ record.note || '—' }}</dd>
</dl>
</article>
</section>
<section class="daily-matrix__detail-section">
<div class="daily-matrix__detail-heading">
<h3>运动 · {{ dayExerciseRecords.length }}条</h3>
<el-button v-if="canEditDailyRecord" link type="primary" @click="openExerciseRecord(undefined, detailDate)">新增一条</el-button>
</div>
<el-empty v-if="!dayExerciseRecords.length" description="当天暂无运动记录" :image-size="48" />
<article v-for="record in dayExerciseRecords" :key="record.id" class="daily-matrix__detail-record">
<header class="daily-matrix__detail-heading">
<strong>{{ recordTimeLabel(record) }} <small>#{{ record.id }}</small></strong>
<el-button v-if="canEditDailyRecord" link type="primary" @click="openExerciseRecord(record, detailDate)">编辑此条</el-button>
</header>
<dl class="daily-matrix__detail-fields">
<dt>运动</dt><dd>{{ record.exercise_type || '—' }}</dd>
<dt>时长</dt><dd>{{ record.duration == null ? '未记录' : `${record.duration} 分钟` }}</dd>
<dt>强度</dt><dd>{{ intensityLabel(record.intensity) }}</dd>
<dt>备注</dt><dd>{{ record.note || '—' }}</dd>
</dl>
<div v-if="record.images?.length" class="daily-matrix__detail-images">
<el-image v-for="(url, index) in record.images" :key="`${url}-${index}`" :src="url"
:preview-src-list="record.images" :initial-index="index" preview-teleported fit="cover" />
</div>
</article>
</section>
</el-drawer>
<el-dialog v-model="bloodDialogVisible" :title="bloodDialogTitle" width="600px" :close-on-click-modal="false">
<el-form :model="bloodForm" label-width="120px">
<el-form-item label="记录日期" required>
@@ -148,6 +237,12 @@
class="w-full"
/>
</el-form-item>
<el-form-item v-if="Number(bloodForm.record_time_estimated) === 1" label="时间说明">
<div class="daily-matrix__time-evidence">
估计时间 · {{ recordTimePeriodLabel(bloodForm) }};原文:{{ bloodForm.record_time_text || '未提供' }}。
手动修改记录时间后会清除估计标记;只改数值则保留来源。
</div>
</el-form-item>
<el-form-item label="空腹血糖">
<el-input-number v-model="bloodForm.fasting_blood_sugar" :precision="2" :step="0.1" :min="0" :max="50" />
<span class="ml-2">mmol/L</span>
@@ -248,11 +343,13 @@
<el-option label="其他" value="其他" />
</el-select>
</el-form-item>
<el-form-item label="运动时长(分钟)" required>
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" />
<el-form-item label="运动时长(分钟)" :required="!exerciseForm.id">
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" placeholder="未记录" />
<span v-if="exerciseForm.id" class="ml-2 text-info">留空表示未记录</span>
</el-form-item>
<el-form-item label="运动强度" required>
<el-select v-model="exerciseForm.intensity" placeholder="请选择运动强度" class="w-full">
<el-form-item label="运动强度">
<el-select v-model="exerciseIntensity" placeholder="未记录" class="w-full">
<el-option label="未记录" value="" />
<el-option label="低强度" :value="1" />
<el-option label="中强度" :value="2" />
<el-option label="高强度" :value="3" />
@@ -353,6 +450,10 @@ interface BloodRecord {
patient_id?: number
record_date?: string
record_time?: string
record_time_estimated?: number | string
record_time_period?: string
record_time_text?: string
followup_audio_task_id?: number | null
record_date_ts?: number
fasting_blood_sugar?: any
postprandial_blood_sugar?: any
@@ -364,12 +465,11 @@ interface BloodRecord {
remark?: string
/** 来源:0-医生录入 1-患者自录(小程序日常记录页) */
source?: number
/** 合并后该日是否含有「患者自录」记录 */
has_patient_self?: boolean
[key: string]: any
}
interface DietRecord {
record_time?: string
id?: number | string
diagnosis_id?: number
patient_id?: number
@@ -388,13 +488,14 @@ interface DietRecord {
}
interface ExerciseRecord {
record_time?: string
id?: number | string
diagnosis_id?: number
patient_id?: number
record_date?: string
exercise_type?: string
duration?: number
intensity?: number
duration?: number | null
intensity?: number | null
intensity_text?: string
images?: string[]
note?: string
@@ -437,6 +538,9 @@ const bloodDialogVisible = ref(false)
const dietDialogVisible = ref(false)
const exerciseDialogVisible = ref(false)
const trackingDialogVisible = ref(false)
const dayDetailVisible = ref(false)
const detailDate = ref('')
const originalBloodTime = ref('')
const bloodSubmitting = ref(false)
const dietSubmitting = ref(false)
const exerciseSubmitting = ref(false)
@@ -445,6 +549,11 @@ const trackingSubmitting = ref(false)
const bloodForm = ref<BloodRecord>(createBloodForm())
const dietForm = ref<DietRecord>(createDietForm())
const exerciseForm = ref<ExerciseRecord>(createExerciseForm())
// el-option uses a string sentinel; persisted unknowns remain SQL/JSON null.
const exerciseIntensity = computed<number | ''>({
get: () => exerciseForm.value.intensity ?? '',
set: (value) => { exerciseForm.value.intensity = value === '' ? null : value }
})
const trackingForm = ref({
note_date: '',
existing_content: '',
@@ -455,7 +564,7 @@ const bloodDialogTitle = computed(() => (bloodForm.value.id ? '编辑血糖血
const dietDialogTitle = computed(() => (dietForm.value.id ? '编辑饮食记录' : '新增饮食记录'))
const exerciseDialogTitle = computed(() => (exerciseForm.value.id ? '编辑运动记录' : '新增运动记录'))
const todayDate = computed(() => formatDate(new Date()))
const trackingCanSubmit = computed(() => !readOnly.value && trackingForm.value.note_date === todayDate.value)
const trackingCanSubmit = computed(() => canEditDailyRecord.value && trackingForm.value.note_date === todayDate.value)
const trackingDialogTitle = computed(() => (trackingCanSubmit.value ? '新增/追加跟踪备注' : '查看跟踪备注'))
const tableWrapRef = ref<HTMLElement | null>(null)
const tableWrapWidth = ref(0)
@@ -583,70 +692,63 @@ const hasPatientSelfRecord = computed(() => {
return bloodRecords.value.some((r) => Number((r as any).source) === 1)
})
const bloodByDate = computed(() => {
const map = new Map<string, BloodRecord>()
for (const record of bloodRecords.value) {
// Group actual rows, never a synthetic record bearing the first row's id.
function groupRecordsByDate<T extends { record_date?: string }>(records: T[]): Map<string, T[]> {
const map = new Map<string, T[]>()
for (const record of records) {
const date = String(record.record_date || '')
if (!date) continue
if (!map.has(date)) {
map.set(date, {
id: record.id,
diagnosis_id: record.diagnosis_id,
patient_id: record.patient_id,
record_date: date,
record_time: record.record_time || '',
record_date_ts: record.record_date_ts,
has_patient_self: false
})
}
const merged = map.get(date)!
const fields: Array<keyof BloodRecord> = [
'fasting_blood_sugar',
'postprandial_blood_sugar',
'other_blood_sugar',
'systolic_pressure',
'diastolic_pressure',
'western_medicine',
'insulin',
'remark'
]
for (const field of fields) {
if (
(merged[field] === undefined || merged[field] === null || merged[field] === '') &&
record[field] !== undefined &&
record[field] !== null &&
record[field] !== ''
) {
;(merged as any)[field] = record[field]
}
}
// 当天有任意 source=1 的记录则标记为患者自录
if (Number(record.source) === 1) {
merged.has_patient_self = true
}
const rows = map.get(date) || []
rows.push(record)
map.set(date, rows)
}
return map
})
}
const dietByDate = computed(() => {
const map = new Map<string, DietRecord>()
for (const record of dietRecords.value) {
const date = String(record.record_date || '')
if (!date || map.has(date)) continue
map.set(date, record)
}
return map
})
const bloodByDate = computed(() => groupRecordsByDate(bloodRecords.value))
const dietByDate = computed(() => groupRecordsByDate(dietRecords.value))
const exerciseByDate = computed(() => groupRecordsByDate(exerciseRecords.value))
const dayBloodRecords = computed(() => bloodByDate.value.get(detailDate.value) || [])
const dayDietRecords = computed(() => dietByDate.value.get(detailDate.value) || [])
const dayExerciseRecords = computed(() => exerciseByDate.value.get(detailDate.value) || [])
const mealFields = [{ key: 'breakfast', label: '早餐' }, { key: 'lunch', label: '午餐' }, { key: 'dinner', label: '晚餐' }]
const exerciseByDate = computed(() => {
const map = new Map<string, ExerciseRecord>()
for (const record of exerciseRecords.value) {
const date = String(record.record_date || '')
if (!date || map.has(date)) continue
map.set(date, record)
function recordTimeLabel(record: { record_time?: string }) {
return record.record_time ? String(record.record_time) : '未记录具体时间'
}
function recordTimePeriodLabel(record: BloodRecord) {
const labels: Record<string, string> = {
dawn: '凌晨', early_morning: '清晨', morning: '上午', noon: '中午',
afternoon: '下午', evening: '晚上', night: '夜间', bedtime: '睡前'
}
return map
})
const period = String(record.record_time_period || '')
return labels[period] || period || '未提供时段'
}
function intensityLabel(value?: number | null) {
return ({ 1: '低强度', 2: '中强度', 3: '高强度' } as Record<number, string>)[Number(value)] || '未记录'
}
function bloodDetailFields(record: BloodRecord) {
const show = (value: unknown) => value == null || value === '' ? '—' : String(value)
return [
{ label: '空腹血糖', value: `${show(record.fasting_blood_sugar)} mmol/L` },
{ label: '餐后2h血糖', value: `${show(record.postprandial_blood_sugar)} mmol/L` },
{ label: '其他血糖', value: `${show(record.other_blood_sugar)} mmol/L` },
{ label: '血压', value: record.systolic_pressure || record.diastolic_pressure ? `${formatBp(record)} mmHg` : '—' },
{ label: '西药', value: show(record.western_medicine) },
{ label: '胰岛素', value: show(record.insulin) },
{ label: '备注', value: show(record.remark) }
]
}
function getDayRecordCount(metric: string, date: string) {
if (['breakfast', 'lunch', 'dinner'].includes(metric)) return dietByDate.value.get(date)?.length || 0
if (metric === 'exercise') return exerciseByDate.value.get(date)?.length || 0
if (metric === 'tracking') return 0
return bloodByDate.value.get(date)?.length || 0
}
const trackingByDate = computed(() => {
const map = new Map<string, TrackingNoteRecord>()
@@ -663,9 +765,10 @@ const chartDates = computed(() => [...visibleDates.value].reverse())
const bloodTrendSeries = computed(() => {
return chartDates.value.reduce(
(acc, date) => {
const blood = bloodByDate.value.get(date)
acc.fasting.push(parseTrendNumber(blood?.fasting_blood_sugar))
acc.postprandial.push(parseTrendNumber(blood?.postprandial_blood_sugar))
const records = bloodByDate.value.get(date) || []
const latestValue = (field: keyof BloodRecord) => records.map((record) => parseTrendNumber(record[field])).find((value) => value !== null) ?? null
acc.fasting.push(latestValue('fasting_blood_sugar'))
acc.postprandial.push(latestValue('postprandial_blood_sugar'))
return acc
},
{
@@ -754,89 +857,49 @@ function parseTrendNumber(value: unknown): number | null {
}
function getCell(metric: string, date: string): { value: string; isHigh: boolean; hasRecord: boolean; isPatientSelf?: boolean } {
const blood = bloodByDate.value.get(date)
const diet = dietByDate.value.get(date)
const exercise = exerciseByDate.value.get(date)
const blood = bloodByDate.value.get(date) || []
const diet = dietByDate.value.get(date) || []
const exercise = exerciseByDate.value.get(date) || []
const tracking = trackingByDate.value.get(date)
const isPatientSelf = !!blood?.has_patient_self
switch (metric) {
case 'fasting':
return {
value: blood?.fasting_blood_sugar != null && blood.fasting_blood_sugar !== '' ? String(blood.fasting_blood_sugar) : '',
isHigh: isHighFastingBloodSugar(blood?.fasting_blood_sugar, props.age),
hasRecord: !!blood && blood.fasting_blood_sugar != null && blood.fasting_blood_sugar !== '',
isPatientSelf
}
case 'postprandial':
return {
value: blood?.postprandial_blood_sugar != null && blood.postprandial_blood_sugar !== '' ? String(blood.postprandial_blood_sugar) : '',
isHigh: isHighPostprandialBloodSugar(blood?.postprandial_blood_sugar, props.age),
hasRecord: !!blood && blood.postprandial_blood_sugar != null && blood.postprandial_blood_sugar !== '',
isPatientSelf
}
case 'other':
return {
value: blood?.other_blood_sugar != null && blood.other_blood_sugar !== '' ? String(blood.other_blood_sugar) : '',
isHigh: isHighOtherBloodSugar(blood?.other_blood_sugar, props.age),
hasRecord: !!blood && blood.other_blood_sugar != null && blood.other_blood_sugar !== '',
isPatientSelf
}
case 'bp':
return {
value: blood && (blood.systolic_pressure || blood.diastolic_pressure) ? formatBp(blood) : '',
isHigh: isHighBloodPressure(blood),
hasRecord: !!blood && !!(blood.systolic_pressure || blood.diastolic_pressure),
isPatientSelf
}
case 'western':
return {
value: blood?.western_medicine || '',
isHigh: false,
hasRecord: !!blood?.western_medicine
}
case 'insulin':
return {
value: blood?.insulin || '',
isHigh: false,
hasRecord: !!blood?.insulin
}
case 'breakfast':
return {
value: diet?.breakfast || diet?.breakfast_foods ? '✓' : '',
isHigh: false,
hasRecord: !!(diet?.breakfast || diet?.breakfast_foods)
}
case 'lunch':
return {
value: diet?.lunch || diet?.lunch_foods ? '✓' : '',
isHigh: false,
hasRecord: !!(diet?.lunch || diet?.lunch_foods)
}
case 'dinner':
return {
value: diet?.dinner || diet?.dinner_foods ? '✓' : '',
isHigh: false,
hasRecord: !!(diet?.dinner || diet?.dinner_foods)
}
case 'exercise':
return {
value: exercise?.duration ? `${exercise.duration}min` : '',
isHigh: false,
hasRecord: !!exercise?.id
}
case 'tracking':
return {
value: tracking?.content ? summarizeTracking(tracking.content) : '',
isHigh: false,
hasRecord: !!tracking?.content
}
default:
return { value: '', isHigh: false, hasRecord: false }
const bloodFields: Record<string, keyof BloodRecord> = {
fasting: 'fasting_blood_sugar', postprandial: 'postprandial_blood_sugar',
other: 'other_blood_sugar', western: 'western_medicine', insulin: 'insulin'
}
const field = bloodFields[metric]
if (field || metric === 'bp') {
const rows = blood.filter((record) => metric === 'bp'
? !!(record.systolic_pressure || record.diastolic_pressure)
: record[field] != null && record[field] !== '')
const isHigh = (record: BloodRecord) => {
if (metric === 'fasting') return isHighFastingBloodSugar(record.fasting_blood_sugar, props.age)
if (metric === 'postprandial') return isHighPostprandialBloodSugar(record.postprandial_blood_sugar, props.age)
if (metric === 'other') return isHighOtherBloodSugar(record.other_blood_sugar, props.age)
return metric === 'bp' && isHighBloodPressure(record)
}
return {
value: rows.map((record) => metric === 'bp' ? formatBp(record) : String(record[field])).join(' / '),
isHigh: rows.some(isHigh), hasRecord: rows.length > 0,
isPatientSelf: rows.some((record) => Number(record.source) === 1)
}
}
if (['breakfast', 'lunch', 'dinner'].includes(metric)) {
const count = diet.filter((record) => record[metric] || record[`${metric}_foods`] || record[`${metric}_images`]?.length).length
return { value: count ? '✓' : '', isHigh: false, hasRecord: count > 0 }
}
if (metric === 'exercise') {
return { value: exercise.map((record) => record.duration != null ? `${record.duration}min` : record.exercise_type || '已记录').join(' / '), isHigh: false, hasRecord: exercise.length > 0 }
}
if (metric === 'tracking') {
return { value: tracking?.content ? summarizeTracking(tracking.content) : '', isHigh: false, hasRecord: !!tracking?.content }
}
return { value: '', isHigh: false, hasRecord: false }
}
async function fetchTracking() {
if (!diagnosisId.value) {
const seq = ++requestSeq
const requestDiagnosisId = diagnosisId.value
if (!requestDiagnosisId) {
loading.value = false
bloodRecords.value = []
dietRecords.value = []
exerciseRecords.value = []
@@ -845,23 +908,23 @@ async function fetchTracking() {
}
const { start, end } = currentRange.value
if (rangeMode.value === 'custom' && (!start || !end)) return
const seq = ++requestSeq
const requestDates = [...visibleDates.value]
loading.value = true
try {
const data: any = await diagnosisTrackingWindow({
id: diagnosisId.value,
id: requestDiagnosisId,
start_date: start,
end_date: end
})
const noteData: any = await diagnosisTrackingNotes({
diagnosis_id: diagnosisId.value
diagnosis_id: requestDiagnosisId
})
if (seq !== requestSeq) return
if (seq !== requestSeq || requestDiagnosisId !== diagnosisId.value) return
bloodRecords.value = Array.isArray(data?.blood_records) ? data.blood_records : []
dietRecords.value = Array.isArray(data?.diet_records) ? data.diet_records : []
exerciseRecords.value = Array.isArray(data?.exercise_records) ? data.exercise_records : []
trackingNotes.value = Array.isArray(noteData)
? noteData.filter((item: any) => visibleDates.value.includes(String(item?.note_date || '')))
? noteData.filter((item: any) => requestDates.includes(String(item?.note_date || '')))
: []
} catch {
if (seq === requestSeq) {
@@ -890,76 +953,88 @@ function handleCustomRangeChange() {
}
}
function recordTimeKey(value: unknown) {
const time = String(value || '')
return /^\d{2}:\d{2}$/.test(time) ? `${time}:00` : time
}
function openBloodRecord(source: BloodRecord | undefined, date: string) {
if (!canEditDailyRecord.value) return
bloodForm.value = { ...createBloodForm(date), ...source }
originalBloodTime.value = recordTimeKey(source?.record_time)
bloodDialogVisible.value = true
}
function openDietRecord(source: DietRecord | undefined, date: string) {
if (!canEditDailyRecord.value) return
dietForm.value = {
...createDietForm(date), ...source,
breakfast_images: [...(source?.breakfast_images || [])],
lunch_images: [...(source?.lunch_images || [])], dinner_images: [...(source?.dinner_images || [])]
}
dietDialogVisible.value = true
}
function openExerciseRecord(source: ExerciseRecord | undefined, date: string) {
if (!canEditDailyRecord.value) return
exerciseForm.value = {
...createExerciseForm(date), ...source,
// Existing omissions must not inherit the defaults used only for manual new records.
...(source ? { duration: source.duration ?? null, intensity: source.intensity ?? null } : {}),
images: [...(source?.images || [])]
}
exerciseDialogVisible.value = true
}
function openQuickAdd(kind: DialogKind) {
if (!canEditDailyRecord.value) return
const date = visibleDates.value[0] || formatDate(new Date())
if (kind === 'blood') {
bloodForm.value = createBloodForm(date)
bloodDialogVisible.value = true
return
}
if (kind === 'diet') {
dietForm.value = createDietForm(date)
dietDialogVisible.value = true
return
}
if (kind === 'tracking') {
const today = todayDate.value
const source = trackingByDate.value.get(today)
trackingForm.value = {
note_date: today,
existing_content: String(source?.content || ''),
content: ''
}
trackingDialogVisible.value = true
return
}
exerciseForm.value = createExerciseForm(date)
exerciseDialogVisible.value = true
if (kind === 'blood') return openBloodRecord(undefined, date)
if (kind === 'diet') return openDietRecord(undefined, date)
if (kind === 'exercise') return openExerciseRecord(undefined, date)
handleCellClick('tracking', todayDate.value)
}
function handleCellClick(metric: string, date: string) {
if (!canEditDailyRecord.value) return
if (['fasting', 'postprandial', 'other', 'bp', 'western', 'insulin'].includes(metric)) {
const source = bloodByDate.value.get(date)
bloodForm.value = source ? { ...createBloodForm(date), ...source } : createBloodForm(date)
bloodDialogVisible.value = true
return
}
if (['breakfast', 'lunch', 'dinner'].includes(metric)) {
const source = dietByDate.value.get(date)
dietForm.value = source ? { ...createDietForm(date), ...source } : createDietForm(date)
dietDialogVisible.value = true
return
}
if (!isCellClickable(metric, date)) return
if (metric === 'tracking') {
const source = trackingByDate.value.get(date)
if (!source && date !== todayDate.value) return
trackingForm.value = {
note_date: date,
existing_content: String(source?.content || ''),
content: ''
}
trackingForm.value = { note_date: date, existing_content: String(source?.content || ''), content: '' }
trackingDialogVisible.value = true
return
}
const source = exerciseByDate.value.get(date)
exerciseForm.value = source ? { ...createExerciseForm(date), ...source } : createExerciseForm(date)
exerciseDialogVisible.value = true
const count = (bloodByDate.value.get(date)?.length || 0) + (dietByDate.value.get(date)?.length || 0) + (exerciseByDate.value.get(date)?.length || 0)
if (count) {
detailDate.value = date
dayDetailVisible.value = true
return
}
if (['breakfast', 'lunch', 'dinner'].includes(metric)) return openDietRecord(undefined, date)
if (metric === 'exercise') return openExerciseRecord(undefined, date)
openBloodRecord(undefined, date)
}
async function submitBlood() {
if (!canEditDailyRecord.value || bloodSubmitting.value) return
if (!bloodForm.value.record_date) {
feedback.msgWarning('请选择记录日期')
return
}
const targetDiagnosisId = diagnosisId.value
const payload = { ...bloodForm.value }
if ('record_time_estimated' in payload && recordTimeKey(payload.record_time) !== originalBloodTime.value) {
payload.record_time_estimated = 0
payload.record_time_period = ''
payload.record_time_text = ''
}
bloodSubmitting.value = true
try {
if (bloodForm.value.id) {
await bloodRecordEdit(bloodForm.value)
if (payload.id) {
await bloodRecordEdit(payload)
} else {
await bloodRecordAdd(bloodForm.value)
await bloodRecordAdd(payload)
}
if (targetDiagnosisId !== diagnosisId.value) return
bloodDialogVisible.value = false
await fetchTracking()
} finally {
@@ -968,17 +1043,21 @@ async function submitBlood() {
}
async function submitDiet() {
if (!canEditDailyRecord.value || dietSubmitting.value) return
if (!dietForm.value.record_date) {
feedback.msgWarning('请选择记录日期')
return
}
const targetDiagnosisId = diagnosisId.value
const payload = { ...dietForm.value }
dietSubmitting.value = true
try {
if (dietForm.value.id) {
await dietRecordEdit(dietForm.value)
if (payload.id) {
await dietRecordEdit(payload)
} else {
await dietRecordAdd(dietForm.value)
await dietRecordAdd(payload)
}
if (targetDiagnosisId !== diagnosisId.value) return
dietDialogVisible.value = false
await fetchTracking()
} finally {
@@ -987,6 +1066,7 @@ async function submitDiet() {
}
async function submitExercise() {
if (!canEditDailyRecord.value || exerciseSubmitting.value) return
if (!exerciseForm.value.record_date) {
feedback.msgWarning('请选择记录日期')
return
@@ -995,17 +1075,20 @@ async function submitExercise() {
feedback.msgWarning('请选择运动类型')
return
}
if (!exerciseForm.value.duration) {
if (!exerciseForm.value.id && !exerciseForm.value.duration) {
feedback.msgWarning('请输入运动时长')
return
}
const targetDiagnosisId = diagnosisId.value
const payload = { ...exerciseForm.value, duration: exerciseForm.value.duration ?? null, intensity: exerciseForm.value.intensity ?? null }
exerciseSubmitting.value = true
try {
if (exerciseForm.value.id) {
await exerciseRecordEdit(exerciseForm.value)
if (payload.id) {
await exerciseRecordEdit(payload)
} else {
await exerciseRecordAdd(exerciseForm.value)
await exerciseRecordAdd(payload)
}
if (targetDiagnosisId !== diagnosisId.value) return
exerciseDialogVisible.value = false
await fetchTracking()
} finally {
@@ -1014,6 +1097,7 @@ async function submitExercise() {
}
async function submitTracking() {
if (trackingSubmitting.value) return
if (!trackingForm.value.note_date) {
feedback.msgWarning('请选择记录日期')
return
@@ -1027,12 +1111,14 @@ async function submitTracking() {
feedback.msgWarning('请输入跟踪备注')
return
}
const targetDiagnosisId = diagnosisId.value
trackingSubmitting.value = true
try {
await diagnosisAddTrackingNote({
diagnosis_id: diagnosisId.value,
diagnosis_id: targetDiagnosisId,
tracking_content: content
})
if (targetDiagnosisId !== diagnosisId.value) return
trackingDialogVisible.value = false
await fetchTracking()
} finally {
@@ -1057,17 +1143,23 @@ function getTrackingPreview(content: string) {
}
function isCellClickable(metric: string, date: string) {
if (!canEditDailyRecord.value) return false
if (metric !== 'tracking') return true
return date === todayDate.value || !!getTrackingContent(date)
if (metric === 'tracking') return !!getTrackingContent(date) || (canEditDailyRecord.value && date === todayDate.value)
return canEditDailyRecord.value || getDayRecordCount(metric, date) > 0
}
watch(
() => props.diagnosisId,
(value) => {
if (value) {
fetchTracking()
}
() => {
dayDetailVisible.value = false
bloodDialogVisible.value = false
dietDialogVisible.value = false
exerciseDialogVisible.value = false
trackingDialogVisible.value = false
bloodRecords.value = []
dietRecords.value = []
exerciseRecords.value = []
trackingNotes.value = []
void fetchTracking()
void nextTick(updateTableWrapWidth)
}
)
@@ -1081,6 +1173,7 @@ onMounted(() => {
})
onUnmounted(() => {
requestSeq++
window.removeEventListener('resize', updateTableWrapWidth)
})
@@ -1116,6 +1209,29 @@ defineExpose({ refresh: fetchTracking })
width: 100%;
}
&__hint, &__time-evidence {
color: var(--el-text-color-secondary);
font-size: 12px;
line-height: 1.6;
margin: 0 0 12px;
overflow-wrap: anywhere;
}
&__record-count { color: var(--el-color-primary); font-size: 11px; white-space: nowrap; }
&__detail-section + &__detail-section { margin-top: 24px; }
&__detail-heading { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
&__detail-heading h3 { margin: 0 0 8px; }
&__detail-heading small { color: var(--el-text-color-secondary); font-weight: normal; }
&__detail-record { border: 1px solid var(--el-border-color); border-radius: 8px; padding: 12px; margin-bottom: 12px; }
&__detail-tags { display: flex; gap: 8px; flex-wrap: wrap; margin: 8px 0; }
&__detail-fields {
display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: 8px; margin: 12px 0 0;
dt { color: var(--el-text-color-secondary); }
dd { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
}
&__detail-images { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
&__detail-images .el-image { width: 64px; height: 64px; border-radius: 4px; }
&__chart {
margin-top: 16px;
padding: 16px 18px;
@@ -0,0 +1,26 @@
<template>
<span v-if="readonly" class="readonly-value">{{ fieldText(modelValue, field) }}</span>
<el-input-number v-else-if="field.type === 'number'" :model-value="numberValue" :disabled="disabled" :controls="false" @update:model-value="(value: number | undefined | null) => emit('update:modelValue', value ?? null)" />
<el-select v-else-if="field.type === 'select' || field.type === 'multiselect'" :model-value="selectValue" :multiple="field.type === 'multiselect'" :disabled="disabled" clearable filterable @update:model-value="(value: FollowupValue) => emit('update:modelValue', value)">
<el-option v-for="option in field.options || []" :key="String(option.value)" :label="option.label" :value="option.value" />
</el-select>
<el-date-picker v-else-if="field.type === 'date'" :model-value="textValue" type="date" value-format="YYYY-MM-DD" :disabled="disabled" @update:model-value="(value: string | null) => emit('update:modelValue', value || null)" />
<el-input v-else :model-value="textValue" type="textarea" :autosize="{ minRows: 1, maxRows: 5 }" :disabled="disabled" @update:model-value="(value: FollowupValue) => emit('update:modelValue', value)" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { FollowupField, FollowupValue } from '@/api/followupAudio'
import { fieldText } from './followupAudioState'
const props = defineProps<{ field: FollowupField; modelValue?: FollowupValue; disabled?: boolean; readonly?: boolean }>()
const emit = defineEmits<{ (event: 'update:modelValue', value: FollowupValue): void }>()
const numberValue = computed(() => props.modelValue === null || props.modelValue === undefined || props.modelValue === '' ? undefined : Number(props.modelValue))
const textValue = computed(() => props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue))
const selectValue = computed(() => {
const canonical = (value: string | number) => props.field.options?.find(option => String(option.value) === String(value))?.value ?? value
if (props.field.type === 'multiselect') return Array.isArray(props.modelValue) ? props.modelValue.map(canonical) : []
return typeof props.modelValue === 'string' || typeof props.modelValue === 'number' ? canonical(props.modelValue) : ''
})
</script>
<style scoped>
.readonly-value { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.6; }
</style>
@@ -0,0 +1,722 @@
<template>
<section v-if="featureEnabled" class="followup-panel" aria-label="回访录音">
<div class="panel-toolbar">
<div class="toolbar-title">
<el-button v-if="selectedId" link type="primary" :disabled="busy" @click="backToList">返回列表</el-button>
<h3 v-else>回访录音 <span>{{ tasks.length }}</span></h3>
</div>
<div class="toolbar-actions">
<el-button link :aria-expanded="helpVisible" @click="helpVisible = !helpVisible">使用说明</el-button>
<el-button :loading="loading" :disabled="busy" @click="refresh">刷新</el-button>
<el-button v-if="!selectedId && !viewOnly && capabilities.can_upload" type="primary" :disabled="!canUpload || busy || createUncertain" @click="openUpload">上传录音</el-button>
</div>
</div>
<div v-if="helpVisible" class="help-box">
<p v-if="previewOnly">{{ capabilities.preview_only ? '当前仅开放测试识别与提炼,可核对并保存审核草稿;测试预览任务不提供确认写入。' : '这是历史测试任务,不写入病例;新上传的真实录音可按正常业务流程审核后确认入单。' }}</p>
<p v-else>录音只生成建议,不会自动写入。逐项核对后选择采纳,再确认写入;日常记录按日期和时段分别保留。</p>
<p>仅当前可见标签页每 5 秒刷新;已编辑内容不会被覆盖。后台分析不受关闭页面影响,未知结果请先核对任务或账单,勿重复上传。</p>
<p v-if="detail">任务 #{{ detail.id }} · 版本 {{ detail.version }} · 保留至 {{ formatExpiry(detail.expires_at) }}</p>
</div>
<el-alert v-if="previewOnly" type="warning" :closable="false" :title="capabilities.preview_only ? '仅测试识别与提炼,不写入病例' : '历史测试任务,仅供查看和审阅'" description="此任务保留测试用途。新业务录音请新建任务,人工核对后确认入单。" show-icon />
<el-alert v-if="!audioReady" type="warning" :closable="false" :title="capabilities.preview_only ? '测试预览尚未就绪,暂不可上传或重试。已有任务可查看。' : '当前环境尚未通过音频能力验证,暂不可上传或重试。已有任务可查看。'" />
<el-alert v-else-if="capabilities.can_upload && !capabilities.models.length" type="warning" :closable="false" title="暂无可用的分析模型,暂不可上传。已有任务可查看。" />
<el-alert v-if="basicDirty" type="warning" :closable="false" :title="previewOnly ? '病历有未保存修改,测试预览不会覆盖这些修改。' : '病历有未保存修改,请先保存病历,再写入录音建议。'" />
<el-alert v-if="createUncertain" type="warning" :closable="false" title="创建结果未确认,已停止重复提交。请刷新列表并联系管理员核对,不要重新上传同一录音。" />
<el-alert v-if="errorMessage" type="error" :closable="false" :title="errorMessage" show-icon />
<div v-if="!selectedId" class="task-list">
<el-table :data="tasks" max-height="440" size="small" table-layout="fixed" empty-text="暂无录音,上传后可提炼回访资料" aria-label="录音任务列表">
<el-table-column label="录音" min-width="210">
<template #default="{ row }">
<el-button class="filename-button" link type="primary" :disabled="busy" @click="openTask(row.id)">{{ row.file_name }}</el-button>
<div class="task-time">{{ row.recorded_at }}</div>
</template>
</el-table-column>
<el-table-column label="状态" width="145">
<template #default="{ row }"><el-tag size="small" :type="statusType(row.status)">{{ followupTaskStatus(row) }}</el-tag><div v-if="row.transcript_available && (row.status === 'failed' || row.status === 'needs_reconciliation')" class="task-time">转写已保留</div></template>
</el-table-column>
<el-table-column label="操作" width="112" align="right">
<template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="openTask(row.id)">查看</el-button><el-button v-if="!viewOnly && row.can_delete !== undefined" link type="danger" :disabled="busy || !canDeleteTask(row)" :title="row.delete_block_reason || '删除未入单录音任务'" @click="deleteRecording(row)">删除</el-button></template>
</el-table-column>
</el-table>
</div>
<div v-else-if="!detail" class="detail-loading" role="status">正在加载录音任务…</div>
<section v-if="selectedId && detail" class="task-detail" aria-label="录音任务详情">
<div class="detail-heading">
<div class="recording-title"><h3>{{ detail.file_name }}</h3><span>通话时间 {{ detail.recorded_at }}</span></div>
<div class="detail-actions"><el-tag size="small" :type="statusType(detail.status)">{{ followupTaskStatus(detail) }}</el-tag><el-button v-if="!viewOnly && detail.can_delete !== undefined" link type="danger" :disabled="busy || !canDeleteTask(detail)" :title="detail.delete_block_reason || '删除未入单录音任务'" @click="deleteRecording(detail)">删除录音</el-button></div>
</div>
<p v-if="detail.status === 'running' || detail.status === 'queued'" class="processing-state" role="status">{{ followupProgressText(detail) }}</p>
<el-alert v-if="detail.error_message || detail.status === 'failed'" :type="detail.status === 'failed' ? 'error' : 'warning'" :closable="false" :title="detail.error_message || '任务处理失败,不能写入;请先核对失败原因。'" />
<el-alert v-if="retainedTranscriptNotice(detail)" type="warning" :closable="false" :title="retainedTranscriptNotice(detail)" />
<el-alert v-if="detail.status === 'needs_reconciliation'" type="error" :closable="false" title="上游结果待核对,禁止重发。请管理员先确认上游任务或账单。" />
<el-alert v-if="detail.status === 'expired'" type="warning" :closable="false" title="录音和转录已过保留期,不能继续写入;已采纳的业务记录保留。" />
<el-button v-if="detail.can_retry && detail.status === 'failed' && !viewOnly" class="retry-button" :disabled="!canUpload || busy" @click="retryTask">重试已确认失败的任务</el-button>
<div class="summary-box">
<div class="muted">回访摘要 · AI未核实草稿,不代表已确认病情</div>
<p>{{ detail.summary || '暂无回访摘要' }}</p>
<div class="summary-counts"><span>{{ detail.status === 'applied' ? '已写入' : '已选' }} <strong>{{ selectedCount }}</strong> 项</span><span>待核实 <strong>{{ pendingCount }}</strong> 项</span></div>
</div>
<el-alert v-if="detail.status === 'review' && !reviewItems.length" type="warning" :closable="false" title="未生成可写入信息" :description="detail.uncertainties.length ? `本次提炼保留了 ${detail.uncertainties.length} 条待核实原因,已展示在下方。请结合原文回听核对,尤其注意声道角色是否相符。` : '请查看回访摘要并回听录音;本次没有可供确认写入的结构化候选。'" show-icon />
<section v-if="hasStereo && !['queued', 'running'].includes(detail.status)" class="channel-role-box" aria-label="声道角色人工标注">
<div v-if="savedChannelRoles !== 'unconfirmed' && !editingRoles && !roleDirty" class="role-summary"><span>{{ savedChannelRoles === 'left_service' ? '左客服端 / 右患者或家属端' : '右客服端 / 左患者或家属端' }} · 已确认</span><el-button v-if="canEditReview" link type="primary" @click="editingRoles = true">修改</el-button></div>
<label v-else>声道角色(人工确认)<el-select :model-value="channelRoles" :disabled="!canEditReview || (busy && mutation !== 'save')" @update:model-value="setChannelRoles"><el-option label="角色待确认" value="unconfirmed" /><el-option label="左客服端 / 右患者或家属端" value="left_service" /><el-option label="右客服端 / 左患者或家属端" value="right_service" /></el-select></label>
<p v-if="savedChannelRoles === 'unconfirmed' || editingRoles || roleDirty" class="muted">声道不等于已核实的说话人身份。角色标注不自动重新提炼;变更后保存草稿会取消全部采纳,须重新核对。</p>
<p v-if="savedChannelRoles !== 'unconfirmed' && !roleDirty" class="muted">当前角色已确认,无需再次选择;只有左右标错时才需修改。</p>
<p v-if="roleDirty" class="review-error" role="status">角色标注正在等待保存;保存后请逐项重新核对。</p>
</section>
<section v-if="detail.role_check?.conflict || (detail.can_reextract !== undefined && savedChannelRoles !== extractionRoles && savedChannelRoles !== 'unconfirmed')" class="role-reextract" aria-label="角色纠错与重新提炼">
<strong>{{ detail.role_check?.conflict ? '声道角色与转写内容可能不一致' : '审核角色已修改,原提炼结果尚未更新' }}</strong>
<p>{{ detail.role_check?.message || '修改角色标注不会自动改变已生成的建议,可按核实后的角色重新提炼。' }}</p>
<blockquote v-for="(evidence, index) in detail.role_check?.evidence || []" :key="index"><span>{{ evidence.channel === 0 ? '左声道' : '右声道' }} · {{ audioTimestamp(evidence.start_ms) }}:{{ evidence.text }}</span><el-button v-if="detail.audio_available" link type="primary" @click="loadDialogue(evidence.start_ms)">回听依据</el-button></blockquote>
<p>当前提炼依据:{{ extractionRoleLabel(extractionRoles) }}。{{ reextractTarget !== 'unconfirmed' ? `待确认的新角色:${extractionRoleLabel(reextractTarget)}。` : '请先回听并修改上方角色标注。' }}建议仅供核对,系统不会自动交换角色。</p>
<el-button type="primary" plain :disabled="!canReextract || busy || dirty || reextractTarget === 'unconfirmed' || reextractTarget === extractionRoles" @click="reextractWithRoles">确认角色并重新提炼</el-button>
<p v-if="dirty">请先完成当前单项核对或取消编辑,等待审核草稿保存后再重新提炼。</p>
<p v-else-if="detail.reextract_block_reason">{{ detail.reextract_block_reason }}</p>
<p class="muted">复用已完成的转写,不重复语音识别;旧结果保留,重新提炼不自动写入病例。</p>
</section>
<p v-if="(detail.extraction_revision || 0) > 0" class="muted">第 {{ (detail.extraction_revision || 0) + 1 }} 版提炼 · {{ extractionRoleLabel(extractionRoles) }} · 历史结果已保留</p>
<FollowupAudioReview :key="selectedId" ref="reviewRef" v-model:items="reviewItems" :fields="detail.fields || capabilities.fields" :disabled="!canEditReview || uploading || (mutation !== '' && mutation !== 'save')" :can-daily="capabilities.can_daily" :applied="detail.status === 'applied'" :uncertainties="detail.uncertainties" :snapshot-items="detail.items" :channel-roles="savedChannelRoles" :save-state="saveState" :persisted-revision="persistedRevision" @saved-next="saveDraft(true)" @seek="loadDialogue">
<template #player>
<div class="audio-player">
<el-button v-if="detail.audio_available" size="small" :loading="audioLoading" @click="reloadAudio">{{ audioUrl ? '重新加载录音' : '加载录音播放' }}</el-button>
<span v-else class="muted">录音不可播放或已清理</span>
<audio v-if="audioUrl" :key="audioUrl" ref="audioElement" :src="audioUrl" controls preload="metadata" />
</div>
<div v-if="hasStereo && detail.audio_available" class="channel-playback" aria-label="声道回听">
<el-button size="small" :type="playbackChannel === 'original' ? 'primary' : 'default'" :aria-pressed="playbackChannel === 'original'" :disabled="audioLoading || channelLoading" @click="playChannel('original')">完整对话</el-button>
<el-button v-for="channel in ([0, 1] as const)" :key="channel" size="small" :type="playbackChannel === channel ? 'primary' : 'default'" :aria-pressed="playbackChannel === channel" :disabled="audioLoading || channelLoading" @click="playChannel(channel)">{{ channelPlaybackLabel(channel, savedChannelRoles) }}</el-button>
<span class="muted" role="status">{{ channelLoading ? '正在切换声道…' : !audioUrl ? '尚未加载录音' : playbackChannel === 'original' ? '回听模式:双方对话' : `回听模式:仅${playbackChannel === 0 ? '左' : '右'}声道` }}</span>
</div>
<p v-if="playbackError" class="review-error" role="alert">{{ playbackError }}</p>
<p v-if="detail.audio_available" class="muted">回听对话默认从该区间前 3 秒开始,连续播放双方声音;可随时切换为只听一方。</p>
</template>
</FollowupAudioReview>
<el-collapse v-model="detailSections" class="original-collapse">
<el-collapse-item title="完整对话转写" name="original">
<div v-if="transcriptSegments.length" class="transcript-segments">
<p class="muted">双方转写按同一时间区间并列展示,不表示发言先后;重叠发言与具体问答请结合录音核对。</p>
<section v-for="window in conversationWindows" :key="window.id" class="transcript-segment">
<div class="segment-heading"><span>{{ audioTimestamp(window.start_ms) }}–{{ audioTimestamp(window.end_ms) }}</span><el-button v-if="detail.audio_available" link type="primary" @click="loadDialogue(window.start_ms)">回听双方对话</el-button></div>
<div class="dialogue-sides">
<div v-for="segment in window.segments" :key="segment.id" class="dialogue-side">
<strong>{{ followupChannelLabel(segment.channel, savedChannelRoles) }}</strong>
<pre>{{ segment.text || '(该区间无转写文本,不代表没有说话)' }}</pre>
</div>
</div>
</section>
</div>
<pre v-else class="transcript-text">{{ detail.transcript || '暂无转录' }}</pre>
</el-collapse-item>
</el-collapse>
<div v-if="detail.status === 'review'" class="review-actions">
<div class="selection-summary"><strong>已选 {{ selectedCount }} 项</strong><span>{{ saveStatusText }}</span></div>
<div v-if="canEditReview" class="action-buttons">
<el-button link :disabled="busy" :loading="mutation === 'save'" @click="saveDraft()">{{ saveState === 'error' || saveState === 'conflict' ? '重试保存草稿' : '立即保存草稿' }}</el-button>
<el-button v-if="canApplyReview" type="primary" :disabled="busy || basicDirty || !selectedCount || !!applyIssue" :loading="mutation === 'apply'" @click="applySelected">确认写入</el-button>
</div>
<p v-if="applyIssue" class="review-error" role="alert">{{ applyIssue }}</p>
</div>
<p v-if="detail.status === 'applied'" class="applied-note">{{ previewOnly ? '该任务已有历史采纳记录;当前为测试预览,不允许再次写入。' : '本次审核已完成,所选项已写入诊单或日常记录,不能重复写入。' }}</p>
</section>
<el-dialog v-model="uploadVisible" title="上传回访录音" width="min(520px, calc(100vw - 32px))" append-to-body :close-on-click-modal="false" :close-on-press-escape="!uploading" :show-close="!uploading" :before-close="closeUpload">
<el-form label-position="top" class="upload-form">
<el-form-item label="录音文件">
<input ref="fileInput" type="file" accept="audio/mpeg,audio/mp4,audio/wav,audio/amr,.mp3,.m4a,.wav,.amr" :disabled="!canUpload || busy || createUncertain" aria-label="录音文件" @change="chooseFile" />
<small>支持 MP3 / M4A / WAV / AMR,最多 {{ Math.floor(capabilities.limits.max_bytes / 1024 / 1024) }} MB / {{ Math.floor(capabilities.limits.max_seconds / 60) }} 分钟。</small>
</el-form-item>
<el-form-item label="实际通话时间(北京时间)">
<el-date-picker v-model="recordedAt" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="用于识别昨天、前天等相对日期" :disabled="!canUpload || busy || createUncertain" />
</el-form-item>
<el-form-item label="本次录音的声道角色">
<el-select v-model="uploadChannelRoles" aria-label="本次录音的声道角色" :disabled="!canUpload || busy || createUncertain">
<el-option label="暂不确定 / 单声道" value="unconfirmed" />
<el-option label="左客服 / 右患者或家属" value="left_service" />
<el-option label="右客服 / 左患者或家属" value="right_service" />
</el-select>
<small>已知角色会在提炼前提供给模型;不确定请勿猜测。单声道不按左右区分身份。</small>
</el-form-item>
<el-collapse class="advanced-settings">
<el-collapse-item title="高级设置 · 分析模型" name="model">
<el-form-item label="分析模型">
<el-select v-model="modelKey" :disabled="!canUpload || busy || createUncertain" placeholder="选择已配置的模型"><el-option v-for="model in capabilities.models" :key="model.value" :label="model.label" :value="model.value" /></el-select>
</el-form-item>
</el-collapse-item>
</el-collapse>
</el-form>
<el-alert v-if="errorMessage" type="error" :closable="false" :title="errorMessage" show-icon />
<el-alert v-if="createUncertain && !uploading" type="warning" :closable="false" title="创建结果未确认,请关闭弹窗后刷新任务列表并联系管理员核对,不要重新上传。" />
<el-progress v-if="uploading" :percentage="uploadProgress" />
<p v-if="uploadStage" class="upload-stage" role="status">{{ uploadStage }}</p>
<p class="muted">{{ previewOnly ? '本次仅测试识别与提炼,可保存审核草稿,不允许写入病历。' : '分析仅生成建议,人工确认后才会写入。' }}</p>
<template #footer><el-button :disabled="uploading" @click="closeUpload()">取消</el-button><el-button type="primary" :disabled="!canUpload || busy || createUncertain" :loading="uploading" @click="submitUpload">上传并分析</el-button></template>
</el-dialog>
</section>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
FollowupAudioError, followupAudioReextract, followupAudioDelete, followupAudioApply, followupAudioBlob, followupAudioCreate,
followupAudioDetail, followupAudioLists, followupAudioRetry, followupAudioSaveDraft,
followupAudioUploadChunk, followupAudioUploadComplete, followupAudioUploadSession,
type FollowupAudioChannel, type FollowupCapabilities, type FollowupChannelRoles, type FollowupReviewItem, type FollowupTaskDetail, type FollowupTaskSummary
} from '@/api/followupAudio'
import FollowupAudioReview from './FollowupAudioReview.vue'
import { channelPlaybackLabel, dialogueWindows, dialoguePlaybackStart, audioTimestamp, changedReviewTarget, cloneReviewItems, createFollowupScope, followupAudioReady, followupCanApply, followupCanReview, followupChannelLabel, followupError, followupFeatureEnabled, followupProgressText, followupTaskStatus, hasStereoTranscript, normalizedChannelRoles, rebaseReviewItems, retainedTranscriptNotice, reviewBatchIssue, reviewFieldIssue, reviewIssue, reviewPending, uploadChunks, uploadIssue } from './followupAudioState'
import { createFollowupAudioPlayback, type FollowupPlaybackChannel } from './followupAudioPlayback'
const props = withDefaults(defineProps<{
diagnosisId: number; viewOnly?: boolean; active?: boolean; capabilities: FollowupCapabilities;
basicDirty?: boolean; beforeApply?: () => boolean
}>(), { viewOnly: false, active: true, basicDirty: false })
const emit = defineEmits<{ (event: 'applied', diagnosisId: number): void }>()
const tasks = ref<FollowupTaskSummary[]>([])
const detail = ref<FollowupTaskDetail | null>(null)
const reviewItems = ref<FollowupReviewItem[]>([])
const selectedId = ref(0)
const snapshot = ref('[]')
const channelRoles = ref<FollowupChannelRoles>('unconfirmed')
const roleSnapshot = ref<FollowupChannelRoles>('unconfirmed')
const editingRoles = ref(false)
const saveState = ref<'idle' | 'pending' | 'saving' | 'saved' | 'error' | 'conflict'>('idle')
const persistedRevision = ref(0)
const committedDirty = computed(() => roleDirty.value || JSON.stringify(reviewItems.value) !== snapshot.value)
const saveStatusText = computed(() => saveState.value === 'saving' ? '正在自动保存…'
: saveState.value === 'error' ? '保存失败,修改仍保留;请重试保存'
: saveState.value === 'conflict' ? '自动保存已暂停;请重新核对后重试保存'
: committedDirty.value ? '等待自动保存…'
: reviewRef.value?.hasUnsavedChanges() ? '当前单项尚未完成核对'
: saveState.value === 'saved' ? '审核草稿已自动保存' : '草稿已同步')
const roleDirty = computed(() => channelRoles.value !== roleSnapshot.value)
const savedChannelRoles = computed(() => normalizedChannelRoles(detail.value?.channel_roles))
const transcriptSegments = computed(() => [...(detail.value?.transcript_segments || [])].sort((a, b) => a.start_ms - b.start_ms || (a.channel ?? -1) - (b.channel ?? -1)))
const conversationWindows = computed(() => dialogueWindows(transcriptSegments.value))
const hasStereo = computed(() => hasStereoTranscript(transcriptSegments.value))
const reviewRef = ref<{ hasUnsavedChanges: () => boolean } | null>(null)
const dirty = computed(() => roleDirty.value || JSON.stringify(reviewItems.value) !== snapshot.value || !!reviewRef.value?.hasUnsavedChanges())
const uploadVisible = ref(false)
const helpVisible = ref(false)
const detailSections = ref<string[]>([])
const file = ref<File | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)
const recordedAt = ref('')
const uploadChannelRoles = ref<FollowupChannelRoles>('unconfirmed')
const modelKey = ref(props.capabilities.models[0]?.value || '')
const loading = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStage = ref('')
const createUncertain = ref(false)
const mutation = ref<'save' | 'apply' | 'retry' | 'delete' | 'reextract' | ''>('')
const errorMessage = ref('')
const audioUrl = ref('')
const audioElement = ref<HTMLAudioElement | null>(null)
const audioLoading = ref(false)
const playbackChannel = ref<FollowupPlaybackChannel>('original')
const channelLoading = ref(false)
const playbackError = ref('')
const documentVisible = ref(typeof document === 'undefined' || document.visibilityState !== 'hidden')
const busy = computed(() => uploading.value || !!mutation.value)
const featureEnabled = computed(() => followupFeatureEnabled(props.capabilities))
const previewOnly = computed(() => !!props.capabilities.preview_only || !!detail.value?.preview_only)
const audioReady = computed(() => followupAudioReady(props.capabilities))
const canUpload = computed(() => !props.viewOnly && featureEnabled.value && audioReady.value && props.capabilities.can_upload && props.capabilities.models.length > 0)
const canEditReview = computed(() => !props.viewOnly && followupCanReview(props.capabilities, !!detail.value?.preview_only) && detail.value?.status === 'review')
const canApplyReview = computed(() => !props.viewOnly && followupCanApply(props.capabilities, !!detail.value?.preview_only) && detail.value?.status === 'review')
const extractionRoles = computed(() => normalizedChannelRoles(detail.value?.extraction_channel_roles))
const reextractTarget = computed<FollowupChannelRoles>(() => {
if (savedChannelRoles.value !== 'unconfirmed' && savedChannelRoles.value !== extractionRoles.value) return savedChannelRoles.value
return normalizedChannelRoles(detail.value?.role_check?.suggested_roles)
})
const canReextract = computed(() => !props.viewOnly && featureEnabled.value && detail.value?.status === 'review' && detail.value?.can_reextract === true)
const selectedCount = computed(() => reviewItems.value.filter(item => item.selected).length)
const pendingCount = computed(() => reviewItems.value.filter(item => reviewPending(item, detail.value?.fields || props.capabilities.fields, props.capabilities.can_daily)).length + (detail.value?.uncertainties.length || 0))
const applyIssue = computed(() => previewOnly.value ? '测试预览仅保存审核草稿,不允许确认写入病历'
: saveState.value === 'conflict' ? '记录版本已变化,请重新核对后重试保存草稿'
: saveState.value === 'error' ? '草稿保存失败,请重试保存成功后再确认写入'
: saveState.value === 'saving' || committedDirty.value ? '审核草稿尚未保存完成,请稍候再确认写入'
: roleDirty.value ? '声道角色标注尚未保存,请先保存草稿并重新核对建议'
: hasStereo.value && savedChannelRoles.value === 'unconfirmed' ? '请先回听并确认声道角色,保存草稿后重新核对建议'
: changedReviewTarget(reviewItems.value, detail.value?.items || [])
? '写入目标或记录日期已更改,请先保存审核草稿取得新快照,再核对并采纳'
: reviewBatchIssue(reviewItems.value, detail.value?.fields || props.capabilities.fields) || reviewItems.value.map(item => reviewFieldIssue(item, detail.value?.fields || props.capabilities.fields) || reviewIssue(item, props.capabilities.can_daily)).find(Boolean) || '')
const effectiveActive = computed(() => props.active && featureEnabled.value && documentVisible.value)
const scope = createFollowupScope()
let timer: ReturnType<typeof setTimeout> | undefined
let autosaveTimer: ReturnType<typeof setTimeout> | undefined
let hydrating = false
let savePromise: Promise<void> | null = null
let pollRunning = false
let audioRequest = 0
let playbackRequest = 0
let playback: ReturnType<typeof createFollowupAudioPlayback> | null = null
let playbackElement: HTMLAudioElement | null = null
let lastDiagnosis = 0
function clearTimer() { if (timer !== undefined) clearTimeout(timer); timer = undefined }
function releaseAudio() {
audioRequest++; playbackRequest++
playback?.dispose(); playback = null; playbackElement = null
audioElement.value?.pause()
if (audioUrl.value) URL.revokeObjectURL(audioUrl.value)
audioUrl.value = ''; audioLoading.value = false; channelLoading.value = false; playbackChannel.value = 'original'; playbackError.value = ''
}
function stop() {
scope.invalidate(); clearTimer(); clearAutosave(); releaseAudio()
savePromise = null
if (saveState.value === 'saving') { saveState.value = 'error'; errorMessage.value = '保存结果尚未确认;修改仍保留,请刷新核对版本后重试保存。' }
loading.value = false; uploading.value = false; mutation.value = ''; pollRunning = false
}
function installDetail(fresh: FollowupTaskDetail, preserve: boolean, preserveRoles = preserve) {
// Completed tasks use the server's confirmed snapshot, never an unsaved local draft.
preserve = preserve && fresh.status === 'review'
const keepRoles = preserveRoles && roleDirty.value && fresh.status === 'review'
if (!fresh.audio_available) releaseAudio()
if (retainedTranscriptNotice(fresh) && (!detail.value || detail.value.status !== fresh.status || !detail.value.transcript_available)) {
if (!detailSections.value.includes('original')) detailSections.value = [...detailSections.value, 'original']
}
hydrating = true
try {
detail.value = fresh
const nextItems = preserve ? rebaseReviewItems(reviewItems.value, fresh.items) : cloneReviewItems(fresh.items)
if (JSON.stringify(nextItems) !== JSON.stringify(reviewItems.value)) reviewItems.value = nextItems
snapshot.value = JSON.stringify(fresh.items)
roleSnapshot.value = normalizedChannelRoles(fresh.channel_roles)
if (!keepRoles) channelRoles.value = roleSnapshot.value
} finally { hydrating = false }
}
function resetRoles() { hydrating = true; channelRoles.value = 'unconfirmed'; roleSnapshot.value = 'unconfirmed'; hydrating = false; editingRoles.value = false; saveState.value = 'idle'; persistedRevision.value = 0 }
function setChannelRoles(value: unknown) {
if (!canEditReview.value || (busy.value && mutation.value !== 'save') || !hasStereo.value || !['unconfirmed', 'left_service', 'right_service'].includes(String(value))) return
channelRoles.value = value as FollowupChannelRoles
}
function taskUnavailable(error: unknown): boolean {
return error instanceof FollowupAudioError && (error.code === 'FOLLOWUP_AUDIO_TASK_UNAVAILABLE' || error.message.includes('FOLLOWUP_AUDIO_TASK_UNAVAILABLE'))
}
function forgetUnavailableTask(id: number) {
if (selectedId.value !== id) return
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []
tasks.value = tasks.value.filter(row => row.id !== id)
errorMessage.value = '录音已删除或不再可访问,已关闭本页缓存与播放;未写入病例。'
void refresh()
}
async function readDetail(id: number, preserve = false, verifyOnly = false) {
const ticket = scope.capture()
let fresh: FollowupTaskDetail
try { fresh = await followupAudioDetail(id, ticket.signal) }
catch (error) {
if (scope.current(ticket) && id === selectedId.value && taskUnavailable(error)) { forgetUnavailableTask(id); return }
throw error
}
if (verifyOnly && detail.value && fresh.version === detail.value.version && fresh.status === detail.value.status) return
if (!scope.current(ticket) || id !== selectedId.value || (detail.value && fresh.version < detail.value.version)) return
preserve = preserve || (!!detail.value && dirty.value)
const newlyApplied = detail.value?.status === 'review' && fresh.status === 'applied'
installDetail(fresh, preserve)
if (newlyApplied && !previewOnly.value) emit('applied', props.diagnosisId)
if (preserve && fresh.status === 'review') { clearAutosave(); saveState.value = 'conflict'; errorMessage.value = '服务端记录或版本已变化;已保留你的字段与日期修改,并取消所有选择。自动保存已暂停,请重新核对后重试保存草稿。' }
else if (preserve && newlyApplied) errorMessage.value = '任务已由其他人确认,已显示实际写入结果;本页未保存的修改未写入。'
}
async function refresh() {
if (!effectiveActive.value || !props.diagnosisId || pollRunning || busy.value) return
const ticket = scope.capture()
pollRunning = true; loading.value = true; clearTimer()
try {
const response = await followupAudioLists(props.diagnosisId, ticket.signal)
if (!scope.current(ticket)) return
tasks.value = response.items
const updated = tasks.value.find(task => task.id === selectedId.value)
if (updated && (!detail.value || updated.version > detail.value.version || (updated.version >= detail.value.version && updated.status !== detail.value.status) || updated.status === 'running')) {
await readDetail(updated.id, dirty.value)
} else if (!updated && selectedId.value && detail.value) {
// A limited list can omit older tasks; only an authoritative detail denial revokes them.
await readDetail(selectedId.value, false, true)
}
} catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
finally {
if (scope.current(ticket)) {
pollRunning = false; loading.value = false
if (effectiveActive.value) timer = setTimeout(() => { void refresh() }, 5000)
}
}
}
async function confirmLeave(): Promise<boolean> {
if (busy.value) { ElMessage.warning('正在上传或提交审核,请等待本次操作结束'); return false }
if (!dirty.value) return true
try {
await ElMessageBox.confirm('审核修改尚未保存。关闭诊单或切换录音将丢失这些修改,是否继续?', '保留审核修改', { type: 'warning', confirmButtonText: '继续离开', cancelButtonText: '返回保存' })
return true
} catch { return false }
}
async function openTask(id: number) {
if (!featureEnabled.value || id === selectedId.value || busy.value) return
const previous = scope.capture()
if (!await confirmLeave() || !scope.current(previous)) return
stop(); resetRoles(); selectedId.value = id; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; errorMessage.value = ''; detailSections.value = []
const ticket = scope.capture()
try { await readDetail(id) } catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
if (scope.current(ticket)) await refresh()
}
async function backToList() {
const ticket = scope.capture()
if (!await confirmLeave() || !scope.current(ticket)) return
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []; errorMessage.value = ''
await refresh()
}
function openUpload() {
if (!canUpload.value || busy.value || createUncertain.value) return
if (!file.value) uploadChannelRoles.value = 'unconfirmed'
uploadVisible.value = true
}
function closeUpload(done?: () => void) { if (uploading.value) return; uploadVisible.value = false; done?.() }
function statusType(status: string) {
if (status === 'failed' || status === 'needs_reconciliation') return 'danger'
if (status === 'applied') return 'success'
if (status === 'review') return 'warning'
return 'info'
}
function chooseFile(event: Event) {
const nextFile = (event.target as HTMLInputElement).files?.[0] || null
// Cancelling the picker or selecting the first file must not discard a role chosen earlier.
if (!nextFile) return
if (file.value && nextFile !== file.value) {
uploadChannelRoles.value = 'unconfirmed'
ElMessage.warning('录音已更换,请重新核对本次录音的声道角色')
}
file.value = nextFile; uploadProgress.value = 0; uploadStage.value = ''
}
async function submitUpload() {
if (busy.value || createUncertain.value) return
const problem = uploadIssue(file.value, recordedAt.value, modelKey.value, props.capabilities, props.viewOnly)
if (problem) { ElMessage.warning(problem); return }
const recording = file.value
if (!recording) return
const ticket = scope.capture()
uploading.value = true; uploadProgress.value = 0; errorMessage.value = ''; clearTimer()
let creating = false
try {
uploadStage.value = '正在创建私有上传会话'
const session = await followupAudioUploadSession({ diagnosis_id: props.diagnosisId, file_name: recording.name, total_bytes: recording.size }, ticket.signal)
if (!scope.current(ticket) || !canUpload.value) return
uploadStage.value = '正在上传录音分片'
const finished = await uploadChunks(recording, session.chunk_bytes,
(index, chunk) => followupAudioUploadChunk(session.upload_id, index, chunk, ticket.signal),
() => scope.current(ticket) && canUpload.value, percent => { uploadProgress.value = percent })
if (!finished) return
uploadStage.value = '正在校验录音时长和完整性'
await followupAudioUploadComplete(session.upload_id, ticket.signal)
if (!scope.current(ticket) || !canUpload.value) return
uploadStage.value = '正在创建分析任务'; creating = true; createUncertain.value = true
const result = await followupAudioCreate({ diagnosis_id: props.diagnosisId, upload_id: session.upload_id, recorded_at: recordedAt.value, model_key: modelKey.value, channel_roles: uploadChannelRoles.value }, ticket.signal)
if (!scope.current(ticket)) return
createUncertain.value = false; uploading.value = false; uploadVisible.value = false; file.value = null; if (fileInput.value) fileInput.value.value = ''
uploadStage.value = result.reused
? result.reuse_message || '同一录音已有任务,已打开原任务,不会重复调用模型'
: props.capabilities.preview_only ? '测试任务已创建,后台将识别与提炼;此任务不允许写入业务记录' : '任务已创建,后台将进行分析;审核前不会写入业务记录'
if (result.reused) ElMessage.warning(uploadStage.value)
await openTask(result.task_id)
} catch (error) {
if (scope.current(ticket)) { errorMessage.value = followupError(error); createUncertain.value = creating && !(error instanceof FollowupAudioError); uploadStage.value = '本次操作已停止,未自动重试' }
} finally { if (scope.current(ticket)) { uploading.value = false; await refresh() } }
}
async function handleReviewError(error: unknown) {
const ticket = scope.capture()
if (taskUnavailable(error) && detail.value) { forgetUnavailableTask(detail.value.id); return }
errorMessage.value = followupError(error)
const stale = error instanceof FollowupAudioError && error.code === 'FOLLOWUP_AUDIO_STALE_REVIEW'
if (stale || /STALE_REVIEW|版本|快照|已变化/.test(errorMessage.value)) {
clearAutosave(); saveState.value = 'conflict'
try { await readDetail(selectedId.value, true) } catch { if (scope.current(ticket)) errorMessage.value += ';刷新失败,当前编辑仍已保留,请稍后刷新。' }
}
}
function clearAutosave() { if (autosaveTimer !== undefined) clearTimeout(autosaveTimer); autosaveTimer = undefined }
function scheduleAutosave() {
clearAutosave()
if (hydrating || !effectiveActive.value || !canEditReview.value || !committedDirty.value || ['error', 'conflict'].includes(saveState.value)) return
if (mutation.value === 'save') return
saveState.value = 'pending'
autosaveTimer = setTimeout(() => { autosaveTimer = undefined; void saveDraft(true) }, 650)
}
// Merge only changes made after the request began. Server-owned evidence and hashes always win.
function mergeSaveResponse(sent: FollowupReviewItem[], saved: FollowupReviewItem[], local: FollowupReviewItem[]) {
const before = new Map(sent.map(item => [item.id, item]))
const latest = new Map(local.map(item => [item.id, item]))
return cloneReviewItems(saved).map(item => {
const previous = before.get(item.id), edit = latest.get(item.id)
if (!previous || !edit) return item
const serverRequiresReview = (item.needs_review && !previous.needs_review) || (previous.selected && !item.selected)
for (const key of ['values', 'record_date', 'record_time', 'time_period', 'target_id', 'selected', 'needs_review'] as const) {
if (serverRequiresReview && (key === 'selected' || key === 'needs_review')) continue
if (JSON.stringify(previous[key]) !== JSON.stringify(edit[key])) Object.assign(item, { [key]: edit[key] })
}
return item
})
}
async function saveDraft(automatic = false): Promise<void> {
if (savePromise) return savePromise
if (!canEditReview.value || !detail.value || busy.value || !effectiveActive.value) return
if (!automatic && reviewRef.value?.hasUnsavedChanges()) { ElMessage.warning('请先保存或取消正在核对的单项修改'); return }
if (automatic && (!committedDirty.value || ['error', 'conflict'].includes(saveState.value))) return
clearAutosave()
const ticket = scope.capture(), taskId = detail.value.id, diagnosisId = props.diagnosisId
const current = () => scope.current(ticket) && selectedId.value === taskId && props.diagnosisId === diagnosisId
const changedRoles = roleDirty.value, sentRoles = channelRoles.value
const sentItems = cloneReviewItems(reviewItems.value), version = detail.value.version
mutation.value = 'save'; saveState.value = 'saving'; errorMessage.value = ''; clearTimer()
const operation = (async () => {
try {
const saved = await followupAudioSaveDraft({ id: taskId, version, items: sentItems, ...(changedRoles && hasStereo.value ? { channel_roles: sentRoles } : {}) }, ticket.signal)
if (!current()) return
if (detail.value && saved.version < detail.value.version) {
saveState.value = 'conflict'; errorMessage.value = '服务端已有更新版本;自动保存已暂停,请核对当前记录后重试保存。'; return
}
if (saved.review_refreshed) {
const latestRoles = channelRoles.value
installDetail(saved, true, false)
if (latestRoles !== sentRoles) { hydrating = true; channelRoles.value = latestRoles; hydrating = false }
saveState.value = 'conflict'
errorMessage.value = '业务记录已变化,版本已刷新;当前编辑已保留,全部选择已取消。自动保存已暂停,请重新核对后重试保存草稿。'
} else {
const latestRoles = channelRoles.value
const merged = changedRoles ? rebaseReviewItems(reviewItems.value, saved.items) : mergeSaveResponse(sentItems, saved.items, reviewItems.value)
hydrating = true
try {
detail.value = saved; snapshot.value = JSON.stringify(saved.items)
roleSnapshot.value = normalizedChannelRoles(saved.channel_roles)
channelRoles.value = latestRoles === sentRoles ? roleSnapshot.value : latestRoles
if (JSON.stringify(merged) !== JSON.stringify(reviewItems.value)) reviewItems.value = merged
} finally { hydrating = false }
editingRoles.value = roleDirty.value
saveState.value = committedDirty.value ? 'pending' : 'saved'
if (!committedDirty.value) persistedRevision.value++
if (!automatic) ElMessage.success(changedRoles ? '角色标注已保存,全部建议须重新核对;不会自动重新提炼' : previewOnly.value ? '测试审核草稿已保存,不会写入病历' : '审核草稿已保存,尚未写入病历')
}
} catch (error) {
if (current()) {
saveState.value = 'error'
await handleReviewError(error)
if (current() && !['conflict'].includes(saveState.value)) errorMessage.value += ';自动保存已暂停,修改仍保留,请重试保存草稿。'
}
} finally {
if (current()) {
mutation.value = ''; savePromise = null
scheduleAutosave()
await refresh()
}
}
})()
savePromise = operation
return operation
}
async function applySelected() {
if (!canApplyReview.value || !detail.value || busy.value || !selectedCount.value) return
if (reviewRef.value?.hasUnsavedChanges()) { ElMessage.warning('请先保存或取消正在核对的单项修改'); return }
if (props.basicDirty || (props.beforeApply && !props.beforeApply())) { ElMessage.warning('请先保存病历表单,当前修改不会被覆盖'); return }
if (applyIssue.value) { ElMessage.warning(applyIssue.value); return }
const ticket = scope.capture()
try { await ElMessageBox.confirm(`将一次性采纳 ${selectedCount.value} 项;任一项冲突则整批不写入。确认已核对原话、日期和时间?`, '确认采纳', { type: 'warning', confirmButtonText: '全部采纳', cancelButtonText: '返回核对' }) } catch { return }
if (!scope.current(ticket) || !canApplyReview.value || !selectedCount.value || props.basicDirty || (props.beforeApply && !props.beforeApply()) || !detail.value) return
if (applyIssue.value) { ElMessage.warning(applyIssue.value); return }
const diagnosisId = props.diagnosisId
mutation.value = 'apply'; errorMessage.value = ''; clearTimer()
try {
await followupAudioApply({ id: detail.value.id, version: detail.value.version, items: cloneReviewItems(reviewItems.value) }, ticket.signal)
if (!scope.current(ticket) || !canApplyReview.value) return
detail.value = { ...detail.value, status: 'applied' }; snapshot.value = JSON.stringify(reviewItems.value)
ElMessage.success('所选记录已全部采纳'); emit('applied', diagnosisId)
await readDetail(selectedId.value)
} catch (error) { if (scope.current(ticket)) await handleReviewError(error) }
finally { if (scope.current(ticket)) { mutation.value = ''; await refresh() } }
}
function extractionRoleLabel(roles: FollowupChannelRoles): string {
return roles === 'left_service' ? '左客服 / 右患者或家属' : roles === 'right_service' ? '右客服 / 左患者或家属' : '角色未确认'
}
async function reextractWithRoles() {
const roles = reextractTarget.value
if (!canReextract.value || !detail.value || busy.value || roles === 'unconfirmed' || roles === extractionRoles.value) return
if (dirty.value) { ElMessage.warning('请先完成或取消当前审核修改,等待草稿保存后再重新提炼'); return }
const ticket = scope.capture(), id = detail.value.id, version = detail.value.version, diagnosisId = props.diagnosisId
const current = () => scope.current(ticket) && diagnosisId === props.diagnosisId && selectedId.value === id
clearAutosave(); clearTimer(); mutation.value = 'reextract'; errorMessage.value = ''
let confirmed = false
try {
await ElMessageBox.confirm(`确认已回听并核实角色为“${extractionRoleLabel(roles)}”?将保留旧版结果,复用已完成的转写重新提炼,不重复语音识别;新建议须重新审核,不自动写入病例。`, '确认角色并重新提炼', { type: 'warning', confirmButtonText: '角色正确,开始重新提炼', cancelButtonText: '返回回听' })
if (!current() || !canReextract.value || dirty.value) return
confirmed = true
const fresh = await followupAudioReextract({ id, version, channel_roles: roles }, ticket.signal)
if (!current()) return
installDetail(fresh, false); saveState.value = 'idle'; editingRoles.value = false
ElMessage.success('已提交重新提炼,将复用原转写;新结果仍需审核,不自动写入病例')
} catch (error) { if (confirmed && current()) await handleReviewError(error) }
finally { if (current()) { mutation.value = ''; scheduleAutosave(); await refresh() } }
}
function canDeleteTask(task: FollowupTaskSummary): boolean {
return !props.viewOnly && featureEnabled.value && task.can_delete === true && ['review', 'failed'].includes(task.status)
}
async function deleteRecording(task: FollowupTaskSummary) {
if (busy.value || !canDeleteTask(task)) return
const ticket = scope.capture(), diagnosisId = props.diagnosisId, id = task.id, version = task.version
const current = () => scope.current(ticket) && diagnosisId === props.diagnosisId
clearAutosave(); clearTimer(); mutation.value = 'delete'; errorMessage.value = ''
let confirmed = false
try {
await ElMessageBox.confirm('删除后,该录音任务及审核草稿将从列表移除,未保存修改会丢弃;不删除或回滚病例。原录音和转写仍按原保留期限清理。重新上传同一文件将创建新的分析任务。确认删除?', '删除录音任务', { type: 'warning', confirmButtonText: '确认删除', cancelButtonText: '保留录音' })
if (!current() || !canDeleteTask(task)) return
confirmed = true
await followupAudioDelete({ id, version }, ticket.signal)
if (!current()) return
// Fence pending playback, autosaves and reads; deletion never revives a stale draft.
if (selectedId.value === id) {
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []
}
tasks.value = tasks.value.filter(row => row.id !== id)
errorMessage.value = ''
ElMessage.success('录音任务已删除,未修改病例。原资料按保留策略清理。')
await refresh()
} catch (error) {
if (confirmed && current()) errorMessage.value = followupError(error)
} finally {
if (current()) { mutation.value = ''; scheduleAutosave(); await refresh() }
}
}
async function retryTask() {
if (!detail.value?.can_retry || detail.value.status !== 'failed' || !canUpload.value || busy.value) return
const ticket = scope.capture()
try { await ElMessageBox.confirm('仅对服务端已确认失败、允许重试的任务重新分析。确认继续?', '确认重试', { type: 'warning' }) } catch { return }
if (!scope.current(ticket) || !detail.value?.can_retry || detail.value.status !== 'failed' || !canUpload.value) return
mutation.value = 'retry'; clearTimer()
try { await followupAudioRetry(detail.value.id, ticket.signal); if (scope.current(ticket)) await readDetail(selectedId.value) }
catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
finally { if (scope.current(ticket)) { mutation.value = ''; await refresh() } }
}
async function loadDialogue(milliseconds: number) { await loadAudio(dialoguePlaybackStart(milliseconds)) }
async function reloadAudio() { releaseAudio(); await loadAudio() }
async function playChannel(channel: FollowupPlaybackChannel) { await loadAudio((audioElement.value?.currentTime || 0) * 1000, channel === 'original' ? undefined : channel) }
async function loadAudio(milliseconds?: number, channel?: FollowupAudioChannel) {
if (!featureEnabled.value || !detail.value?.audio_available) return
const operation = ++playbackRequest
playbackError.value = ''
if (channel !== undefined && (!hasStereo.value || (channel !== 0 && channel !== 1))) {
releaseAudio(); playbackError.value = '未取得可验证的双声道片段,无法隔离声道;请使用原音播放。'; return
}
const ticket = scope.capture(); const id = detail.value.id
if (!audioUrl.value) {
const requestId = ++audioRequest; audioLoading.value = true
try {
const blob = await followupAudioBlob(id, ticket.signal)
if (!scope.current(ticket) || requestId !== audioRequest || id !== selectedId.value) return
audioUrl.value = URL.createObjectURL(blob)
} catch (error) { if (scope.current(ticket) && requestId === audioRequest) errorMessage.value = followupError(error) }
finally { if (scope.current(ticket) && requestId === audioRequest) audioLoading.value = false }
}
await nextTick()
if (!scope.current(ticket) || operation !== playbackRequest || id !== selectedId.value || !audioUrl.value || !audioElement.value) return
const element = audioElement.value
if (playbackElement !== element) { playback?.dispose(); playback = createFollowupAudioPlayback(element); playbackElement = element }
const routing = playback
channelLoading.value = true
try {
if (!routing || !await routing.select(channel ?? 'original')) return
if (!scope.current(ticket) || operation !== playbackRequest || id !== selectedId.value) return
playbackChannel.value = channel ?? 'original'
if (typeof milliseconds !== 'number' || !Number.isFinite(milliseconds)) return
element.currentTime = Math.max(0, milliseconds / 1000)
try { await element.play() } catch { if (scope.current(ticket) && operation === playbackRequest) playbackError.value = '播放未启动,请使用播放器控件继续。' }
} catch (error) {
if (scope.current(ticket) && operation === playbackRequest) { playbackChannel.value = 'original'; playbackError.value = followupError(error) }
} finally { if (scope.current(ticket) && operation === playbackRequest) channelLoading.value = false }
}
function formatExpiry(value: number | string) {
if (!value) return '由保留策略控制'
const date = typeof value === 'number' || /^\d+$/.test(value) ? new Date(Number(value) * 1000) : new Date(value)
return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
}
function onVisibility() { documentVisible.value = document.visibilityState !== 'hidden' }
watch([() => props.diagnosisId, effectiveActive, () => !!props.capabilities.preview_only], ([id, active]) => {
stop()
if (id !== lastDiagnosis) {
resetRoles(); lastDiagnosis = id; selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'
tasks.value = []; file.value = null; recordedAt.value = ''; uploadChannelRoles.value = 'unconfirmed'; uploadVisible.value = false; detailSections.value = []; helpVisible.value = false; errorMessage.value = ''; uploadStage.value = ''; createUncertain.value = false
}
if (active) { void refresh(); scheduleAutosave() }
}, { immediate: true })
watch([() => JSON.stringify(reviewItems.value), channelRoles], () => { if (!hydrating) scheduleAutosave() }, { flush: 'sync' })
watch(() => props.capabilities.models, models => {
if (!models.some(model => model.value === modelKey.value)) modelKey.value = models[0]?.value || ''
})
onMounted(() => document.addEventListener('visibilitychange', onVisibility))
onBeforeUnmount(() => { stop(); document.removeEventListener('visibilitychange', onVisibility) })
defineExpose({ confirmLeave, refresh, hasUnsavedChanges: () => dirty.value })
</script>
<style scoped>
.followup-panel { display: grid; gap: 12px; min-width: 0; color: var(--el-text-color-primary); font-size: 14px; }
.panel-toolbar, .toolbar-actions, .detail-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-width: 0; }
.toolbar-actions { justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
.toolbar-actions :deep(.el-button + .el-button) { margin-left: 0; }
h3 { margin: 0; font-size: 14px; font-weight: 600; }
.toolbar-title h3 span { margin-left: 5px; font-weight: 400; color: var(--el-text-color-secondary); }
.help-box { background: #fff; border: 1px solid #e2e8f0; border-radius: 10px; padding: 10px 14px; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.7; }
.help-box p { margin: 3px 0; }
.task-list, .task-detail { min-width: 0; max-width: 100%; border: 1px solid #e2e8f0; border-radius: 10px; background: #fff; overflow: hidden; }
.task-list { padding: 4px 12px; }
.task-list :deep(.el-table) { --el-table-header-bg-color: #f8fafc; }
.task-list :deep(.el-table .cell) { line-height: 1.5; }
.filename-button { max-width: 100%; height: auto; text-align: left; white-space: normal; word-break: break-word; line-height: 1.6; }
.filename-button :deep(span) { overflow-wrap: anywhere; }
.task-time, .recording-title > span { display: block; color: var(--el-text-color-secondary); font-size: 12px; margin-top: 3px; }
.task-detail { padding: 16px; display: grid; gap: 14px; overflow: visible; }
.detail-heading { align-items: flex-start; }
.recording-title { min-width: 0; }
.recording-title h3 { overflow-wrap: anywhere; line-height: 1.6; }
.role-reextract { padding: 12px; border: 1px solid var(--el-color-warning-light-5); background: var(--el-color-warning-light-9); border-radius: 6px; display: grid; gap: 8px; }
.role-reextract p { margin: 0; line-height: 1.6; }
.role-reextract blockquote { margin: 0; padding: 8px; background: var(--el-bg-color); white-space: pre-wrap; overflow-wrap: anywhere; }
.role-reextract :deep(.el-button) { justify-self: start; }
.detail-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.detail-heading :deep(.el-tag) { flex-shrink: 0; }
.detail-loading { padding: 32px; text-align: center; color: var(--el-text-color-secondary); }
.processing-state, .applied-note { margin: 0; color: var(--el-text-color-secondary); font-size: 13px; }
.retry-button { justify-self: start; }
.summary-box { padding-bottom: 12px; border-bottom: 1px solid #e2e8f0; }
.summary-box > p { margin: 0 0 10px; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; }
.summary-counts { display: flex; gap: 20px; color: var(--el-text-color-secondary); font-size: 12px; }
.summary-counts strong { color: var(--el-text-color-primary); font-weight: 600; }
.channel-role-box { display: grid; gap: 6px; font-size: 12px; }
.role-summary { display: flex; align-items: center; gap: 12px; }
.channel-role-box label { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
.channel-role-box :deep(.el-select) { width: 260px; max-width: 100%; }
.channel-playback { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin: 8px 0; }
.channel-playback :deep(.el-button + .el-button) { margin-left: 0; }
.transcript-segments { max-height: 320px; overflow-y: auto; margin-top: 12px; }
.transcript-segment { padding: 10px 0; border-bottom: 1px solid #e2e8f0; }
.segment-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--el-text-color-secondary); font-size: 12px; }
.transcript-segment pre { margin: 5px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font-family: inherit; }
.dialogue-sides { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr)); gap: 10px; margin-top: 8px; }
.dialogue-side { padding: 10px; background: var(--el-fill-color-light); border-radius: 6px; min-width: 0; }
.dialogue-side strong { font-size: 12px; color: var(--el-text-color-secondary); }
.original-collapse { --el-collapse-border-color: #e2e8f0; border-top: 0; }
.original-collapse :deep(.el-collapse-item__header) { height: 38px; font-size: 13px; color: var(--el-text-color-regular); }
.original-collapse :deep(.el-collapse-item__content) { padding-bottom: 10px; }
.audio-player { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.audio-player audio { width: 100%; max-width: 440px; height: 36px; }
.transcript-text { max-height: 280px; overflow-y: auto; margin: 12px 0 0; padding: 12px; background: #f8fafc; border-radius: 6px; white-space: pre-wrap; overflow-wrap: anywhere; font-family: inherit; }
.review-actions { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px; align-items: center; padding-top: 2px; }
.selection-summary { display: grid; gap: 3px; font-size: 13px; }
.selection-summary span { color: var(--el-text-color-secondary); font-size: 12px; }
.action-buttons { display: flex; gap: 8px; }
.action-buttons :deep(.el-button + .el-button) { margin-left: 0; }
.review-error { color: var(--el-color-danger); width: 100%; margin: 0; font-size: 12px; }
.muted, .upload-stage { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; margin: 0; }
.upload-stage { margin: 10px 0; color: var(--el-text-color-regular); }
.upload-form { min-width: 0; }
.upload-form input { max-width: 100%; }
.upload-form small { display: block; color: var(--el-text-color-secondary); line-height: 1.5; margin-top: 6px; }
.upload-form :deep(.el-date-editor), .upload-form :deep(.el-select) { width: 100%; }
@media (max-width: 640px) {
.panel-toolbar { align-items: flex-start; flex-wrap: wrap; gap: 8px; }
.toolbar-actions { gap: 6px; }
.task-list { padding: 0 4px; }
.task-detail { padding: 12px; gap: 12px; }
.detail-heading { flex-wrap: wrap; gap: 6px; }
.review-actions { align-items: flex-start; }
.action-buttons { margin-left: auto; }
}
</style>
@@ -0,0 +1,273 @@
<template>
<section class="followup-review" aria-label="回访录音人工审核">
<el-tabs v-model="group" class="review-tabs" aria-label="提炼结果分类">
<el-tab-pane :label="`全部 ${counts.all}`" name="all" />
<el-tab-pane :label="`诊单资料 ${counts.diagnosis}`" name="diagnosis" />
<el-tab-pane :label="`日常记录 ${counts.daily}`" name="daily" />
<el-tab-pane :label="`待核实 ${counts.pending + (uncertainties?.length || 0)}`" name="pending" />
</el-tabs>
<div class="review-caption"><span>{{ applied ? '审核结果' : '提炼结果' }} · {{ visibleItems.length }} 项</span><span v-if="!applied">跨分类已选 {{ counts.selected }} 项</span></div>
<p v-if="!canDaily && counts.daily" class="permission-note">日常记录仅供查看,当前账号没有编辑权限。</p>
<div class="review-table">
<el-table :data="visibleItems" max-height="360" row-key="id" size="small" table-layout="fixed" :empty-text="items.length ? '此分类暂无内容' : '暂无结构化结果,可查看录音原文'" aria-label="回访提炼结果">
<el-table-column v-if="!applied" label="采纳" width="50" align="center">
<template #default="{ row }"><el-checkbox :model-value="row.selected" :disabled="disabled || (!row.selected && selectionBlocked(row))" :aria-label="`采纳${itemTitle(row)}`" @update:model-value="(value: boolean | string | number) => toggleSelection(row, !!value)" /></template>
</el-table-column>
<el-table-column label="字段 / 内容" min-width="210">
<template #default="{ row }">
<div v-for="field in itemFields(row).slice(0, 2)" :key="field.key" class="result-line"><span>{{ field.label }}:</span>{{ fieldText(row.values[field.key], field) }}</div>
<span v-if="!itemFields(row).length" class="muted">暂无有效字段</span>
<div class="item-meta">{{ itemKindLabel(row) }}<span v-if="itemFields(row).length > 2"> · 共 {{ itemFields(row).length }} 个字段</span><span v-if="row.target_id"> · 更新已有记录</span></div>
<div v-if="row.kind !== 'diagnosis'" class="item-meta mobile-event-time">{{ row.record_date || '日期待核实' }} · {{ reviewTimeValue(row.record_time) || row.time_period || '时间待核实' }}{{ row.time_estimated ? '(推定)' : '' }}</div>
</template>
</el-table-column>
<el-table-column label="日期 / 时段" width="130">
<template #default="{ row }"><span>{{ row.kind === 'diagnosis' ? '—' : row.record_date || '待补充日期' }}</span><div v-if="row.kind !== 'diagnosis'" class="item-meta">{{ reviewTimeValue(row.record_time) || row.time_period || '未提及时间' }}{{ row.time_estimated ? '(推定)' : '' }}</div></template>
</el-table-column>
<el-table-column label="状态" width="90">
<template #default="{ row }"><el-tag size="small" :type="itemStatus(row).type">{{ itemStatus(row).label }}</el-tag></template>
</el-table-column>
<el-table-column label="操作" width="60" align="right" fixed="right">
<template #default="{ row }"><el-button link type="primary" @click="openReview(row.id)">{{ applied || disabled ? '查看' : '核对' }}</el-button></template>
</el-table-column>
</el-table>
</div>
<section v-if="(group === 'pending' || !items.length) && uncertainties?.length" class="uncertainty-list" aria-label="原文待核实信息">
<strong>本次未能确认的信息与原因</strong>
<ul><li v-for="(value, index) in uncertainties" :key="index">{{ uncertaintyText(value) }}</li></ul>
</section>
<section ref="reviewWorkspace" class="review-workspace" tabindex="-1" aria-label="同页核对与回听">
<div class="review-player"><slot name="player" /></div>
<p v-if="navigationNotice" class="editor-notice" role="status">{{ navigationNotice }}</p>
<div v-if="editor" class="inline-editor-heading"><strong>{{ applied || disabled ? '查看审核结果' : '核对提炼内容' }} · {{ editorPosition }} / {{ items.length }}</strong><el-button link @click="cancelReview()">{{ editorDirty ? '取消本项修改' : '收起核对' }}</el-button></div>
<section v-if="editor" class="review-editor">
<div class="editor-heading"><strong>{{ followupKindLabels[editor.kind] }}</strong><el-tag size="small" :type="itemStatus(editor).type">{{ itemStatus(editor).label }}</el-tag></div>
<p v-if="editorNotice" class="editor-notice" role="status">{{ editorNotice }}</p>
<div class="evidence">
<div class="evidence-title">录音原话</div>
<blockquote v-for="(quote, index) in editor.evidence" :key="index"><div v-if="quote.channel === 0 || quote.channel === 1" class="muted">{{ followupChannelLabel(quote.channel, channelRoles) }}</div><span>{{ quote.text }}</span><el-button v-if="evidencePlaybackLabel(quote)" link type="primary" @click="seekEvidence(quote)">{{ evidencePlaybackLabel(quote) }}</el-button></blockquote>
<p v-if="editor.evidence.some(quote => quote.position_type === 'segment')" class="muted">回听位置为转写片段范围,不是原话的逐字时间戳;默认回听双方对话,请结合原始录音核对。</p>
<p v-if="!editor.evidence.length" class="muted">未提供原话证据,请人工核实。</p>
<p v-if="editor.date_text || editor.time_text" class="muted">时间原话:{{ editor.date_text || '未提及日期' }} · {{ editor.time_text || '未提及时间' }}</p>
</div>
<div v-if="editor.conflict || editor.possible_duplicate || editor.time_estimated" class="review-flags"><span v-if="editor.conflict">与已有值冲突</span><span v-if="editor.possible_duplicate">可能存在重复记录</span><span v-if="editor.time_estimated">时间由时段推定</span></div>
<template v-if="editor.kind !== 'diagnosis'">
<div v-if="disabled || applied" class="readonly-event"><span>{{ editor.record_date || '未记录日期' }} · {{ reviewTimeValue(editor.record_time) || editor.time_period || '未记录时间' }}</span><span>{{ editor.target_id ? `更新记录 #${editor.target_id}` : '新增独立记录' }}</span></div>
<div v-else class="event-time">
<label class="target-field">写入目标<el-select :model-value="editor.target_id || 0" @update:model-value="(value: number) => chooseTarget(value)"><el-option label="新增独立记录(不覆盖已有行)" :value="0" /><el-option v-for="candidate in editorCandidates" :key="candidate.id" :value="candidate.id" :disabled="!!candidate.delete_time" :label="candidateLabel(editor, candidate)" /></el-select></label>
<label>记录日期<el-date-picker :model-value="editor.record_date" type="date" value-format="YYYY-MM-DD" placeholder="请核实日期" @update:model-value="(value: string | null) => patchEditor({ record_date: value || null, target_id: null })" /></label>
<label>记录时间<el-time-picker :model-value="reviewTimeValue(editor.record_time)" value-format="HH:mm" format="HH:mm" placeholder="未提及可留空" @update:model-value="(value: string | null) => patchEditor({ record_time: value || null })" /></label>
<label>原始时段<el-input :model-value="editor.time_period || ''" placeholder="如早晨、餐后" @update:model-value="(value: string) => patchEditor({ time_period: value || null })" /></label>
</div>
<p v-if="targetChanged && !applied" class="target-hint" role="status">日期或目标已更改。保存本项后将自动同步草稿并刷新目标当前值,请依据新值重新核对。</p>
</template>
<div class="field-grid field-grid--header"><span>字段</span><span>{{ applied ? '写入前值' : targetChanged ? '旧目标值(待刷新)' : '当前值' }}</span><span>{{ applied || disabled ? '审核值' : '拟采纳值' }}</span></div>
<div v-for="field in itemFields(editor)" :key="field.key" class="field-grid">
<div class="field-label">{{ field.label }}<small v-if="field.readonly">只读</small></div>
<div class="current-value">{{ fieldText(editor.current_values[field.key], field) }}</div>
<div class="suggested-value"><FollowupAudioField :field="field" :model-value="editor.values[field.key]" :readonly="disabled || applied || field.readonly" @update:model-value="value => setValue(field.key, value)" /><el-button v-if="!disabled && !applied" link type="danger" :disabled="Object.keys(editor.values).length <= 1" @click="removeField(field.key)">移除</el-button></div>
</div>
<p v-if="!disabled && !applied" class="muted">仅可更正或移除本项提议字段,不采纳整项请取消勾选;新增内容请返回原诊单编辑人工补录。</p>
<el-checkbox v-if="!disabled && !applied" :model-value="!editor.needs_review" class="review-confirm" @update:model-value="(value: boolean | string | number) => confirmReview(!!value)">我已核对原话、冲突 / 重复及日期时间,确认本项内容</el-checkbox>
<p v-if="editorIssue && !disabled && !applied" class="review-error" role="status">{{ editorIssue }}</p>
</section>
<div v-if="editor && !disabled && !applied" class="editor-footer">
<span class="draft-hint" role="status">{{ saveState === 'saving' || saveState === 'pending' ? '审核草稿同步中,不写入病例' : saveState === 'error' || saveState === 'conflict' ? '草稿同步需处理,请查看下方提示' : '核对结果自动保存为草稿,最终确认后才写入病例' }}</span>
<el-button @click="skipAndNext">暂不采纳并下一项</el-button>
<el-button :disabled="!editorDirty" @click="saveReview(false)">保存本项修改</el-button>
<el-button type="primary" :disabled="!!editorIssue || targetChanged" @click="saveReview(true, true)">{{ nextReviewId ? '采纳并下一项' : '完成核对并选中' }}</el-button>
</div>
</section>
</section>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import type { FollowupAudioChannel, FollowupChannelRoles, FollowupField, FollowupFields, FollowupReviewItem, FollowupValue } from '@/api/followupAudio'
import FollowupAudioField from './FollowupAudioField.vue'
import { cloneReviewItems, evidencePlaybackLabel, fieldText, followupChannelLabel, followupKindLabels, hasEditableReviewFields, reviewCounts, reviewFieldIssue, reviewIssue, reviewPending, reviewTimeValue } from './followupAudioState'
const props = defineProps<{ items: FollowupReviewItem[]; fields: FollowupFields; disabled: boolean; canDaily: boolean; applied?: boolean; uncertainties?: unknown[]; snapshotItems?: FollowupReviewItem[]; channelRoles?: FollowupChannelRoles; saveState?: string; persistedRevision?: number }>()
const emit = defineEmits<{ (event: 'update:items', items: FollowupReviewItem[]): void; (event: 'seek', milliseconds: number, channel?: FollowupAudioChannel): void; (event: 'saved-next'): void }>()
type Group = 'all' | 'diagnosis' | 'daily' | 'pending'
type Editable = Partial<Pick<FollowupReviewItem, 'values' | 'record_date' | 'record_time' | 'time_period' | 'selected' | 'target_id' | 'needs_review'>>
const group = ref<Group>('all')
const editor = ref<FollowupReviewItem | null>(null)
const editorSource = ref('')
const editorNotice = ref('')
const navigationNotice = ref('')
const reviewWorkspace = ref<HTMLElement | null>(null)
const editorPosition = computed(() => props.items.findIndex(item => item.id === editor.value?.id) + 1)
const nextReviewId = computed(() => {
const index = visibleItems.value.findIndex(item => item.id === editor.value?.id)
return index < 0 ? null : visibleItems.value.slice(index + 1).find(item => !item.selected && !selectionBlocked(item))?.id || null
})
const counts = computed(() => reviewCounts(props.items, props.fields, props.canDaily))
const visibleItems = computed(() => props.items.filter(item => group.value === 'all' || (group.value === 'diagnosis' && item.kind === 'diagnosis') || (group.value === 'daily' && item.kind !== 'diagnosis') || (group.value === 'pending' && reviewPending(item, props.fields, props.canDaily))))
const editorDirty = computed(() => !!editor.value && JSON.stringify(editor.value) !== editorSource.value)
const targetChanged = computed(() => {
if (!editor.value || !editorSource.value) return false
const source: FollowupReviewItem = props.snapshotItems?.find(item => item.id === editor.value?.id) || JSON.parse(editorSource.value)
return editor.value.target_id !== source.target_id || editor.value.record_date !== source.record_date
})
const editorCandidates = computed(() => {
if (!editor.value || !editorSource.value) return []
const source: FollowupReviewItem = props.snapshotItems?.find(item => item.id === editor.value?.id) || JSON.parse(editorSource.value)
return editor.value.record_date === source.record_date ? editor.value.candidates || [] : []
})
const editorIssue = computed(() => editor.value ? reviewFieldIssue({ ...editor.value, selected: true }, props.fields) || reviewIssue({ ...editor.value, selected: true }, props.canDaily) : '')
function patch(id: string, update: Editable) { emit('update:items', props.items.map(item => item.id === id ? { ...item, ...update } : item)) }
function itemFields(item: FollowupReviewItem): FollowupField[] { return Object.keys(item.values).map(key => (props.fields[item.kind] || []).find(field => field.key === key) || { key, label: key, type: 'text', readonly: true }) }
function itemKindLabel(item: FollowupReviewItem) { return followupKindLabels[item.kind] }
function itemTitle(item: FollowupReviewItem) { return itemFields(item).map(field => field.label).join('、') || followupKindLabels[item.kind] }
function selectionBlocked(item: FollowupReviewItem) { return props.disabled || !!props.applied || !hasEditableReviewFields(item, props.fields) || (item.kind !== 'diagnosis' && !props.canDaily) || !!reviewFieldIssue({ ...item, selected: true }, props.fields) }
function toggleSelection(item: FollowupReviewItem, selected: boolean) {
if (props.disabled || props.applied) return
if (!selected) { patch(item.id, { selected: false }); return }
if (selectionBlocked(item)) return
if (reviewPending(item, props.fields, props.canDaily)) { openReview(item.id); return }
patch(item.id, { selected: true })
}
function itemStatus(item: FollowupReviewItem): { label: string; type: 'success' | 'info' | 'warning' } {
if (props.applied) return { label: item.selected ? '已写入' : '未采纳', type: item.selected ? 'success' : 'info' }
if (!hasEditableReviewFields(item, props.fields)) return { label: '只读字段', type: 'info' }
if (reviewPending(item, props.fields, props.canDaily)) return { label: '待核实', type: 'warning' }
return { label: item.selected ? '已选择' : '已核对', type: item.selected ? 'success' : 'info' }
}
function openReview(id: string) {
if (editor.value?.id === id && editorDirty.value && !props.applied) {
void nextTick(() => { reviewWorkspace.value?.scrollIntoView({ block: 'start' }); reviewWorkspace.value?.focus({ preventScroll: true }) })
return
}
if (editor.value && editor.value.id !== id && editorDirty.value && !props.applied) {
editorNotice.value = '当前项有未保存修改,请先保存或取消本项修改,再核对其他项。'
return
}
const item = props.items.find(candidate => candidate.id === id)
if (!item) return
editor.value = cloneReviewItems([item])[0]; editorSource.value = JSON.stringify(editor.value); editorNotice.value = ''; navigationNotice.value = ''
void nextTick(() => { reviewWorkspace.value?.scrollIntoView({ block: 'start' }); reviewWorkspace.value?.focus({ preventScroll: true }) })
}
function cancelReview(done?: () => void) { editor.value = null; editorSource.value = ''; editorNotice.value = ''; done?.() }
function patchEditor(update: Editable) {
if (!editor.value || props.disabled || props.applied) return
// Detail/snapshot items are editable drafts, not the server-owned original proposal.
if (update.values && Object.keys(update.values).some(key => !Object.prototype.hasOwnProperty.call(editor.value?.values, key))) return
editor.value = { ...editor.value, ...update, selected: false, needs_review: true }
}
function setValue(key: string, value: FollowupValue) {
if (!editor.value || !Object.prototype.hasOwnProperty.call(editor.value.values, key)
|| !(props.fields[editor.value.kind] || []).some(field => field.key === key && !field.readonly)) return
patchEditor({ values: { ...editor.value.values, [key]: value } })
}
function removeField(key: string) { if (!editor.value || Object.keys(editor.value.values).length <= 1) return; const values = { ...editor.value.values }; delete values[key]; patchEditor({ values }) }
function chooseTarget(id: number) {
if (!editor.value || (id && !editorCandidates.value.some(candidate => candidate.id === id && !candidate.delete_time))) return
patchEditor({ target_id: id || null })
}
function confirmReview(confirmed: boolean) {
if (!editor.value || props.disabled || props.applied) return
editor.value = { ...editor.value, needs_review: !confirmed, selected: confirmed ? editor.value.selected : false }
}
function saveReview(select: boolean, advance = false) {
if (!editor.value || props.disabled || props.applied || (select && (editorIssue.value || targetChanged.value))) return
const item = editor.value
const nextId = advance ? nextReviewId.value : null
patch(item.id, { values: { ...item.values }, record_date: item.record_date, record_time: item.record_time, time_period: item.time_period, target_id: item.target_id, selected: select || (!editorIssue.value && !targetChanged.value && item.selected), needs_review: targetChanged.value || item.needs_review })
cancelReview()
emit('saved-next')
if (nextId) openReview(nextId)
else if (advance) navigationNotice.value = '当前列表已核对至末项;可切换分类继续,或确认写入已选内容。'
}
function skipAndNext() {
if (!editor.value || props.disabled || props.applied) return
if (editorDirty.value) { editorNotice.value = '当前项有未保存修改,请先保存或取消修改后再跳过。'; return }
const nextId = nextReviewId.value
patch(editor.value.id, { selected: false })
cancelReview(); emit('saved-next')
if (nextId) openReview(nextId)
else navigationNotice.value = '本项暂不采纳,未写入病例;可切换分类继续核对。'
}
function candidateLabel(item: FollowupReviewItem, candidate: NonNullable<FollowupReviewItem['candidates']>[number]) {
const preview = (props.fields[item.kind] || []).filter(field => Object.prototype.hasOwnProperty.call(candidate.values, field.key)).slice(0, 2).map(field => `${field.label} ${fieldText(candidate.values[field.key], field)}`).join(',')
return `#${candidate.id} · ${candidate.record_time || candidate.time_period || '时间未记录'}${candidate.time_estimated ? '(推定)' : ''}${preview ? ` · ${preview}` : ''}`
}
function seekEvidence(quote: FollowupReviewItem['evidence'][number]) {
if (!evidencePlaybackLabel(quote) || typeof quote.start_ms !== 'number') return
emit('seek', quote.start_ms)
}
function uncertaintyText(value: unknown) { return typeof value === 'string' ? value : JSON.stringify(value) }
watch(() => props.items.find(item => item.id === editor.value?.id), fresh => {
if (!editor.value) return
if (!fresh) { cancelReview(); return }
const current = JSON.stringify(fresh)
if (current === editorSource.value) return
const edited = editor.value
editor.value = editorDirty.value && !props.applied ? { ...cloneReviewItems([fresh])[0], values: { ...edited.values }, record_date: edited.record_date, record_time: edited.record_time, time_period: edited.time_period, target_id: edited.target_id, selected: false, needs_review: true } : cloneReviewItems([fresh])[0]
editorSource.value = current
editorNotice.value = '任务数据已更新,当前编辑已保留;请重新核对后选择。'
}, { deep: true })
watch(() => props.applied, applied => { if (applied && editor.value) openReview(editor.value.id) })
defineExpose({ hasUnsavedChanges: () => editorDirty.value })
</script>
<style scoped>
.followup-review, .review-table { min-width: 0; max-width: 100%; }
.review-tabs :deep(.el-tabs__header) { margin: 0 0 8px; }
.review-tabs :deep(.el-tabs__item) { padding: 0 14px; font-size: 13px; height: 36px; }
.review-tabs :deep(.el-tabs__nav-wrap::after) { height: 1px; background: #e2e8f0; }
.review-caption { display: flex; gap: 12px; justify-content: space-between; margin: 0 0 8px; color: var(--el-text-color-secondary); font-size: 12px; }
.review-table { overflow: hidden; }
.review-table :deep(.el-table) { --el-table-header-bg-color: #f8fafc; }
.review-table :deep(.el-table .cell) { line-height: 1.6; }
.result-line { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
.result-line > span { color: #64748b; }
.item-meta, .muted, .permission-note { color: #64748b; font-size: 12px; }
.item-meta { margin-top: 2px; }
.mobile-event-time { display: none; }
.permission-note { margin: 0 0 8px; }
.uncertainty-list { margin-top: 12px; padding: 10px 12px; background: #f8fafc; border-radius: 6px; font-size: 13px; line-height: 1.6; overflow-wrap: anywhere; }
.uncertainty-list strong { font-size: 12px; font-weight: 500; color: var(--el-text-color-secondary); }
.uncertainty-list ul { padding-left: 18px; margin: 6px 0 0; }
.review-editor { display: grid; gap: 12px; min-width: 0; max-height: 65vh; overflow-y: auto; padding-right: 4px; }
.editor-heading { display: flex; align-items: center; gap: 10px; }
.editor-heading strong { font-size: 14px; }
.evidence { padding: 10px 12px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; overflow-wrap: anywhere; }
.evidence-title { color: var(--el-text-color-secondary); font-size: 12px; }
.evidence blockquote { margin: 6px 0; white-space: pre-wrap; line-height: 1.6; }
.evidence blockquote :deep(.el-button) { margin-left: 8px; }
.evidence p { margin: 6px 0 0; }
.review-flags { display: flex; flex-wrap: wrap; gap: 6px 14px; color: var(--el-color-warning-dark-2); font-size: 12px; }
.event-time { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
.event-time label { display: grid; gap: 5px; font-size: 12px; color: var(--el-text-color-regular); }
.event-time .target-field { grid-column: 1 / -1; }
.event-time :deep(.el-date-editor), .event-time :deep(.el-select), .suggested-value :deep(.el-input-number), .suggested-value :deep(.el-select), .suggested-value :deep(.el-date-editor) { width: 100%; }
.readonly-event { display: flex; flex-wrap: wrap; gap: 8px 20px; font-size: 13px; }
.target-hint, .editor-notice { margin: 0; color: var(--el-color-warning-dark-2); font-size: 12px; line-height: 1.6; }
.field-grid { display: grid; grid-template-columns: 1fr 1fr 1.6fr; align-items: start; gap: 12px; padding-bottom: 10px; border-bottom: 1px solid #e2e8f0; font-size: 13px; }
.field-grid--header { color: var(--el-text-color-secondary); font-size: 12px; padding-bottom: 6px; }
.field-label small { display: block; color: var(--el-text-color-secondary); margin-top: 3px; }
.current-value { white-space: pre-wrap; overflow-wrap: anywhere; }
.suggested-value { min-width: 0; display: grid; gap: 4px; }
.suggested-value > :deep(.el-button) { justify-self: end; font-size: 12px; }
.review-confirm { white-space: normal; height: auto; min-height: 32px; align-items: flex-start; }
.review-confirm :deep(.el-checkbox__input) { margin-top: 4px; }
.review-confirm :deep(.el-checkbox__label) { white-space: normal; line-height: 1.6; font-size: 13px; }
.review-workspace { margin-top: 14px; scroll-margin-top: 12px; outline: none; }
.review-workspace:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: 4px; }
.review-player { position: sticky; top: 0; z-index: 2; background: var(--el-bg-color, #fff); padding: 10px 0; border-bottom: 1px solid var(--el-border-color-lighter); }
.inline-editor-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 14px 0; }
.draft-hint { flex: 1 1 100%; font-size: 12px; color: var(--el-text-color-secondary); }
.review-error { color: var(--el-color-danger); font-size: 12px; margin: 0; }
.editor-footer { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
.editor-footer :deep(.el-button + .el-button) { margin-left: 0; }
@media (max-width: 640px) {
.mobile-event-time { display: block; }
.review-tabs :deep(.el-tabs__item) { padding: 0 10px; }
.review-caption { gap: 6px; flex-wrap: wrap; }
.event-time { grid-template-columns: 1fr; }
.field-grid { grid-template-columns: 1fr; gap: 6px; }
.field-grid--header { display: none; }
.field-label { font-weight: 600; }
.current-value::before { content: '当前值:'; color: var(--el-text-color-secondary); }
.suggested-value::before { content: '审核值:'; color: var(--el-text-color-secondary); }
.editor-footer { gap: 6px; }
}
</style>
@@ -0,0 +1,59 @@
export type FollowupPlaybackChannel = 'original' | 0 | 1
function browserAudioContext(): AudioContext | null {
const browser = globalThis as typeof globalThis & { webkitAudioContext?: typeof AudioContext }
const Constructor = browser.AudioContext || browser.webkitAudioContext
return Constructor ? new Constructor() : null
}
/** One authorized HTML audio element owns one lazy graph; isolated audio is duplicated to both speakers. */
export function createFollowupAudioPlayback(element: HTMLMediaElement, createContext: () => AudioContext | null = browserAudioContext) {
let context: AudioContext | null = null
let source: MediaElementAudioSourceNode | null = null
let splitter: ChannelSplitterNode | null = null
let merger: ChannelMergerNode | null = null
let disposed = false
let generation = 0
function disconnect() { source?.disconnect(); splitter?.disconnect(); merger?.disconnect() }
return {
async select(channel: FollowupPlaybackChannel): Promise<boolean> {
if (disposed) return false
const ticket = ++generation
element.pause()
if (channel === 'original' && !context) return true
try {
if (!context) {
context = createContext()
if (!context) throw new Error('当前浏览器不支持 Web Audio,无法隔离声道;请使用原音播放。')
source = context.createMediaElementSource(element)
splitter = context.createChannelSplitter(2)
merger = context.createChannelMerger(2)
}
if (!source) throw new Error('音频播放节点未就绪')
disconnect()
if (channel === 'original') source.connect(context.destination)
else {
if (!splitter || !merger) throw new Error('声道播放节点未就绪')
source.connect(splitter)
splitter.connect(merger, channel, 0)
splitter.connect(merger, channel, 1)
merger.connect(context.destination)
}
await context.resume()
if (!disposed && ticket === generation && context.state !== 'running') throw new Error('音频上下文未运行')
return !disposed && ticket === generation
} catch (error) {
if (disposed || ticket !== generation) return false
disconnect()
// Keep an explicit original-audio fallback; never autoplay it after failed isolation.
if (source && context) source.connect(context.destination)
throw new Error(`无法隔离声道,已停止本次回听;可选择原音播放。${error instanceof Error ? error.message : ''}`)
}
},
dispose() {
if (disposed) return
disposed = true; generation++; element.pause(); disconnect()
if (context) void context.close().catch(() => { /* Element is already detached and all nodes disconnected. */ })
}
}
}
@@ -0,0 +1,196 @@
import type { FollowupAudioChannel, FollowupCapabilities, FollowupChannelRoles, FollowupField, FollowupFields, FollowupReviewItem, FollowupTaskDetail, FollowupTaskSummary, FollowupTranscriptSegment, FollowupValue } from '@/api/followupAudio'
export const FOLLOWUP_CHUNK_BYTES = 2097152
export const followupKindLabels = { diagnosis: '诊单资料', blood: '血糖 / 血压', diet: '饮食', exercise: '运动', tracking_note: '跟踪备注' }
export const followupStatusLabels: Record<string, string> = {
queued: '等待处理', running: '正在分析', review: '待人工审核', applied: '已采纳',
failed: '处理失败', needs_reconciliation: '结果待核对', expired: '已过保留期'
}
const followupStageLabels: Record<string, string> = { transcribing: '正在转写', extracting: '正在提炼', validating: '正在校验', review: '待人工审核' }
export function followupTaskStatus(task: Pick<FollowupTaskSummary, 'status' | 'stage'>): string {
return (task.status === 'running' && followupStageLabels[task.stage]) || followupStatusLabels[task.status] || task.status
}
export function followupProgressText(task: FollowupTaskSummary): string {
const progress = task.pipeline_progress
const valid = progress && Number.isSafeInteger(progress.transcribed) && Number.isSafeInteger(progress.total)
&& progress.total > 0 && progress.transcribed >= 0 && progress.transcribed <= progress.total
return `${followupTaskStatus(task)}${valid ? ` · 转写片段 ${progress.transcribed} / ${progress.total}` : ''};人工审核前不会写入业务记录。`
}
export function retainedTranscriptNotice(task: FollowupTaskDetail): string {
if (!task.transcript_available || !task.transcript.trim()) return ''
if (task.status === 'failed') return '处理失败,已完成片段的转写仍可查看。保留转写不代表提炼成功,不能直接写入病历。'
if (task.status === 'needs_reconciliation') return '结果待核对,已完成片段的转写仍可查看。请先核对上游结果,不要重复发送。'
return ''
}
export function evidencePlaybackLabel(quote: FollowupReviewItem['evidence'][number]): string {
if (typeof quote.start_ms !== 'number' || !Number.isFinite(quote.start_ms) || quote.start_ms < 0) return ''
if (quote.channel !== undefined && quote.channel !== 0 && quote.channel !== 1) return ''
if (quote.position_type === 'segment') {
if (!quote.segment_id || typeof quote.end_ms !== 'number' || !Number.isFinite(quote.end_ms) || quote.end_ms <= quote.start_ms) return ''
return `回听对话 ${audioTimestamp(quote.start_ms)}–${audioTimestamp(quote.end_ms)}`
}
return `播放 ${audioTimestamp(quote.start_ms)}`
}
export function audioTimestamp(ms: number): string { const seconds = Math.max(0, Math.floor(ms / 1000)); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` }
export function normalizedChannelRoles(value: unknown): FollowupChannelRoles { return value === 'left_service' || value === 'right_service' ? value : 'unconfirmed' }
export function hasStereoTranscript(segments: FollowupTranscriptSegment[] = []): boolean { return segments.some(segment => segment.channel === 0) && segments.some(segment => segment.channel === 1) }
export function followupChannelLabel(channel?: FollowupAudioChannel, roles: FollowupChannelRoles = 'unconfirmed'): string {
if (channel !== 0 && channel !== 1) return '未标注声道'
const side = channel === 0 ? '左声道' : '右声道'
const confirmed = normalizedChannelRoles(roles)
if (confirmed === 'unconfirmed') return `${side} · 角色待确认`
const service = confirmed === 'left_service' ? channel === 0 : channel === 1
return `${side} · ${service ? '客服端' : '患者/家属端'}(人工标注)`
}
/** Preserve coarse ASR windows; never invent speaker turn order or word-level timestamps. */
export function dialogueWindows(segments: FollowupTranscriptSegment[]) {
const windows = new Map<string, { id: string; start_ms: number; end_ms: number; segments: FollowupTranscriptSegment[] }>()
for (const segment of segments) {
const id = `${segment.start_ms}:${segment.end_ms}`
if (!windows.has(id)) windows.set(id, { id, start_ms: segment.start_ms, end_ms: segment.end_ms, segments: [] })
windows.get(id)!.segments.push(segment)
}
return [...windows.values()].sort((a, b) => a.start_ms - b.start_ms || a.end_ms - b.end_ms)
.map(window => ({ ...window, segments: [...window.segments].sort((a, b) => (a.channel ?? -1) - (b.channel ?? -1)) }))
}
export function dialoguePlaybackStart(milliseconds: number): number {
return Number.isFinite(milliseconds) ? Math.max(0, milliseconds - 3000) : 0
}
export function channelPlaybackLabel(channel: FollowupAudioChannel, roles: FollowupChannelRoles): string {
if (roles === 'unconfirmed') return channel === 0 ? '只听左声道' : '只听右声道'
const service = roles === 'left_service' ? channel === 0 : channel === 1
return service ? '只听客服' : '只听患者/家属'
}
export const cloneReviewItems = (items: FollowupReviewItem[]): FollowupReviewItem[] => JSON.parse(JSON.stringify(items))
export function fieldText(value: FollowupValue | undefined, field: FollowupField): string {
if (value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length)) return '未记录'
const display = (part: string | number | boolean) => field.options?.find(option => String(option.value) === String(part))?.label || String(part)
return Array.isArray(value) ? value.map(display).join('、') : display(value)
}
export function hasEditableReviewFields(item: FollowupReviewItem, fields: FollowupFields): boolean {
return Object.keys(item.values).some(key => fields[item.kind]?.some(field => field.key === key && !field.readonly))
}
/** Prevent multiple selected writes to the same diagnosis field; never silently pick a last value. */
export function reviewBatchIssue(items: FollowupReviewItem[], fields: FollowupFields): string {
const touched = new Set<string>()
for (const item of items.filter(item => item.selected)) {
if (item.kind === 'diagnosis') {
for (const key of Object.keys(item.values)) {
if (touched.has(key)) {
const label = fields.diagnosis?.find(field => field.key === key)?.label || key
return `${label}存在多条选中建议,请合并内容到一项或仅保留一项后再确认写入`
}
touched.add(key)
}
}
}
return ''
}
export function reviewFieldIssue(item: FollowupReviewItem, fields: FollowupFields): string {
if (!item.selected) return ''
for (const key of Object.keys(item.values)) {
const field = fields[item.kind]?.find(candidate => candidate.key === key)
if (!field || field.readonly) return `${field?.label || key} 当前不可编辑,请先取消采纳该字段`
}
return ''
}
export function reviewIssue(item: FollowupReviewItem, canDaily: boolean): string {
if (!item.selected) return ''
if (item.needs_review) return '请明确核对不确定、冲突或重复内容'
if (item.kind !== 'diagnosis' && !canDaily) return '没有日常记录编辑权限'
if (!Object.keys(item.values).length) return '至少填写一个有效字段'
if (item.kind !== 'diagnosis' && !validDate(item.record_date)) return '请核对并填写有效的记录日期'
if (item.record_time && !/^([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(item.record_time)) return '请填写有效的记录时间'
return ''
}
/** Pending is independent of selection so filtering never hides unresolved items. */
export function reviewPending(item: FollowupReviewItem, fields: FollowupFields, canDaily: boolean): boolean {
return item.needs_review || !!reviewFieldIssue({ ...item, selected: true }, fields) || !!reviewIssue({ ...item, selected: true }, canDaily)
}
export function reviewCounts(items: FollowupReviewItem[], fields: FollowupFields, canDaily: boolean) {
return {
all: items.length,
diagnosis: items.filter(item => item.kind === 'diagnosis').length,
daily: items.filter(item => item.kind !== 'diagnosis').length,
pending: items.filter(item => reviewPending(item, fields, canDaily)).length,
selected: items.filter(item => item.selected).length
}
}
export function changedReviewTarget(items: FollowupReviewItem[], snapshot: FollowupReviewItem[]): boolean {
const previous = new Map(snapshot.map(item => [item.id, item]))
return items.some(item => {
const original = previous.get(item.id)
return item.selected && original && (item.target_id !== original.target_id || item.record_date !== original.record_date)
})
}
/** The API accepts legacy seconds, while the review editor exposes minute precision. */
export function reviewTimeValue(value: string | null): string | null {
return value && /^([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(value) ? value.slice(0, 5) : null
}
export function validDate(value: string | null): boolean {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
const [year, month, day] = value.split('-').map(Number)
const date = new Date(Date.UTC(year, month - 1, day))
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
}
/** A stale snapshot refresh never discards user values or reselects an item for them. */
export function rebaseReviewItems(local: FollowupReviewItem[], fresh: FollowupReviewItem[]): FollowupReviewItem[] {
const previous = new Map(local.map(item => [item.id, item]))
return cloneReviewItems(fresh).map(item => {
const edit = previous.get(item.id)
return edit ? { ...item, values: { ...edit.values }, record_date: edit.record_date, record_time: edit.record_time,
time_period: edit.time_period, target_id: edit.target_id, selected: false, needs_review: true } : item
})
}
/** Missing preview readiness/scope fails closed; normal deployments retain their full-verification rules. */
export function followupFeatureEnabled(caps: FollowupCapabilities | null): boolean {
return !!caps?.enabled && (!caps.preview_only || caps.test_scope_allowed === true)
}
export function followupAudioReady(caps: FollowupCapabilities | null): boolean {
return !!caps && (caps.preview_only ? caps.preview_ready === true && caps.test_scope_allowed === true : caps.audio_verified || (caps.manual_review_enabled === true && caps.manual_review_ready === true))
}
export function followupCanReview(caps: FollowupCapabilities | null, previewTask = false): boolean {
return followupFeatureEnabled(caps) && !!caps && (caps.preview_only || previewTask ? caps.can_review === true : caps.can_apply)
}
export function followupCanApply(caps: FollowupCapabilities | null, previewTask = false): boolean {
return followupFeatureEnabled(caps) && followupAudioReady(caps) && !!caps && !caps.preview_only && !previewTask && caps.can_apply
}
export function uploadIssue(file: Pick<File, 'size' | 'name'> | null, recordedAt: string, model: string, caps: FollowupCapabilities | null, viewOnly: boolean): string {
if (viewOnly || !caps || !followupFeatureEnabled(caps) || !followupAudioReady(caps) || !caps.can_upload) return '当前不可上传录音'
if (!file || !file.size) return '请选择非空录音文件'
if (file.size > caps.limits.max_bytes) return '录音文件超过大小限制'
if (!/\.(mp3|wav|m4a|amr)$/i.test(file.name)) return '请选择支持的录音格式'
if (!/^\d{4}-\d{2}-\d{2} ([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(recordedAt) || !validDate(recordedAt.slice(0, 10))) return '请填写实际录音时间(北京时间)'
if (!caps.models.some(option => option.value === model)) return '请选择可用的分析模型'
return ''
}
/** All async operations capture one generation; invalidate on patient switch, hide or dispose. */
export function createFollowupScope() {
let generation = 0
let controller = new AbortController()
return {
capture: () => ({ generation, signal: controller.signal }),
current: (ticket: { generation: number; signal: AbortSignal }) => ticket.generation === generation && !ticket.signal.aborted,
invalidate() { controller.abort(); generation++; controller = new AbortController() }
}
}
export async function uploadChunks(
file: Blob,
chunkBytes: number,
send: (index: number, chunk: Blob) => Promise<{ received: boolean }>,
isCurrent: () => boolean,
progress: (percent: number) => void
): Promise<boolean> {
if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 65536 || chunkBytes > FOLLOWUP_CHUNK_BYTES) throw new Error('服务端分片配置不匹配,请联系管理员')
for (let start = 0, index = 0; start < file.size; start += chunkBytes, index++) {
if (!isCurrent()) return false
const result = await send(index, file.slice(start, start + chunkBytes))
if (!isCurrent()) return false
if (!result.received) throw new Error('录音分片未被服务端确认,上传已停止')
progress(Math.round(Math.min(start + chunkBytes, file.size) / file.size * 100))
}
return isCurrent()
}
export function followupError(error: unknown): string {
return error instanceof Error ? error.message : '请求失败;当前审核内容已保留,请刷新任务状态后确认'
}
+150 -6
View File
@@ -52,7 +52,7 @@
</p>
</div>
</template>
<el-tabs v-model="activeTab" class="diagnosis-tabs tcm-diagnosis-tabs">
<el-tabs v-model="activeTab" :before-leave="beforeTabLeave" class="diagnosis-tabs tcm-diagnosis-tabs">
<!-- 基本信息标签页 -->
<el-tab-pane label="病历" name="basic">
<el-form
@@ -660,6 +660,7 @@
lazy
>
<daily-matrix
ref="dailyMatrixRef"
v-if="formData.id"
:diagnosis-id="Number(formData.id)"
:patient-id="Number(formData.patient_id)"
@@ -670,6 +671,33 @@
<el-empty v-else description="请先保存诊单后查看" />
</el-tab-pane>
<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音" name="followupAudio" lazy>
<el-alert v-if="followupCapabilitiesLoading" title="正在检查回访录音状态…" type="info" :closable="false" show-icon />
<div v-else-if="followupCapabilitiesError" role="alert">
<el-alert :title="followupCapabilitiesError" type="error" :closable="false" show-icon />
<el-button class="mt-3" @click="loadFollowupCapabilities">重新加载</el-button>
</div>
<FollowupAudioPanel
v-else-if="visible && followupCapabilities?.enabled && followupCapabilitiesDiagnosisId === Number(formData.id)"
:key="Number(formData.id)"
ref="followupAudioRef"
:diagnosis-id="Number(formData.id)"
:view-only="viewOnly"
:active="activeTab === 'followupAudio'"
:capabilities="followupCapabilities"
:basic-dirty="basicDirty"
:before-apply="canApplyFollowup"
@applied="handleFollowupApplied"
/>
<el-alert
v-else
:title="followupCapabilities?.test_scope_allowed === false ? '当前诊单未开放回访录音' : '当前未启用回访录音,请联系管理员确认'"
type="info"
:closable="false"
show-icon
/>
</el-tab-pane>
<!-- 病历记录标签页(开方后自动显示) -->
<el-tab-pane label="处方" name="bingli" :disabled="!formData.id" v-if="hasPermission(['tcm.diagnosis/chufang'])">
<div v-if="formData.id" class="bingli-tab-content">
@@ -785,6 +813,7 @@
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { tcmDiagnosisAdd, tcmDiagnosisEdit, tcmDiagnosisDetail, checkPhone, checkIdCard, diagnosisTrackingNotes } from '@/api/tcm'
import { getDictData } from '@/api/app'
import feedback from '@/utils/feedback'
@@ -794,6 +823,8 @@ import useAppStore from '@/stores/modules/app'
import { ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import DailyMatrix from './components/DailyMatrix.vue'
import FollowupAudioPanel from './components/FollowupAudioPanel.vue'
import { followupAudioCapabilities, type FollowupCapabilities } from '@/api/followupAudio'
import CaseRecordList from './components/CaseRecordList.vue'
import CallRecordPanel from './components/CallRecordPanel.vue'
import ImChatRecordPanel from './components/ImChatRecordPanel.vue'
@@ -811,6 +842,15 @@ const getImageUrl = (url: string) => (url?.indexOf?.('http') === 0 ? url : appSt
const caseRecordListRef = ref()
const callRecordPanelRef = ref<{ refresh?: () => void } | null>(null)
const prescriptionRef = ref()
const dailyMatrixRef = ref<{ refresh?: () => Promise<void> | void } | null>(null)
const followupAudioRef = ref<{ confirmLeave: () => Promise<boolean> } | null>(null)
const followupCapabilities = ref<FollowupCapabilities | null>(null)
const followupCapabilitiesLoading = ref(false)
const followupCapabilitiesError = ref('')
const followupCapabilitiesDiagnosisId = ref<number | null>(null)
const basicSnapshot = ref('')
let diagnosisGeneration = 0
let capabilitiesRequest: AbortController | undefined
const visible = ref(false)
/** 只读查看:与 consumers 处方等处「查看诊单」一致,全部 Tab 仅展示不可保存 */
@@ -822,6 +862,7 @@ const submitting = ref(false)
/** 拥有后手机号可正常编辑,失焦不再强制脱敏 */
const hasPhonePlainPermission = computed(() => hasPermission(['tcm.diagnosis/phonePlain']))
const hasDailyRecordPermission = computed(() => hasPermission(['tcm.diagnosis/dailyRecord']))
const hasFollowupAudioPermission = computed(() => hasPermission(['tcm.diagnosis/followupAudio']))
const patientBasicLocked = ref(false)
const canEditPatientBasicFromApi = ref(true)
const latestPrescriptionOrder = ref<{
@@ -970,6 +1011,77 @@ const formData = ref({
external_userid: ''
})
// Include unmasked identity values so merely revealing a number is not an unsaved edit.
const basicFingerprint = () => JSON.stringify({ ...formData.value,
phone: originalPhone.value || formData.value.phone, id_card: originalIdCard.value || formData.value.id_card })
const basicDirty = computed(() => !viewOnly.value && !!basicSnapshot.value && basicFingerprint() !== basicSnapshot.value)
const canApplyFollowup = () => !basicDirty.value && visible.value && !viewOnly.value
async function beforeTabLeave(next: string | number, previous: string | number): Promise<boolean> {
if (next === 'followupAudio' && basicDirty.value) {
feedback.msgWarning('病历有未保存修改,请先保存后再进入回访录音审核,当前输入已保留')
return false
}
if (previous === 'followupAudio') return await followupAudioRef.value?.confirmLeave() ?? true
return true
}
async function handleFollowupApplied(diagnosisId: number) {
if (!visible.value || Number(formData.value.id) !== diagnosisId) return
const generation = diagnosisGeneration
try {
// The response itself is also guarded, including edits made while it is in flight.
await loadDiagnosisDetailIntoForm(diagnosisId, true)
if (generation !== diagnosisGeneration || !visible.value || Number(formData.value.id) !== diagnosisId) return
await dailyMatrixRef.value?.refresh?.()
emit('success')
} catch {
if (generation === diagnosisGeneration) feedback.msgWarning('录音已采纳,但病历或日常记录刷新失败,请手动刷新查看')
}
}
function resetFollowupCapabilities() {
capabilitiesRequest?.abort()
capabilitiesRequest = undefined
followupCapabilities.value = null
followupCapabilitiesDiagnosisId.value = null
followupCapabilitiesLoading.value = false
followupCapabilitiesError.value = ''
}
async function loadFollowupCapabilities(): Promise<void> {
// A rapid second click must not create another request for the same context.
if (followupCapabilitiesLoading.value) return
resetFollowupCapabilities()
const id = Number(formData.value.id)
if (!visible.value || !id || !hasFollowupAudioPermission.value) return
const generation = diagnosisGeneration
const request = new AbortController()
capabilitiesRequest = request
followupCapabilitiesLoading.value = true
const isCurrent = () => capabilitiesRequest === request && !request.signal.aborted
&& generation === diagnosisGeneration && visible.value && Number(formData.value.id) === id
try {
const result = await followupAudioCapabilities(id, request.signal)
if (!isCurrent()) return
if (typeof result?.enabled !== 'boolean') throw new Error('Invalid capability response')
followupCapabilities.value = result
followupCapabilitiesDiagnosisId.value = id
} catch {
if (!isCurrent()) return
// No endpoint failure (including permission denial) may mount the panel.
followupCapabilitiesError.value = '回访录音状态加载失败,请重新加载;若仍失败,请联系管理员检查权限或服务状态'
} finally {
if (isCurrent()) {
followupCapabilitiesLoading.value = false
capabilitiesRequest = undefined
}
}
}
watch([visible, () => formData.value.id, hasFollowupAudioPermission], () => {
// Invalidate synchronously on patient switches and permission changes.
if (!hasFollowupAudioPermission.value && activeTab.value === 'followupAudio') activeTab.value = 'basic'
resetFollowupCapabilities()
void loadFollowupCapabilities()
}, { flush: 'sync' })
onBeforeUnmount(() => { diagnosisGeneration++; resetFollowupCapabilities() })
/** 就诊卡创建来源(与 zyt_tcm_diagnosis.create_source 一致) */
const createSourceOptions = [
{ value: '', label: '未设置' },
@@ -1260,8 +1372,14 @@ const getDictOptions = async () => {
}
}
async function loadDiagnosisDetailIntoForm(id: number): Promise<void> {
async function loadDiagnosisDetailIntoForm(id: number, preserveDirty = false): Promise<void> {
const generation = diagnosisGeneration
const data = await tcmDiagnosisDetail({ id })
if (generation !== diagnosisGeneration || !visible.value) return
if (preserveDirty && basicDirty.value) {
feedback.msgWarning('录音已采纳,病历仍保留你的未保存修改;请核对后再保存,未用刷新覆盖输入')
return
}
originalPhone.value = data.phone || ''
originalIdCard.value = data.id_card || ''
@@ -1277,6 +1395,7 @@ async function loadDiagnosisDetailIntoForm(id: number): Promise<void> {
formData.value.show_card = Number(data.show_card) === 0 ? 0 : 1
const y = data.diabetes_discovery_year
formData.value.diabetes_discovery_year = y == null || y === '' ? '' : String(y)
basicSnapshot.value = basicFingerprint()
}
const resetPatientBasicLockState = () => {
@@ -1286,6 +1405,11 @@ const resetPatientBasicLockState = () => {
}
const open = async (type: string, id?: number) => {
const generation = ++diagnosisGeneration
submitting.value = false
basicSnapshot.value = ''
resetFollowupCapabilities()
formData.value.id = ''
viewOnly.value = false
mode.value = type
visible.value = true
@@ -1296,6 +1420,7 @@ const open = async (type: string, id?: number) => {
// 加载字典数据
await getDictOptions()
if (generation !== diagnosisGeneration || !visible.value) return
if (type === 'edit' && id) {
await loadDiagnosisDetailIntoForm(id)
@@ -1310,6 +1435,11 @@ const open = async (type: string, id?: number) => {
/** 只读打开:与编辑同一套界面与全部 Tab,不可保存 */
const openViewOnly = async (id: number) => {
if (!id) return
const generation = ++diagnosisGeneration
submitting.value = false
basicSnapshot.value = ''
resetFollowupCapabilities()
formData.value.id = ''
viewOnly.value = true
mode.value = 'edit'
visible.value = true
@@ -1318,13 +1448,17 @@ const openViewOnly = async (id: number) => {
idCardRevealUnlocked.value = false
resetPatientBasicLockState()
await getDictOptions()
if (generation !== diagnosisGeneration || !visible.value) return
await loadDiagnosisDetailIntoForm(id)
}
const handleSubmit = async () => {
if (viewOnly.value) return
if (viewOnly.value || submitting.value) return
const generation = diagnosisGeneration
await formRef.value?.validate()
if (generation !== diagnosisGeneration || !visible.value) return
// A user can keep typing while the request is pending. Only mark submitted bytes saved.
const submittedForm = JSON.parse(basicFingerprint()) as typeof formData.value
submitting.value = true
try {
// 准备提交数据,使用原始完整数据
@@ -1336,6 +1470,7 @@ const handleSubmit = async () => {
if (mode.value === 'add') {
const result = await tcmDiagnosisAdd(submitData)
if (generation !== diagnosisGeneration || !visible.value) return
// 如果是新增,保存成功后切换到编辑模式,这样可以添加血糖血压记录
if (result && result.id) {
@@ -1343,11 +1478,14 @@ const handleSubmit = async () => {
phoneRevealUnlocked.value = false
idCardRevealUnlocked.value = false
formData.value.id = result.id
submittedForm.id = result.id
// 重新获取详情,确保patient_id等字段正确
try {
const detail = await tcmDiagnosisDetail({ id: result.id })
if (generation !== diagnosisGeneration || !visible.value) return
formData.value.patient_id = detail.patient_id
submittedForm.patient_id = detail.patient_id
// 更新原始数据
originalPhone.value = detail.phone || ''
@@ -1367,11 +1505,13 @@ const handleSubmit = async () => {
await tcmDiagnosisEdit(submitData)
}
if (generation !== diagnosisGeneration || !visible.value) return
basicSnapshot.value = JSON.stringify(submittedForm)
emit('success')
} catch (error) {
console.error('提交失败:', error)
} finally {
submitting.value = false
if (generation === diagnosisGeneration) submitting.value = false
}
}
@@ -1395,7 +1535,11 @@ const handleOpenPrescription = () => {
prescriptionRef.value?.open(data)
}
const handleClose = () => {
const handleClose = async () => {
if (followupAudioRef.value && !await followupAudioRef.value.confirmLeave()) return
diagnosisGeneration++
resetFollowupCapabilities()
basicSnapshot.value = ''
formRef.value?.resetFields()
formData.value = {
id: '',
+2
View File
@@ -79,6 +79,7 @@
</el-form-item>
</el-form>
</el-card>
<iam-personal />
<footer-btns>
<el-button type="primary" @click="handleSubmit">保存</el-button>
</footer-btns>
@@ -108,6 +109,7 @@
</template>
<script setup lang="ts" name="userSetting">
import IamPersonal from '@/components/iam-v2/personal.vue'
import type { FormInstance } from 'element-plus'
import { nextTick, onMounted, onUnmounted, ref, reactive } from 'vue'
import { Loading, CircleCheck, Connection } from '@element-plus/icons-vue'
@@ -0,0 +1,47 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const file = process.env.FOLLOWUP_EXERCISE_MATRIX_SOURCE || path.resolve(__dirname, '../src/views/tcm/diagnosis/components/DailyMatrix.vue')
const source = fs.readFileSync(file, 'utf8')
function setup() {
const descriptor = parse(source, {filename:file}).descriptor
const compiled = compileScript(descriptor, {id:'exercise-null'})
const output = ts.transpileModule(compiled.content, {compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText
const calls=[]; const warnings=[]; const module={exports:{}}
const api={diagnosisTrackingWindow:async()=>({}),diagnosisTrackingNotes:async()=>[],exerciseRecordEdit:async p=>calls.push(p),exerciseRecordAdd:async p=>calls.push(p)}
new Function('require','module','exports',output)(name=>name==='vue'?{...vue,onMounted(){},onUnmounted(){}}:name==='@/utils/perm'?{hasPermission:()=>true}:name==='@/api/tcm'?api:name==='@/utils/feedback'?{default:{msgWarning:m=>warnings.push(m)}}:{default:{}},module,module.exports)
const scope=vue.effectScope()
const matrix=scope.run(()=>module.exports.default.setup({diagnosisId:1,patientId:101,readOnly:false},{expose(){}}))
return {matrix,calls,warnings,dispose:()=>scope.stop()}
}
test('real DailyMatrix edit and submit preserve null duration/intensity',async()=>{
const f=setup(); f.matrix.openExerciseRecord({id:1,record_date:'2026-09-29',exercise_type:'散步',duration:null,intensity:null},'2026-09-29')
assert.equal(f.matrix.exerciseForm.value.duration,null);assert.equal(f.matrix.exerciseForm.value.intensity,null)
f.matrix.exerciseForm.value.note='仅改备注';await f.matrix.submitExercise()
assert.equal(f.calls.length,1);assert.equal(f.calls[0].duration,null);assert.equal(f.calls[0].intensity,null);assert.deepEqual(f.warnings,[]);f.dispose()
})
test('missing keys in existing row do not inherit manual-entry defaults',()=>{
const f=setup();f.matrix.openExerciseRecord({id:2,exercise_type:'散步'},'2026-09-29')
assert.equal(f.matrix.exerciseForm.value.duration,null);assert.equal(f.matrix.exerciseForm.value.intensity,null);f.dispose()
})
test('explicit known and zero values remain unchanged; cleared duration submits null',async()=>{
const f=setup();f.matrix.openExerciseRecord({id:2,exercise_type:'散步',duration:0,intensity:1},'2026-09-29')
await f.matrix.submitExercise();assert.equal(f.calls[0].duration,0);assert.equal(f.calls[0].intensity,1)
f.matrix.exerciseForm.value.duration=undefined;await f.matrix.submitExercise();assert.equal(f.calls[1].duration,null);f.dispose()
})
test('unknown intensity option maps to null without conflating known low intensity',()=>{
const f=setup();f.matrix.openExerciseRecord({id:1,exercise_type:'散步',duration:null,intensity:null},'2026-09-29')
assert.equal(f.matrix.exerciseIntensity.value,'');f.matrix.exerciseIntensity.value=1;assert.equal(f.matrix.exerciseForm.value.intensity,1)
f.matrix.exerciseIntensity.value='';assert.equal(f.matrix.exerciseForm.value.intensity,null)
assert.equal(f.matrix.intensityLabel(null),'未记录');assert.equal(f.matrix.intensityLabel(1),'低强度');f.dispose()
})
test('matrix compiles and detail rendering explicitly distinguishes unknown from zero',()=>{
const descriptor=parse(source,{filename:file}).descriptor;const script=compileScript(descriptor,{id:'exercise-compile'})
const render=compileTemplate({source:descriptor.template.content,filename:file,id:'exercise-compile',compilerOptions:{bindingMetadata:script.bindings}})
assert.deepEqual(render.errors,[]);assert.ok(/<el-option label="未记录" value=""/.test(source), "explicit unknown option exists")
assert.ok(/record\.duration == null \? '未记录'/.test(source), 'null duration renders unknown')
})
@@ -0,0 +1,64 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const dir = path.resolve(__dirname, '../src/views/tcm/diagnosis/components')
const reviewFile = process.env.FOLLOWUP_INLINE_REVIEW_SOURCE || path.join(dir, 'FollowupAudioReview.vue')
function execute(source, requireFn) {
const out = ts.transpileModule(source,{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText
const module={exports:{}};new Function('require','module','exports',out)(requireFn,module,module.exports);return module.exports
}
const state=execute(fs.readFileSync(path.join(dir,'followupAudioState.ts'),'utf8'),require)
const row=(id,extra={})=>({id,kind:'blood',values:{fasting_blood_sugar:6.2},record_date:'2026-10-12',record_time:'08:00',time_period:'早晨',time_estimated:true,time_text:'早晨',date_text:'今天',evidence:[{text:'六点二',channel:1,segment_id:'right-1',start_ms:0,end_ms:15000,position_type:'segment'}],needs_review:true,selected:false,target_id:null,current_values:{},expected_hash:'original',conflict:false,possible_duplicate:false,...extra})
function setup(extra={}){
const descriptor=parse(fs.readFileSync(reviewFile,'utf8'),{filename:reviewFile}).descriptor
const compiled=compileScript(descriptor,{id:'inline-review'})
const mod=execute(compiled.content,name=>name==='vue'?vue:name==='./followupAudioState'?state:{default:{}})
const props=vue.reactive({items:[row('one'),row('two'),row('three')],fields:{blood:[{key:'fasting_blood_sugar',label:'空腹血糖',type:'number'}]},disabled:false,canDaily:true,applied:false,saveState:'saved',...extra})
const events=[];const scope=vue.effectScope();const review=scope.run(()=>mod.default.setup(props,{expose(){},emit(event,...args){events.push([event,...args]);if(event==='update:items')props.items=args[0]}}))
return {review,props,events,dispose:()=>scope.stop()}
}
test('inline editor has one permanently mounted player slot and no modal overlay',()=>{
const source=fs.readFileSync(reviewFile,'utf8');assert.doesNotMatch(source,/<el-dialog/);assert.equal((source.match(/<slot name="player"/g)||[]).length,1)
assert.match(source,/position: sticky/);assert.match(source,/aria-label="同页核对与回听"/)
const descriptor=parse(source,{filename:reviewFile}).descriptor;const script=compileScript(descriptor,{id:'inline-compile'})
const render=compileTemplate({source:descriptor.template.content,filename:reviewFile,id:'inline-compile',compilerOptions:{bindingMetadata:script.bindings}});assert.deepEqual(render.errors,[])
})
test('accept-next requires explicit verification, retains immutable evidence and opens next unselected item',async()=>{
const f=setup({items:[row('one'),row('two',{selected:true,needs_review:false}),row('three')]});f.review.openReview('one')
f.review.saveReview(true,true);assert.equal(f.props.items[0].selected,false);assert.equal(f.review.editor.value.id,'one')
f.review.confirmReview(true);f.review.saveReview(true,true)
assert.equal(f.props.items[0].selected,true);assert.equal(f.props.items[0].needs_review,false);assert.equal(f.review.editor.value.id,'three')
assert.deepEqual(f.props.items[0].evidence,row('one').evidence);assert.ok(f.events.some(e=>e[0]==='saved-next'))
await vue.nextTick();assert.equal(f.review.editor.value.id,'three');f.dispose()
})
test('pending-filter accept-next captures next id before accepted row leaves filter',()=>{
const f=setup();f.review.group.value='pending';f.review.openReview('one');f.review.confirmReview(true);f.review.saveReview(true,true)
assert.equal(f.review.editor.value.id,'two');assert.deepEqual(f.review.visibleItems.value.map(r=>r.id),['two','three']);f.dispose()
})
test('skip preserves patient values, does not claim review complete, and never writes or selects',()=>{
const f=setup();f.review.openReview('one');f.review.skipAndNext();assert.equal(f.review.editor.value.id,'two');assert.equal(f.props.items[0].needs_review,true);assert.equal(f.props.items[0].selected,false)
assert.deepEqual(f.props.items[0].values,{fasting_blood_sugar:6.2});assert.ok(f.events.every(e=>['update:items','saved-next'].includes(e[0])));f.dispose()
})
test('inline row switching or skipping never silently drops unsaved edits',()=>{
const f=setup();f.review.openReview('one');f.review.setValue('fasting_blood_sugar',6.8);f.review.openReview('two');assert.equal(f.review.editor.value.id,'one');assert.match(f.review.editorNotice.value,/未保存/)
f.review.skipAndNext();assert.equal(f.review.editor.value.id,'one');assert.equal(f.review.editor.value.values.fasting_blood_sugar,6.8);assert.equal(f.props.items[0].values.fasting_blood_sugar,6.2);f.dispose()
})
test('date change remains gated until saved and authoritative target refreshed',()=>{
const f=setup();f.review.openReview('one');f.review.patchEditor({record_date:'2026-10-11'});f.review.confirmReview(true);f.review.saveReview(true,true);assert.equal(f.props.items[0].selected,false);assert.equal(f.review.editor.value.id,'one')
f.review.saveReview(false);assert.equal(f.props.items[0].record_date,'2026-10-11');assert.equal(f.props.items[0].needs_review,true);assert.ok(f.events.some(e=>e[0]==='saved-next'));f.dispose()
})
test('last item completes without wrapping or applying, read-only cannot advance mutations',()=>{
const f=setup({items:[row('one')]});f.review.openReview('one');f.review.confirmReview(true);f.review.saveReview(true,true);assert.equal(f.review.editor.value,null);assert.match(f.review.navigationNotice.value,/末项/);assert.equal(f.events.some(e=>e[0]==='apply'),false);f.dispose()
const g=setup({disabled:true});g.review.openReview('one');g.review.skipAndNext();g.review.saveReview(true,true);assert.equal(g.events.length,0);g.dispose()
})
test('reopening the same row or toggling its selection preserves unsaved editor data',()=>{
const f=setup();f.review.openReview('one');f.review.setValue('fasting_blood_sugar',7.1)
f.review.openReview('one');assert.equal(f.review.editor.value.values.fasting_blood_sugar,7.1)
f.review.toggleSelection(f.props.items[0],true);assert.equal(f.review.editor.value.values.fasting_blood_sugar,7.1)
assert.equal(f.props.items[0].values.fasting_blood_sugar,6.2);assert.equal(f.props.items[0].selected,false);f.dispose()
})
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -8,7 +8,7 @@
Windows 直接在项目根目录双击:
- `一键运行_医生工作站.bat`:优先启动现有成品;没有成品时自动使用 `uv` 准备源码环境并运行。
- `一键运行_医生工作站.bat`:在源码目录且 `.venv` 可用时运行最新源码;否则运行现有成品;没有成品时使用 `uv` 准备源码环境并运行。
- `一键打包_医生工作站.bat`:自动同步锁定的 Python/Node 依赖,检查冻结 QtWebEngine/QtMultimedia 文件,执行应用与媒体离屏冒烟验证,最后生成 `dist/DoctorWorkstation-Setup-Windows-x64-<版本>.exe` 安装包、便携 ZIP 和 SHA-256 文件。首次使用会自动下载固定版本的 Inno Setup,并校验下载文件的 SHA-256 与数字签名。
英文稳定别名分别是 `Run_DoctorWorkstation.bat` 和 `Build_DoctorWorkstation.bat`。分发 ZIP 解压后,可直接双击其中的 `Start_DoctorWorkstation.bat`。
+12 -8
View File
@@ -9,6 +9,7 @@ $FrozenExecutable = Join-Path $ProjectRoot "dist\DoctorWorkstation\DoctorWorksta
$ProjectPython = Join-Path $ProjectRoot ".venv\Scripts\python.exe"
$ProjectUvCache = Join-Path $ProjectRoot ".uv-cache"
$SourceRoot = Join-Path $ProjectRoot "src"
$SourceEntry = Join-Path $SourceRoot "doctor_workstation\__main__.py"
function Test-ProjectPython {
param([Parameter(Mandatory = $true)][string]$Candidate)
@@ -33,7 +34,13 @@ function Find-Uv {
}
try {
if (Test-Path -LiteralPath $FrozenExecutable -PathType Leaf) {
$Python = $null
if ((Test-Path -LiteralPath $SourceEntry -PathType Leaf) -and
(Test-ProjectPython -Candidate $ProjectPython)) {
$Python = $ProjectPython
Write-Host "Using current source tree: $SourceRoot"
}
elseif (Test-Path -LiteralPath $FrozenExecutable -PathType Leaf) {
Write-Host "Using packaged application: $FrozenExecutable"
if ($ValidateOnly) {
Write-Host "Windows run entry validation passed."
@@ -47,13 +54,7 @@ try {
}
exit $ApplicationExitCode
}
$Python = $null
if (Test-ProjectPython -Candidate $ProjectPython) {
$Python = $ProjectPython
Write-Host "Using existing project environment: $ProjectPython"
}
else {
elseif (Test-Path -LiteralPath $SourceEntry -PathType Leaf) {
$Uv = Find-Uv
if (-not $Uv) {
throw "No packaged application or usable .venv was found, and uv is not installed."
@@ -108,6 +109,9 @@ try {
}
$Python = $ProjectPython
}
else {
throw "No source entry or packaged application was found."
}
if ($ValidateOnly) {
Write-Host "Windows run entry validation passed."
+4
View File
@@ -1004,6 +1004,8 @@ class ApplicationController(QObject):
preview_height = min(380, max(320, round(preview_width * 0.66)))
margin = 18
if callable(getattr(video_window, "setProperty", None)):
video_window.setProperty("doctorSkipOpenGeometry", True)
video_window.showNormal()
video_window.setMinimumSize(440, 300)
video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
@@ -1058,6 +1060,8 @@ class ApplicationController(QObject):
window.raise_()
if activate:
window.activateWindow()
if callable(getattr(window, "setProperty", None)):
window.setProperty("doctorSkipOpenGeometry", False)
except (AttributeError, RuntimeError):
return
@@ -64,6 +64,7 @@ DEMO_PERMISSIONS: tuple[str, ...] = (
"tcm.diagnosis/editAiReport",
"tcm.diagnosis/aiAnalysis",
"tcm.diagnosis/aiAssistant",
"tcm.diagnosis/aiGeneratePrescription",
"tcm.diagnosis/patientAiReports",
"tcm.diagnosis/generatePatientAiReport",
"tcm.diagnosis/dailyRecord",
@@ -19,7 +19,6 @@ from doctor_workstation.core.errors import (
ApiBusinessError,
ApiHttpError,
ApiProtocolError,
ApiTimeoutError,
ApiTransportError,
AuthenticationExpiredError,
)
@@ -1413,11 +1412,11 @@ class RemoteDoctorRepository:
task: str = "custom",
cancelled: Callable[[], bool] | None = None,
) -> Iterator[dict[str, Any]]:
"""Stream a diagnosis answer, with one legacy fallback before first content."""
"""Stream a diagnosis answer; use the legacy route only when streaming is absent."""
clean_prompt, clean_task = _diagnosis_ai_request(diagnosis_id, prompt, task)
body = {"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task}
received_delta = False
received_event = False
received_done = False
try:
for raw_event in self.client.post_event_stream(
@@ -1428,13 +1427,12 @@ class RemoteDoctorRepository:
):
if cancelled is not None and cancelled():
return
received_event = True
event = _normalise_diagnosis_ai_event(raw_event)
if event is None:
continue
kind = event["event"]
if kind == "delta":
received_delta = True
elif kind == "done":
if kind == "done":
received_done = True
yield event
if kind == "done":
@@ -1443,12 +1441,16 @@ class RemoteDoctorRepository:
return
if not received_done:
raise ApiProtocolError("AI assistant stream ended before done")
except (ApiHttpError, ApiProtocolError, ApiTimeoutError, ApiTransportError):
if received_delta or (cancelled is not None and cancelled()):
except ApiHttpError as error:
if (
error.status_code not in {404, 405}
or received_event
or (cancelled is not None and cancelled())
):
raise
# Older deployments do not expose the stream route. Submit exactly one
# request through the confirmed non-streaming endpoint in that case.
# Only a missing stream route on an older deployment justifies another
# full request. Timeouts, transport failures and malformed streams do not.
result = self.analyze_diagnosis_ai(
diagnosis_id,
clean_prompt,
@@ -43,6 +43,7 @@ from PySide6.QtWidgets import (
)
from ..core.appointment_modes import APPOINTMENT_MODES
from .theme import main_window_target_rect
from .widgets import (
display_text,
first_value,
@@ -1766,6 +1767,11 @@ class AppointmentDrawer(QDialog):
super().mousePressEvent(event)
def _sync_to_owner(self) -> None:
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
self._update_drawer_width()
return
if self._owner is None:
self._update_drawer_width()
return
@@ -54,6 +54,7 @@ from ..diagnosis_terms import (
TermIndex,
shared_terms,
)
from ..report_provenance import report_provenance_lines
from ..theme import apply_reading_rhythm, mark_business_dialog
from ..widgets import (
display_text,
@@ -176,8 +177,8 @@ QDialog#AiConsultDialog QTabBar#AiConsultTabs {
}
QDialog#AiConsultDialog QTabBar#AiConsultTabs::tab {
min-height: 36px;
padding: 0 16px;
margin-right: 4px;
padding: 0 7px;
margin-right: 0;
color: #606163;
background-color: transparent;
border: 0;
@@ -189,6 +190,18 @@ QDialog#AiConsultDialog QTabBar#AiConsultTabs::tab:selected {
font-weight: 600;
border-bottom: 2px solid #4F63D9;
}
QDialog#AiConsultDialog QPushButton#AiConsultChatFilter {
min-height: 30px;
padding: 0 12px;
color: #4F63D9;
background-color: #FFFFFF;
border: 1px solid #E1E5F4;
border-radius: 8px;
font-size: 13px;
}
QDialog#AiConsultDialog QPushButton#AiConsultChatFilter:hover {
background-color: #EEF1FA;
}
QDialog#AiConsultDialog QFrame#AiConsultChatPane,
QDialog#AiConsultDialog QFrame#AiConsultSide,
QDialog#AiConsultDialog QFrame#AiConsultRecordPane {
@@ -483,6 +496,22 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalDisclaimer {
font-size: 13px;
font-weight: 400;
}
QDialog#AiConsultDialog QFrame#AiConsultReportProvenance {
background-color: #F7F8FC;
border: 1px solid #E4E8F2;
border-radius: 9px;
}
QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceTitle {
color: #27336B;
background-color: transparent;
font-size: 12px;
font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceLine {
color: #555B68;
background-color: transparent;
font-size: 12px;
}
QDialog#AiConsultDialog QFrame#AiConsultEventCard {
background-color: #F7F7F7;
border: 1px solid #EDEDEE;
@@ -637,6 +666,13 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] {
font-size: 13px;
font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultTag[level="unknown"] {
color: #6A6B6D;
background-color: #F0F0F0;
border-radius: 8px;
padding: 2px 8px;
font-size: 13px;
}
QDialog#AiConsultDialog QPushButton#AiConsultChipButton {
min-height: 28px;
max-height: 30px;
@@ -854,6 +890,11 @@ QUICK_PROMPTS: tuple[tuple[str, str], ...] = (
("并发症风险评估", "请评估并发症风险并给出随访要点。"),
("生成问诊问题", "请生成接下来应向患者确认的关键问诊问题。"),
)
AI_PRESCRIPTION_PERMISSION = "tcm.diagnosis/aiGeneratePrescription"
PRESCRIPTION_CREATE_PERMISSIONS = (
"tcm.diagnosis/chufang",
"tcm.diagnosis/kaifang",
)
TOOL_ITEMS: tuple[tuple[str, str, str], ...] = (
("chart", "分析病历", "请根据当前病历给出辨证与病情摘要。"),
("trend", "血糖趋势", "请评估该患者的血糖控制情况与趋势。"),
@@ -2104,6 +2145,26 @@ def parse_structured_report(raw: Any) -> tuple[str, tuple[_ReportSection, ...],
)
def _report_provenance_widget(raw: Any, parent: QWidget) -> QFrame:
card = QFrame(parent)
card.setObjectName("AiConsultReportProvenance")
_style_surface(card)
layout = QVBoxLayout(card)
layout.setContentsMargins(12, 10, 12, 11)
layout.setSpacing(4)
title = QLabel("报告出处", card)
title.setObjectName("AiConsultReportProvenanceTitle")
layout.addWidget(title)
for line in report_provenance_lines(raw):
label = QLabel(line, card)
label.setObjectName("AiConsultReportProvenanceLine")
label.setWordWrap(True)
label.setTextFormat(Qt.TextFormat.PlainText)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
layout.addWidget(label)
return card
_InsightItem = namedtuple("_InsightItem", "kind marker label text")
_INSIGHT_LIST_RE = re.compile(r"^\s*(\d{1,2})\s*([\.、))]\s*)")
@@ -2409,6 +2470,7 @@ class _StructuredReportPanel(QWidget):
disclaimer: str,
*,
time_text: str = "",
provenance: Any = None,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
@@ -2455,6 +2517,7 @@ class _StructuredReportPanel(QWidget):
note = _FittedText(_reading_html(disclaimer), parent=self)
note.setObjectName("AiConsultReportDisclaimer")
root.addWidget(note)
root.addWidget(_report_provenance_widget(provenance, self))
# 富余高度归到底部,否则会被平摊进每张卡片,把报告拉得空空荡荡。
root.addStretch(1)
@@ -2528,6 +2591,7 @@ class _ClinicalAnalysisPanel(QWidget):
model: _ClinicalAnalysisModel,
*,
time_text: str = "",
provenance: Any = None,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
@@ -2621,6 +2685,7 @@ class _ClinicalAnalysisPanel(QWidget):
disclaimer.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
_style_surface(disclaimer)
root.addWidget(disclaimer)
root.addWidget(_report_provenance_widget(provenance, self))
QTimer.singleShot(0, self._apply_responsive_layout)
def set_time_text(self, time_text: str) -> None:
@@ -2844,6 +2909,7 @@ class _ChatBubble(QWidget):
super().__init__(parent)
self._role = role
self._raw_payload = text
self._provenance: Mapping[str, Any] = {}
self._clinical_panel: _ClinicalAnalysisPanel | None = None
row = QHBoxLayout(self)
row.setContentsMargins(12, 7, 12, 7)
@@ -2914,6 +2980,9 @@ class _ChatBubble(QWidget):
if self.body is not None:
self.body.set_payload(text)
def set_provenance(self, value: Any) -> None:
self._provenance = dict(value) if isinstance(value, Mapping) else {}
def set_time_text(self, text: str) -> None:
if not text:
return
@@ -2934,6 +3003,7 @@ class _ChatBubble(QWidget):
panel = _ClinicalAnalysisPanel(
model,
time_text=self.stamp.text(),
provenance=self._provenance,
parent=self._bubble_frame,
)
else:
@@ -2944,6 +3014,7 @@ class _ChatBubble(QWidget):
panel = _StructuredReportPanel(
*report,
time_text=self.stamp.text(),
provenance=self._provenance,
parent=self._bubble_frame,
)
if panel is None:
@@ -3075,6 +3146,8 @@ class _AiStreamWorker(QRunnable):
@Slot()
def run(self) -> None:
try:
if self.is_cancelled():
return
stream = getattr(self.repository, "stream_diagnosis_ai", None)
if callable(stream):
events = stream(
@@ -3098,6 +3171,8 @@ class _AiStreamWorker(QRunnable):
{"event": "delta", "text": answer, "fallback": True},
{**payload, "event": "done", "fallback": True},
)
if self.is_cancelled():
return
for event in events:
if self.is_cancelled():
return
@@ -3136,13 +3211,18 @@ class _ClickCard(QFrame):
AI_CONTEXT_MAX_CHARS = 320
AI_PROMPT_LIMIT = 500
#: 首个增量到达前显示的占位文案,避免留下一块没有任何说明的空白气泡。
AI_STREAM_PENDING_TEXT = "正在生成…"
#: 等待服务端整理诊单资料时显示的占位文案。
AI_STREAM_PENDING_TEXT = "正在整理诊单资料…"
#: 服务端确认资料已准备好、尚未收到回答时显示的占位文案。
AI_STREAM_WAITING_TEXT = "资料已整理,正在等待 AI 回复…"
#: 连接结束但一个字都没收到时的兜底文案。
AI_STREAM_SILENT_TEXT = (
"AI 助手没有返回内容,可能是服务端未响应或连接中断,请稍后重试。"
)
AI_STREAM_TOTAL_TIMEOUT_MS = 180_000
AI_STREAM_TIMEOUT_TEXT = "等待 AI 回复超时,已停止本次等待,请稍后重试。"
AI_CONTEXT_SEPARATOR = "\n\n— 医生提问 —\n"
@@ -3458,10 +3538,14 @@ class AiConsultDialog(QDialog):
# done 事件是否到达。用于区分“模型没内容”和“连接直接断了”。
self._stream_completed = False
self._follow_chat = True
self._chat_filter = "all"
self._flush_timer = QTimer(self)
self._flush_timer.setSingleShot(True)
self._flush_timer.setInterval(40)
self._flush_timer.timeout.connect(self._flush_stream_chunks)
self._stream_timeout_timer = QTimer(self)
self._stream_timeout_timer.setSingleShot(True)
self._stream_timeout_timer.timeout.connect(self._stream_timed_out)
self.setObjectName("AiConsultDialog")
self.setWindowTitle("问诊详情")
# QDialog 默认只带关闭按钮,医生无法把这个信息密度很高的窗口放大到整屏。
@@ -3508,6 +3592,7 @@ class AiConsultDialog(QDialog):
self._generation += 1
self._image_generation += 1
self._clear_chat()
self._set_chat_filter("all")
# The AI context envelope depends on workspace data that has not yet
# been fetched, so reset its cache eagerly instead of letting it
# linger from a previous patient session.
@@ -3540,6 +3625,24 @@ class AiConsultDialog(QDialog):
layout = QVBoxLayout(shell)
layout.setContentsMargins(18, 14, 18, 14)
layout.setSpacing(12)
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.setChildrenCollapsible(False)
splitter.addWidget(self._build_center())
splitter.addWidget(self._build_right_pane())
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 0)
splitter.setSizes([920, 460])
layout.addWidget(splitter, 1)
def _build_right_pane(self) -> QWidget:
host = QWidget()
host.setObjectName("AiConsultRightPane")
host.setMinimumWidth(360)
host.setMaximumWidth(480)
layout = QVBoxLayout(host)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
layout.addLayout(self._build_crumb())
layout.addWidget(self._build_hero())
self.tabs = QTabBar()
@@ -3548,15 +3651,31 @@ class AiConsultDialog(QDialog):
self.tabs.addTab(title)
self.tabs.currentChanged.connect(self._tab_changed)
layout.addWidget(self.tabs)
layout.addWidget(self._build_side(), 1)
return host
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.setChildrenCollapsible(False)
splitter.addWidget(self._build_center())
splitter.addWidget(self._build_side())
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 0)
splitter.setSizes([920, 400])
layout.addWidget(splitter, 1)
def _build_chat_filter(self) -> QPushButton:
self.chat_filter_button = QPushButton("筛选")
self.chat_filter_button.setObjectName("AiConsultChatFilter")
self.chat_filter_button.setAccessibleName("筛选问诊对话")
self.chat_filter_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.chat_filter_menu = QMenu(self.chat_filter_button)
for value, label in (
("all", "全部对话"),
("patient", "患者消息"),
("doctor", "医生消息"),
("ai", "AI 助手消息"),
("system", "系统事件"),
):
action = self.chat_filter_menu.addAction(label)
action.setData(value)
action.setCheckable(True)
action.setChecked(value == "all")
action.triggered.connect(
lambda _checked=False, role=value: self._set_chat_filter(role)
)
self.chat_filter_button.setMenu(self.chat_filter_menu)
return self.chat_filter_button
def _build_crumb(self) -> QHBoxLayout:
row = QHBoxLayout()
@@ -3572,6 +3691,7 @@ class AiConsultDialog(QDialog):
current.setObjectName("AiConsultCrumbCurrent")
row.addWidget(current)
row.addStretch(1)
row.addWidget(self._build_chat_filter())
back = QPushButton("返回")
back.setObjectName("AiConsultBack")
back.clicked.connect(self.reject)
@@ -3582,9 +3702,11 @@ class AiConsultDialog(QDialog):
card = QFrame()
card.setObjectName("AiConsultHero")
_style_surface(card)
row = QHBoxLayout(card)
row.setContentsMargins(16, 14, 16, 14)
row.setSpacing(14)
body = QVBoxLayout(card)
body.setContentsMargins(14, 12, 14, 12)
body.setSpacing(8)
row = QHBoxLayout()
row.setSpacing(10)
self.avatar = QLabel("患")
self.avatar.setObjectName("AiConsultAvatar")
self.avatar.setFixedSize(44, 44)
@@ -3599,13 +3721,14 @@ class AiConsultDialog(QDialog):
self.identity_label = QLabel("")
self.identity_label.setObjectName("AiConsultMeta")
info.addWidget(self.identity_label)
self.chip_row = _FlowRow()
info.addWidget(self.chip_row)
row.addLayout(info, 1)
full = QPushButton("查看完整资料")
full.setObjectName("AiConsultFullRecord")
full.clicked.connect(self._open_full_record)
row.addWidget(full, 0, Qt.AlignmentFlag.AlignTop)
body.addLayout(row)
self.chip_row = _FlowRow()
body.addWidget(self.chip_row)
return card
def _build_center(self) -> QWidget:
@@ -3662,6 +3785,8 @@ class AiConsultDialog(QDialog):
hint.setObjectName("AiConsultComposerLabel")
chips.addWidget(hint)
for label, prompt in QUICK_PROMPTS[:3]:
if label == "AI 生成处方" and not self._can_generate_ai_prescription():
continue
button = QPushButton(label)
button.setObjectName("AiConsultChipButton")
button.setCursor(Qt.CursorShape.PointingHandCursor)
@@ -3808,7 +3933,6 @@ class AiConsultDialog(QDialog):
side.setObjectName("AiConsultSide")
_style_surface(side)
side.setMinimumWidth(350)
side.setMaximumWidth(420)
outer = QVBoxLayout(side)
outer.setContentsMargins(18, 16, 18, 16)
outer.setSpacing(14)
@@ -3911,6 +4035,32 @@ class AiConsultDialog(QDialog):
def _tab_changed(self, index: int) -> None:
self.center_stack.setCurrentIndex(index)
self.chat_filter_button.setVisible(index == 0)
def _set_chat_filter(self, role: str) -> None:
self._chat_filter = role
label = "全部对话"
for action in self.chat_filter_menu.actions():
selected = action.data() == role
action.setChecked(selected)
if selected:
label = action.text()
self.chat_filter_button.setText(
"筛选" if role == "all" else f"筛选:{label}"
)
for index in range(self.chat_layout.count() - 1):
widget = self.chat_layout.itemAt(index).widget()
if widget is not None:
widget.setVisible(self._chat_item_matches_filter(widget))
def _chat_item_matches_filter(self, widget: QWidget) -> bool:
if self._chat_filter == "all":
return True
if isinstance(widget, _ChatEvent):
return self._chat_filter == "system"
if isinstance(widget, _ChatBubble):
return widget._role == self._chat_filter
return True
def _clear_chat(self) -> None:
while self.chat_layout.count() > 1:
@@ -3932,6 +4082,7 @@ class AiConsultDialog(QDialog):
) -> _ChatBubble:
bubble = _ChatBubble(role=role, text=text, time_text=time_text, extra=extra)
self.chat_layout.insertWidget(self.chat_layout.count() - 1, bubble)
bubble.setVisible(self._chat_item_matches_filter(bubble))
if self._follow_chat:
QTimer.singleShot(0, self._scroll_chat_to_bottom)
return bubble
@@ -3953,6 +4104,7 @@ class AiConsultDialog(QDialog):
marker=marker,
)
self.chat_layout.insertWidget(self.chat_layout.count() - 1, event)
event.setVisible(self._chat_item_matches_filter(event))
if self._follow_chat:
QTimer.singleShot(0, self._scroll_chat_to_bottom)
return event
@@ -4550,6 +4702,7 @@ class AiConsultDialog(QDialog):
time_text=item.time_text,
)
if item.role == "ai":
bubble.set_provenance(row)
bubble.finalize_clinical_analysis()
def _render_analysis(self, analysis: Mapping[str, Any]) -> None:
@@ -4564,51 +4717,25 @@ class AiConsultDialog(QDialog):
)
top_risk = risk_rows[0] if risk_rows else {}
risk_label = display_text(first_value(top_risk, "label"), "")
risk_level = str(first_value(top_risk, "level", default="medium") or "medium")
risk_level = str(first_value(top_risk, "level", default="unknown") or "unknown")
if risk_level not in {"high", "medium", "low"}:
risk_level = "medium"
level_text = {"high": "高风险", "medium": "中风险", "low": "低风险"}[risk_level]
diagnosis = _as_mapping(get_value(self._detail, "diagnosis", default=self._detail) or self._seed)
appointment = _as_mapping(get_value(self._detail, "appointment", default={}))
clinical = display_text(
_pick(("clinical_diagnosis", "diagnosis_name"), diagnosis, appointment, self._seed),
"",
)
complaint = display_text(_pick(("chief_complaint",), diagnosis, self._seed), "")
glucose = _pick(("fasting_blood_sugar",), diagnosis, appointment, self._seed)
glucose_number = _as_float(glucose)
if not advice:
advice = _join_meta(clinical, f"主诉 {complaint}" if complaint else "") or "结合现有病历评估证候与病情。"
if not risk_label:
if glucose_number is not None and glucose_number >= 7.0:
risk_label, risk_level, level_text = "高血糖风险", "high", "高风险"
elif glucose_number is not None and glucose_number >= 6.1:
risk_label, risk_level, level_text = "血糖波动风险", "medium", "中风险"
else:
risk_label, risk_level, level_text = "需持续随访", "low", "低风险"
if not treatment:
treatment = "结合处方、依从性与最新检验结果评估是否需要调整用药。"
markdown = _analysis_markdown(
{
"diagnosis_advice": advice,
"treatment_advice": treatment,
"risk_assessment": risk_rows
or [{"label": risk_label, "level": risk_level}],
}
)
risk_level = "unknown"
level_text = {"high": "高风险", "medium": "中风险", "low": "低风险", "unknown": "未提供"}[risk_level]
if not advice and not treatment and not risk_rows:
self._set_insights(
[("分析状态", "当前诊单暂无可用的 AI 分析报告,请重新分析后查看。", "未生成", "unknown")]
)
return
markdown = _analysis_markdown(payload)
if markdown:
bubble = self._append_bubble("ai", markdown)
bubble.set_provenance(payload)
bubble.finalize_clinical_analysis()
glucose_tag, glucose_level = (
("未达标", "warn")
if "高血糖" in risk_label or risk_level == "high"
else ("需关注", "low")
)
self._set_insights(
[
("血糖控制评估", advice, glucose_tag, glucose_level),
("并发症风险评估", risk_label, level_text, risk_level),
("用药合理性评估", treatment, "需关注", "low"),
("血糖控制评估", advice or "报告未提供此项分析。", "已分析" if advice else "未提供", "low" if advice else "unknown"),
("并发症风险评估", risk_label or "报告未列出风险项。", level_text, risk_level),
("用药合理性评估", treatment or "报告未提供此项分析。", "已分析" if treatment else "未提供", "low" if treatment else "unknown"),
]
)
@@ -5464,6 +5591,13 @@ class AiConsultDialog(QDialog):
def _submit(self) -> None:
self._ask(self.input.text())
def _can_generate_ai_prescription(self) -> bool:
return has_permission(
self.permissions, AI_PRESCRIPTION_PERMISSION, default=False
) and has_permission(
self.permissions, PRESCRIPTION_CREATE_PERMISSIONS, default=False
)
def _handle_local_action(self, text: str) -> bool:
if not _is_open_prescription_intent(text):
return False
@@ -5474,9 +5608,8 @@ class AiConsultDialog(QDialog):
text,
time_text=datetime.now().strftime("%H:%M"),
)
can_prescribe = any(
has_permission(self.permissions, code, default=False)
for code in ("tcm.diagnosis/chufang", "tcm.diagnosis/kaifang")
can_prescribe = has_permission(
self.permissions, PRESCRIPTION_CREATE_PERMISSIONS, default=False
)
if not can_prescribe:
self._append_bubble(
@@ -5485,6 +5618,15 @@ class AiConsultDialog(QDialog):
time_text="系统",
)
return True
if not has_permission(
self.permissions, AI_PRESCRIPTION_PERMISSION, default=False
):
self._append_bubble(
"ai",
"当前账号没有 AI 生成处方权限,无法生成处方草稿。",
time_text="系统",
)
return True
if not callable(getattr(self.repository, "create_prescription", None)):
self._append_bubble(
"ai",
@@ -5898,6 +6040,7 @@ class AiConsultDialog(QDialog):
worker.signals.finished.connect(
lambda: self._stream_finished(generation, stream_generation, worker)
)
self._stream_timeout_timer.start(AI_STREAM_TOTAL_TIMEOUT_MS)
QThreadPool.globalInstance().start(worker)
QTimer.singleShot(0, self._scroll_chat_to_bottom)
@@ -5916,6 +6059,8 @@ class AiConsultDialog(QDialog):
kind = str(payload.get("event") or "").lower()
if kind == "start":
self._stream_meta.update(payload)
if self._stream_bubble is not None and not self._stream_text and not self._pending_chunks:
self._stream_bubble.set_payload(AI_STREAM_WAITING_TEXT)
return
if kind == "delta":
chunk = payload.get("text")
@@ -5928,6 +6073,7 @@ class AiConsultDialog(QDialog):
return
self._stream_meta.update(payload)
self._stream_completed = True
self._stream_timeout_timer.stop()
if not self._stream_text and not self._pending_chunks:
answer = first_value(payload, "answer", "content", default="")
if answer not in (None, ""):
@@ -5944,6 +6090,7 @@ class AiConsultDialog(QDialog):
self._stream_bubble.set_time_text(
_join_meta(model, datetime.now().strftime("%H:%M"))
)
self._stream_bubble.set_provenance(self._stream_meta)
self._stream_bubble.finalize_clinical_analysis()
def _flush_stream_chunks(self) -> None:
@@ -5963,6 +6110,7 @@ class AiConsultDialog(QDialog):
) -> None:
if not self._stream_is_current(generation, stream_generation):
return
self._stream_timeout_timer.stop()
self._flush_stream_chunks()
message = friendly_error(error)
if self._stream_text:
@@ -5981,10 +6129,11 @@ class AiConsultDialog(QDialog):
) -> None:
if not self._stream_is_current(generation, stream_generation):
return
self._stream_timeout_timer.stop()
if self._stream_worker is worker:
self._stream_worker = None
# 连接结束却既没有 done 也没有报错时(服务端静默断开),占位气泡会永远
# 停在“正在生成…”。这里补一条明确说明,而不是留一块空白卡片。
# 连接结束却既没有 done 也没有报错时(服务端静默断开),
# 将阶段占位文案替换成明确说明。
if (
not self._stream_completed
and not self._stream_text
@@ -5996,9 +6145,23 @@ class AiConsultDialog(QDialog):
self._asking = False
self.send_button.setEnabled(True)
def _stream_timed_out(self) -> None:
if not self._asking or self._stream_completed:
return
self._flush_stream_chunks()
bubble = self._stream_bubble
text = self._stream_text
self._cancel_stream()
if bubble is not None:
bubble.set_payload(
f"{text}\n\n> {AI_STREAM_TIMEOUT_TEXT}" if text else AI_STREAM_TIMEOUT_TEXT
)
bubble.set_time_text(datetime.now().strftime("%H:%M"))
def _cancel_stream(self) -> None:
self._stream_generation += 1
self._flush_timer.stop()
self._stream_timeout_timer.stop()
if self._stream_worker is not None:
self._stream_worker.cancel()
self._stream_worker = None
@@ -67,6 +67,7 @@ from ..diagnosis_media import (
safe_image_sources,
)
from ..infinite_list import InfiniteList
from ..theme import main_window_target_rect
from ..widgets import (
display_text,
first_value,
@@ -716,6 +717,11 @@ class OrderDetailDrawer(QDialog):
QTimer.singleShot(0, self.sync_to_owner)
def sync_to_owner(self) -> None:
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
self.drawer_panel.setFixedWidth(max(1, round(target.width() * self.drawer_ratio)))
return
owner = self._owner
if owner is None:
self.resize(1152, 720)
@@ -1836,6 +1842,10 @@ class DiagnosisDialog(QDialog):
def _sync_host_geometry(self) -> None:
if self._embedded:
return
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
return
owner = self._owner
if owner is None:
if self.width() < 760 or self.height() < 520:
@@ -33,6 +33,7 @@ from PySide6.QtWidgets import (
from ...core.errors import AuthenticationExpiredError
from ..reception_style import body_family
from ..report_provenance import report_provenance_lines
from ..widgets import first_value, format_record_time, friendly_error, has_permission, run_async
from .issued_prescription_ai_console import AgreementBar, StepRail, rail_qss
from .issued_prescription_ai_glyphs import Glyph, LogoTile, glyph_icon
@@ -1414,7 +1415,14 @@ class IssuedPrescriptionAiDialog(QDialog):
comparison_html += "<p class=sec>逐味贡献</p>" + _html(_comparison_rows(comparison.get("rows")) or "没有可展示的逐味对照。")
comparison_html += _html({field: value for field, value in comparison.items() if field not in {"score", "herb_score", "rows"}})
_set_html(views["comparison"], comparison_html)
_set_html(views["sources"], _html({"source_summary": batch.get("source_summary"), "missing": batch.get("missing"), "coverage": model.get("coverage"), "baseline_eligible": batch.get("baseline_eligible"), "baseline_exclusion_reasons": batch.get("baseline_exclusion_reasons"), "cutoff_at": format_record_time(batch.get("cutoff_at")), "generated_at": format_record_time(model.get("generated_at"))}))
source_html = _html({"source_summary": batch.get("source_summary"), "missing": batch.get("missing"), "coverage": model.get("coverage"), "baseline_eligible": batch.get("baseline_eligible"), "baseline_exclusion_reasons": batch.get("baseline_exclusion_reasons"), "cutoff_at": format_record_time(batch.get("cutoff_at")), "generated_at": format_record_time(model.get("generated_at"))})
reference_lines = [line for line in report_provenance_lines(model)
if line.startswith(("知识参考:", "参考章节:", "原文:", "古籍参考:"))]
if reference_lines:
source_html += '<p class="sec">文献出处</p>' + "".join(
"<p>" + escape(line) + "</p>" for line in reference_lines
)
_set_html(views["sources"], source_html)
if first_load and not self._pending_drafts:
review = mapping(model.get("review"))
views["comment"].setPlainText(str(review.get("comment") or ""))
@@ -93,6 +93,7 @@ from PySide6.QtWidgets import (
from .. import icons
from ..diagnosis_terms import shared_terms
from ..infinite_list import InfiniteList
from ..theme import main_window_target_rect
from ..widgets import (
MessageBanner,
display_text,
@@ -3306,6 +3307,17 @@ class PrescriptionEditorDialog(QDialog):
self._fit_drawer_geometry()
def _fit_drawer_geometry(self) -> None:
target = main_window_target_rect(self)
if target is not None:
width = target.width()
self.drawer_surface.setMaximumWidth(max(self.DRAWER_WIDTH, width))
self.setGeometry(target)
if self.diagnosis_host.isVisible():
editor_width = min(self.DRAWER_WIDTH, max(520, round(width * 0.55)))
self.workspace_splitter.setSizes([max(300, width - editor_width - 1), editor_width])
else:
self.workspace_splitter.setSizes([0, width])
return
parent = self.parentWidget()
if parent is None:
return
@@ -26,6 +26,7 @@ from PySide6.QtWidgets import (
QWidget,
)
from ..report_provenance import report_provenance_lines
from ..theme import apply_reading_rhythm
from ..widgets import (
EmptyState,
@@ -1413,8 +1414,22 @@ class PrescriptionAiReportDialog(QDialog):
or "仅供专业人员辅助审方,不替代辨证、诊断和处方审核。"
)
self._add_label(disclaimer, "PrescriptionAiMuted")
self._add_report_provenance(data)
return
self._section("报告正文", str(data.get("content") or "暂无报告正文"))
self._add_report_provenance(data)
def _add_report_provenance(self, data: dict[str, Any]) -> None:
if self.kind is not DIAGNOSIS_AI_KIND:
return
lines = [f"关联诊单:#{self._entity_id()}", *report_provenance_lines(data)]
label = QLabel("报告出处\n" + "\n".join(lines))
label.setObjectName("DiagnosisAiReportProvenance")
label.setTextFormat(Qt.TextFormat.PlainText)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
label.setWordWrap(True)
label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
self.host_layout.addWidget(label)
def reject(self) -> None:
self.dialog_generation += 1
@@ -1464,6 +1479,13 @@ class DiagnosisAiAssistantDialog(QDialog):
self.answer_label = _AiAnswerBrowser()
self.answer_scroll = self.answer_label
root.addWidget(self.answer_scroll, 1)
self.source_label = QLabel("")
self.source_label.setObjectName("DiagnosisAiAssistantProvenance")
self.source_label.setTextFormat(Qt.TextFormat.PlainText)
self.source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.source_label.setWordWrap(True)
self.source_label.setVisible(False)
root.addWidget(self.source_label)
actions = QHBoxLayout()
actions.addStretch(1)
self.retry_button = QPushButton("重试")
@@ -1481,6 +1503,8 @@ class DiagnosisAiAssistantDialog(QDialog):
self.question_label.setText(f"问题:{self.prompt}")
self.answer_label.clear()
self.model_label.clear()
self.source_label.clear()
self.source_label.hide()
self._ask()
def _ask(self) -> None:
@@ -1519,6 +1543,8 @@ class DiagnosisAiAssistantDialog(QDialog):
)
self.model_label.setText(f"本次模型:{model}")
self.answer_label.set_answer(answer)
self.source_label.setText("分析出处:" + ";".join(report_provenance_lines(payload)))
self.source_label.show()
self.status_banner.show_message("分析完成", "success")
self.loading = False
self.retry_button.setEnabled(True)
@@ -1527,6 +1553,7 @@ class DiagnosisAiAssistantDialog(QDialog):
if generation != self.request_generation:
return
self.status_banner.show_message(error_message(error), "danger")
self.source_label.hide()
self.loading = False
self.retry_button.setEnabled(True)
@@ -89,6 +89,7 @@ from ..dialogs.prescription_ai import (
)
from ..filter_disclosure import FilterDisclosure
from ..reception_style import body_family, heading_family, number_family
from ..report_provenance import report_provenance_lines
from ..theme import mark_business_dialog
from ..widgets import (
EmptyState,
@@ -3335,6 +3336,14 @@ class _ReceptionAiAnalysisDialog(QDialog):
"",
"ReceptionAiAnalysisDialogTreatmentText",
)
source_label = QLabel("", body)
source_label.setObjectName("ReceptionAiAnalysisDialogSources")
source_label.setTextFormat(Qt.TextFormat.PlainText)
source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
source_label.setWordWrap(True)
source_label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
body_layout.addWidget(source_label)
self.source_label = source_label
body_layout.addStretch(1)
scroll.setWidget(body)
surface_layout.addWidget(scroll, 1)
@@ -3525,6 +3534,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
" | ".join(part for part in (model, f"第 {version} 版", generated_at) if part)
)
self.meta_label.setVisible(bool(self.meta_label.text()))
self.source_label.setText("报告出处\n" + "\n".join(report_provenance_lines(payload)))
self.scroll_area.verticalScrollBar().setValue(0)
@@ -5198,6 +5208,13 @@ class ReceptionPage(QWidget):
state_layout.addStretch(1)
self.ai_analysis_stack.addWidget(analysis_state)
analysis_layout.addWidget(self.ai_analysis_stack)
self.ai_source_label = QLabel("", analysis_card)
self.ai_source_label.setObjectName("ReceptionAiSourceSummary")
self.ai_source_label.setTextFormat(Qt.TextFormat.PlainText)
self.ai_source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.ai_source_label.setWordWrap(True)
self.ai_source_label.setStyleSheet("color: #5B6474; font-size: 11px;")
analysis_layout.addWidget(self.ai_source_label)
self.ai_detail_actions_host = QWidget(analysis_card)
report_footer = QHBoxLayout(self.ai_detail_actions_host)
@@ -5432,6 +5449,7 @@ class ReceptionPage(QWidget):
self.ai_analysis_stack.setCurrentWidget(
self.ai_analysis_content_page if success else self.ai_analysis_state_page
)
self.ai_source_label.setVisible(success)
if success and payload is not None:
if (
self._ai_analysis_rendered_model != model
@@ -5559,6 +5577,9 @@ class ReceptionPage(QWidget):
)
self.ai_analysis_snapshot_meta.setVisible(bool(meta_text))
self.ai_analysis_card.setToolTip("")
source_lines = report_provenance_lines(payload)
self.ai_source_label.setText("报告出处:" + ";".join(source_lines[:2]))
self.ai_source_label.setToolTip("\n".join(source_lines))
def _render_ai_risk_chips(self, risks: Sequence[Mapping[str, Any]]) -> None:
_clear_ai_layout(self.ai_risk_chip_layout)
@@ -0,0 +1,142 @@
"""Human-readable, server-recorded source scope for clinical AI reports."""
from __future__ import annotations
import re
from collections.abc import Mapping
from typing import Any
from urllib.parse import unquote
_REPORT_SOURCE_COUNTS = (
("diagnosis_count", "诊单"),
("doctor_note_count", "医生备注"),
("tracking_note_count", "随访记录"),
("blood_record_count", "血糖血压记录"),
("diet_record_count", "饮食记录"),
("exercise_record_count", "运动记录"),
("prescription_count", "历史处方"),
("im_message_count", "IM 消息"),
("wechat_message_count", "企微消息"),
("call_record_count", "视频问诊"),
("transcript_segment_count", "视频转写片段"),
)
_NIHAIXIA_SOURCE_URL = "https://github.com/coinweth/nihaixia-skill"
_NIHAIXIA_COMMIT = "270e94e637c4249dc411e54ac6715f21247de3cb"
_ANCIENT_BOOKS_COMMIT = "db0155dc7c42b9c6b3736896661f317c7110038f"
_ANCIENT_BOOKS_URL = "https://github.com/xiaopangxia/TCM-Ancient-Books"
def _source_text(value: Any, limit: int) -> str:
"""Keep displayed source metadata brief and free of repository links."""
text = re.sub(r"https://github\.com(?:/[^\s,。;、」)》\]]*)?", "", str(value or ""))
return " ".join(text.split())[:limit]
def report_provenance_lines(raw: Any) -> tuple[str, ...]:
"""Describe recorded inputs; never turn model prose into a claimed citation."""
report = raw if isinstance(raw, Mapping) else {}
lines: list[str] = []
ids = report.get("source_diagnosis_ids")
diagnosis_ids = [
value for value in ids if type(value) is int and value > 0
] if isinstance(ids, (list, tuple)) else []
if diagnosis_ids:
shown = "、".join(f"#{value}" for value in diagnosis_ids[:12])
lines.append("来源诊单:" + shown + (" 等" if len(diagnosis_ids) > 12 else ""))
summary = report.get("source_summary")
counts = []
if isinstance(summary, Mapping):
for key, label in _REPORT_SOURCE_COUNTS:
value = summary.get(key)
if type(value) is int and value > 0:
counts.append(f"{label} {value} 条")
if counts:
lines.append("患者资料范围:" + "、".join(counts))
elif isinstance(summary, Mapping) and type(summary.get("source_record_count")) is int and summary["source_record_count"] > 0:
lines.append(f"患者资料范围:记录 {summary['source_record_count']} 条,分类未记录")
elif not diagnosis_ids:
lines.append("患者资料范围:此报告未附可核查的来源清单")
knowledge = report.get("knowledge_source")
url = knowledge.get("url") if isinstance(knowledge, Mapping) else None
legacy_source_match = re.fullmatch(
re.escape(_NIHAIXIA_SOURCE_URL) + r"/blob/([0-9a-f]{40})/SKILL\.md",
url,
) if isinstance(url, str) else None
valid_knowledge = isinstance(knowledge, Mapping) and knowledge.get("commit") == _NIHAIXIA_COMMIT and (
(url in (None, "") and knowledge.get("path") == "SKILL.md")
or (
legacy_source_match is not None
and legacy_source_match.group(1) == _NIHAIXIA_COMMIT
and knowledge.get("path") in (None, "SKILL.md")
)
)
if valid_knowledge:
lines.append(
"知识参考:倪海厦临床参考 Skill;本地资料:"
"server/knowledge/nihaixia-skill/SKILL.md"
+ f"(版本 {_NIHAIXIA_COMMIT[:12]})"
)
sections = knowledge.get("sections")
allowed_sections = {"六经速查表", "六经辨证诊断公式", "七步走辨证思维模式"}
if isinstance(sections, (list, tuple)) and sections and all(
isinstance(item, str) and item in allowed_sections for item in sections
):
lines.append("参考章节:" + "、".join(sections))
else:
lines.append("知识参考:此报告未记录所用知识资料版本")
ancient_sources = report.get("ancient_book_sources")
shown_sources: set[tuple[str, int]] = set()
if isinstance(ancient_sources, (list, tuple)):
for source in ancient_sources[:12]:
if not isinstance(source, Mapping) or source.get("commit") != _ANCIENT_BOOKS_COMMIT:
continue
ancient_url = source.get("url")
filename = source.get("path")
line_number = source.get("line")
if ancient_url not in (None, ""):
legacy_match = re.fullmatch(
re.escape(_ANCIENT_BOOKS_URL)
+ r"/blob/"
+ _ANCIENT_BOOKS_COMMIT
+ r"/([^/#?]+\.txt)#L([1-9]\d{0,8})",
ancient_url,
) if isinstance(ancient_url, str) else None
if legacy_match is None:
continue
legacy_filename = unquote(legacy_match.group(1))
legacy_line = int(legacy_match.group(2))
if filename not in (None, legacy_filename) or line_number not in (None, legacy_line):
continue
filename, line_number = legacy_filename, legacy_line
if not (
isinstance(filename, str)
and re.fullmatch(r"[^/\\\x00-\x1f]{1,255}\.txt", filename)
and type(line_number) is int
and 0 < line_number < 1_000_000_000
):
continue
source_key = (filename, line_number)
if source_key in shown_sources:
continue
shown_sources.add(source_key)
title = _source_text(source.get("title"), 60) or "古籍原文"
chapter = _source_text(source.get("chapter"), 60)
excerpt = _source_text(source.get("excerpt"), 120)
lines.append(
"古籍参考:《" + title + "》"
+ ("「" + chapter + "」" if chapter else "")
+ f";本地资料:server/knowledge/tcm-ancient-books/{filename}"
+ f" 第{line_number}行(版本 {_ANCIENT_BOOKS_COMMIT[:12]})"
+ (";摘录:" + excerpt if excerpt else "")
)
if not shown_sources and "-ancient-" in str(
report.get("prompt_version") or report.get("context_version") or ""
):
lines.append("古籍参考:本次未记录可核查的古籍片段")
if report.get("is_edited") is True:
lines.append("人工编辑:报告生成后已修改,来源范围仅对应原始生成版本。")
lines.append("以上列出本次输入范围与知识参考,不代表每条结论均有逐项引用。")
return tuple(lines)
+1
View File
@@ -885,6 +885,7 @@ class ShellWindow(QMainWindow):
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setProperty("doctorMainWindow", True)
self.setWindowTitle("甄养堂 · 问诊中心")
self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
# The ground paints its own rounded corner, so everything outside that
+78 -1
View File
@@ -8,7 +8,7 @@ from pathlib import Path
from string import Template
from typing import Any
from PySide6.QtCore import QEvent, QObject, QPointF, Qt
from PySide6.QtCore import QEvent, QObject, QPointF, QRect, Qt
from PySide6.QtGui import (
QColor,
QFont,
@@ -33,6 +33,7 @@ from PySide6.QtWidgets import (
QScrollArea,
QTextBrowser,
QTextEdit,
QWidget,
)
from doctor_workstation.resources import resource_path
@@ -1450,6 +1451,73 @@ def mark_business_dialog(dialog: QDialog, object_name: str | None = None) -> Non
_refresh_widget_style(dialog)
def main_window_target_rect(window: QWidget) -> QRect | None:
"""Return a centered rectangle covering 85% of the visible workstation."""
app = QApplication.instance()
if app is None:
return None
main = next(
(
candidate
for candidate in app.topLevelWidgets()
if candidate is not window
and candidate.property("doctorMainWindow")
and candidate.isVisible()
),
None,
)
if main is None:
return None
main_frame = main.frameGeometry()
target_width = max(1, round(main_frame.width() * 0.85))
target_height = max(1, round(main_frame.height() * 0.85))
return QRect(
main_frame.center().x() - target_width // 2,
main_frame.center().y() - target_height // 2,
target_width,
target_height,
)
def _size_new_window_to_main(window: QWidget) -> None:
"""Open a business window at 85% of the visible workstation, centered."""
if not window.isWindow() or window.property("doctorMainWindow"):
return
if window.property("doctorSkipOpenGeometry"):
return
if (
isinstance(window, (QMessageBox, QInputDialog, QFileDialog))
or window.metaObject().className() == "QPrintDialog"
):
return
if window.windowFlags() & Qt.WindowType.FramelessWindowHint:
# Drawers have their own owner-sync routines and use the same target rect.
return
target = main_window_target_rect(window)
if target is None:
return
target_width = target.width()
target_height = target.height()
if window.minimumWidth() > target_width:
window.setMinimumWidth(target_width)
if window.minimumHeight() > target_height:
window.setMinimumHeight(target_height)
if window.maximumWidth() < target_width:
window.setMaximumWidth(target_width)
if window.maximumHeight() < target_height:
window.setMaximumHeight(target_height)
window.resize(target_width, target_height)
frame = window.frameGeometry()
window.move(
target.center().x() - frame.width() // 2,
target.center().y() - frame.height() // 2,
)
class _BusinessDialogStyleFilter(QObject):
"""Style dynamically-created Qt dialogs just before they become visible."""
@@ -1490,6 +1558,7 @@ class _BusinessDialogStyleFilter(QObject):
if not self._is_native_or_overlay(watched):
allow_dialog_resize(watched)
elif isinstance(watched, QDialog) and event_type == QEvent.Type.Show:
_size_new_window_to_main(watched)
for button_box in watched.findChildren(QDialogButtonBox):
_polish_dialog_buttons(button_box)
if not self._is_native_or_overlay(watched):
@@ -1505,6 +1574,13 @@ class _BusinessDialogStyleFilter(QObject):
watched.setMinimumWidth(max(watched.minimumWidth(), 460))
elif isinstance(watched, QInputDialog):
watched.setMinimumWidth(max(watched.minimumWidth(), 480))
elif (
isinstance(watched, QWidget)
and event_type == QEvent.Type.Show
and watched.isWindow()
and watched.windowType() == Qt.WindowType.Window
):
_size_new_window_to_main(watched)
return False
@@ -1600,4 +1676,5 @@ __all__ = [
"apply_theme",
"crisp_pixmap",
"mark_business_dialog",
"main_window_target_rect",
]
+228 -3
View File
@@ -8,7 +8,7 @@ from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import Qt
from PySide6.QtCore import QPoint, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import (
QApplication,
@@ -125,6 +125,56 @@ def test_ai_consult_dialog_matches_workspace_chrome(
dialog.close()
def test_header_and_chat_filter_move_to_right_pane_and_filter_message_roles(
application: QApplication,
) -> None:
dialog = AiConsultDialog(
DemoDoctorRepository(), PermissionSet(["tcm.diagnosis/aiAssistant"])
)
patient = dialog._append_bubble("patient", "患者提问")
doctor = dialog._append_bubble("doctor", "医生回复")
ai = dialog._append_bubble("ai", "智能分析")
system = dialog._append_event(title="视频开始")
dialog.show()
application.processEvents()
right_pane = dialog.findChild(QWidget, "AiConsultRightPane")
chat_pane = dialog.findChild(QWidget, "AiConsultChatPane")
assert right_pane is not None and chat_pane is not None
assert right_pane.mapTo(dialog, QPoint(0, 0)).x() >= chat_pane.mapTo(
dialog, QPoint(chat_pane.width(), 0)
).x()
assert dialog.tabs.parentWidget() is right_pane
assert dialog.chat_filter_button.parentWidget() is right_pane
assert right_pane.findChild(QWidget, "AiConsultHero") is not None
assert all(item.isVisible() for item in (patient, doctor, ai, system))
actions = {action.data(): action for action in dialog.chat_filter_menu.actions()}
actions["doctor"].trigger()
application.processEvents()
assert doctor.isVisible()
assert not patient.isVisible()
assert not ai.isVisible()
assert not system.isVisible()
new_doctor = dialog._append_bubble("doctor", "新的医生回复")
new_patient = dialog._append_bubble("patient", "新的患者提问")
application.processEvents()
assert new_doctor.isVisible()
assert not new_patient.isVisible()
actions["all"].trigger()
application.processEvents()
assert all(item.isVisible() for item in (patient, doctor, ai, system, new_doctor, new_patient))
dialog.tabs.setCurrentIndex(1)
application.processEvents()
assert not dialog.chat_filter_button.isVisible()
dialog.tabs.setCurrentIndex(0)
application.processEvents()
assert dialog.chat_filter_button.isVisible()
dialog.close()
@pytest.mark.parametrize("key", [Qt.Key.Key_Return, Qt.Key.Key_Enter])
def test_input_enter_submits_once_without_closing_dialog(
application: QApplication,
@@ -197,6 +247,52 @@ def test_prescription_action_without_permission_does_not_call_ai_or_repository(
dialog.close()
@pytest.mark.parametrize(
("grants", "visible"),
[
(["tcm.diagnosis/aiAssistant"], False),
(["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang"], False),
(["tcm.diagnosis/aiAssistant", "tcm.diagnosis/aiGeneratePrescription"], False),
(["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang", "tcm.diagnosis/aiGeneratePrescription"], True),
],
)
def test_ai_prescription_quick_prompt_requires_both_permissions(
application: QApplication,
grants: list[str],
visible: bool,
) -> None:
dialog = AiConsultDialog(DemoDoctorRepository(), PermissionSet(grants))
buttons = dialog.findChildren(QPushButton, "AiConsultChipButton")
assert ("AI 生成处方" in [button.text() for button in buttons]) is visible
dialog.close()
def test_prescription_action_with_write_permission_but_without_ai_grant_is_blocked(
application: QApplication,
) -> None:
class Repository:
def create_prescription(self, _payload: Any) -> None:
raise AssertionError("must not create without AI prescription permission")
def generate_ai_prescription(self, _diagnosis_id: int) -> None:
raise AssertionError("must not generate without AI prescription permission")
dialog = AiConsultDialog(
Repository(),
PermissionSet(["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang"]),
)
dialog.diagnosis_id = 501
dialog._ask("开个处方")
application.processEvents()
bodies = [
browser.toPlainText()
for browser in dialog.findChildren(QTextBrowser, "AiConsultBubbleText")
]
assert any("没有 AI 生成处方权限" in body for body in bodies)
assert dialog._stream_worker is None
dialog.close()
def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership(
application: QApplication,
immediate_async: None,
@@ -298,7 +394,7 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
dialog = AiConsultDialog(
Repository(),
PermissionSet(
["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang"]
["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang", "tcm.diagnosis/aiGeneratePrescription"]
),
parent=host,
)
@@ -366,7 +462,7 @@ def test_prescription_action_rejects_mismatched_patient_detail(
dialog = AiConsultDialog(
Repository(),
PermissionSet(
["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang"]
["tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang", "tcm.diagnosis/aiGeneratePrescription"]
),
)
dialog.diagnosis_id = 501
@@ -617,6 +713,29 @@ def test_ai_consult_sidebar_loads_patient_facts_and_reports(
dialog.close()
def test_missing_server_analysis_is_not_presented_as_ai_diagnosis(
application: QApplication,
) -> None:
dialog = AiConsultDialog(
DemoDoctorRepository(), PermissionSet(["tcm.diagnosis/aiAssistant"])
)
dialog._seed = {
"clinical_diagnosis": "糖尿病",
"fasting_blood_sugar": 11.2,
}
dialog._render_analysis({})
dialog.show()
application.processEvents()
titles = [
widget.text()
for widget in dialog.findChildren(QLabel, "AiConsultRecordTitle")
]
assert titles == ["分析状态"]
assert not dialog.findChildren(QTextBrowser, "AiConsultBubbleText")
dialog.close()
def test_ai_consult_sidebar_survives_chat_archive_errors(
application: QApplication,
immediate_async: None,
@@ -1372,6 +1491,55 @@ def test_pending_and_silently_closed_streams_never_show_a_blank_bubble(
dialog.close()
def test_stalled_stream_exits_pending_state_and_ignores_late_events(
application: QApplication,
monkeypatch: pytest.MonkeyPatch,
) -> None:
dialog = _silent_dialog(monkeypatch)
dialog.show()
application.processEvents()
dialog._ask("请总结当前病情")
generation, stream_generation = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
worker = dialog._stream_worker
assert bubble is not None and worker is not None
assert dialog._stream_timeout_timer.isActive()
dialog._stream_timed_out()
assert worker.is_cancelled()
assert not dialog._stream_timeout_timer.isActive()
assert not dialog._asking
assert dialog.send_button.isEnabled()
assert bubble._raw_payload == ai_consult_module.AI_STREAM_TIMEOUT_TEXT
calls: list[int] = []
monkeypatch.setattr(
dialog.repository,
"stream_diagnosis_ai",
lambda *args, **kwargs: calls.append(1),
raising=False,
)
worker.run()
assert calls == []
dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "迟到回复"})
dialog._stream_finished(generation, stream_generation, worker)
assert bubble._raw_payload == ai_consult_module.AI_STREAM_TIMEOUT_TEXT
dialog._ask("请补充说明")
second_bubble = dialog._stream_bubble
assert second_bubble is not None
dialog._stream_event(
dialog._generation,
dialog._stream_generation,
{"event": "delta", "text": "已收到部分分析"},
)
dialog._stream_timed_out()
assert second_bubble._raw_payload.startswith("已收到部分分析\n\n>")
assert ai_consult_module.AI_STREAM_TIMEOUT_TEXT in second_bubble._raw_payload
dialog.close()
def test_answered_stream_replaces_the_pending_placeholder(
application: QApplication,
monkeypatch: pytest.MonkeyPatch,
@@ -1382,15 +1550,29 @@ def test_answered_stream_replaces_the_pending_placeholder(
dialog._ask("请总结当前病情")
generation, stream_generation = dialog._generation, dialog._stream_generation
assert dialog._stream_bubble is not None
assert dialog._stream_bubble._raw_payload == ai_consult_module.AI_STREAM_PENDING_TEXT
dialog._stream_event(
generation,
stream_generation,
{"event": "start", "source_summary": {"patient_name": "敏感姓名"}},
)
assert dialog._stream_bubble._raw_payload == ai_consult_module.AI_STREAM_WAITING_TEXT
assert "敏感姓名" not in dialog._stream_bubble._raw_payload
dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "证候:"})
dialog._flush_timer.stop()
dialog._flush_stream_chunks()
assert dialog._stream_bubble._raw_payload == "证候:"
dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "脾肾两虚"})
dialog._stream_event(generation, stream_generation, {"event": "done", "model_label": "千问"})
dialog._stream_finished(generation, stream_generation, dialog._stream_worker)
application.processEvents()
assert dialog._stream_text == "证候:脾肾两虚"
assert not dialog._stream_timeout_timer.isActive()
texts = _bubble_texts(dialog)
assert not any(ai_consult_module.AI_STREAM_PENDING_TEXT in text for text in texts)
assert not any(ai_consult_module.AI_STREAM_WAITING_TEXT in text for text in texts)
assert not any(ai_consult_module.AI_STREAM_SILENT_TEXT in text for text in texts)
dialog.close()
@@ -1522,6 +1704,49 @@ def test_sectioned_reply_becomes_a_structured_report(application: QApplication)
bubble.deleteLater()
def test_structured_report_shows_recorded_patient_and_skill_sources(
application: QApplication,
) -> None:
reply = (
"以下根据当前病历及历史随访资料作初步梳理,请医师结合原始记录复核所有结论,并确认记录时间与患者本人相符。\n"
"1. 病情判断\n- 当前资料尚不足以确认具体证型,仍需补充舌脉与检查资料。\n"
"2. 建议下一步\n- 请核对既往病历、血糖血压记录及随访记录,再决定后续检查与处置。\n"
)
commit = "270e94e637c4249dc411e54ac6715f21247de3cb"
bubble = ai_consult_module._ChatBubble(role="ai", text=reply)
bubble.set_provenance({
"source_diagnosis_ids": [501, 502],
"source_summary": {"diagnosis_count": 2, "blood_record_count": 3},
"knowledge_source": {
"title": "倪海厦 skill",
"url": f"https://github.com/coinweth/nihaixia-skill/blob/{commit}/SKILL.md",
"commit": commit,
"sections": ["六经速查表"],
},
})
assert bubble.finalize_clinical_analysis() is True
card = bubble.findChild(ai_consult_module.QFrame, "AiConsultReportProvenance")
assert card is not None
lines = [label.text() for label in card.findChildren(QLabel)]
assert any("#501" in line and "#502" in line for line in lines)
assert any("诊单 2 条" in line and "血糖血压记录 3 条" in line for line in lines)
assert any("server/knowledge/nihaixia-skill/SKILL.md" in line and "版本 270e94e637c4" in line for line in lines)
assert all("https://github.com" not in line for line in lines)
bubble.deleteLater()
def test_clinical_report_marks_unrecorded_provenance(application: QApplication) -> None:
bubble = ai_consult_module._ChatBubble(role="ai", text=LONG_CLINICAL_REPLY)
assert bubble.finalize_clinical_analysis() is True
card = bubble.findChild(ai_consult_module.QFrame, "AiConsultReportProvenance")
assert card is not None
lines = [label.text() for label in card.findChildren(QLabel)]
assert any("未附可核查的来源清单" in line for line in lines)
assert any("未记录所用知识资料版本" in line for line in lines)
bubble.deleteLater()
@pytest.mark.parametrize(
"reply",
[
+1
View File
@@ -53,6 +53,7 @@ def test_windows_one_click_entrypoints_and_release_pipeline() -> None:
release_launcher = read("packaging/windows/start_release.bat")
assert run_script.index("$FrozenExecutable") < run_script.index("Find-Uv")
assert run_script.index('Write-Host "Using current source tree:') < run_script.index('Write-Host "Using packaged application:')
assert "& $Uv sync --frozen" in run_script
assert '"UV_CACHE_DIR"' in run_script
assert "$ProjectUvCache" in run_script
@@ -1335,6 +1335,34 @@ def test_patient_report_dialog_uses_one_scroll_owner_and_wrapped_risk_flow(
application.processEvents()
def test_reception_report_displays_recorded_sources(application: QApplication) -> None:
commit = "270e94e637c4249dc411e54ac6715f21247de3cb"
payload = _snapshot("qwen", 2, "2026-10-08 15:00:00")
payload.update({
"source_diagnosis_ids": [501],
"source_summary": {"diagnosis_count": 1, "prescription_count": 2},
"knowledge_source": {
"url": f"https://github.com/coinweth/nihaixia-skill/blob/{commit}/SKILL.md",
"commit": commit,
"sections": ["六经速查表"],
},
})
dialog = _ReceptionAiAnalysisDialog({"qwen": [payload]})
assert "#501" in dialog.source_label.text()
assert "历史处方 2 条" in dialog.source_label.text()
assert "六经速查表" in dialog.source_label.text()
assert "server/knowledge/nihaixia-skill/SKILL.md" in dialog.source_label.text()
assert "https://github.com" not in dialog.source_label.text()
page = ReceptionPage(object(), PermissionSet([]))
page._render_ai_analysis_payload(payload, "qwen")
assert "报告出处" in page.ai_source_label.text()
assert "#501" in page.ai_source_label.text()
assert "https://github.com" not in page.ai_source_label.text()
dialog.close()
page.close()
def test_reception_ai_card_is_compact_preview_without_nested_scroll(
application: QApplication,
) -> None:
+1
View File
@@ -308,6 +308,7 @@ def test_diagnosis_dialog_renders_saved_case_report(
assert dialog.snapshot_caption.text() == "完整病历"
assert "肝郁脾虚证" in dialog.snapshot_body.text()
assert any("核心判断" in text for text in labels)
assert any("报告出处" in text and "关联诊单:#501" in text for text in labels)
assert dialog.can_refresh is True
assert not dialog.generate_button.isHidden()
dialog.close()
@@ -0,0 +1,81 @@
from __future__ import annotations
from doctor_workstation.ui.report_provenance import report_provenance_lines
_COMMIT = "db0155dc7c42b9c6b3736896661f317c7110038f"
_URL = (
"https://github.com/xiaopangxia/TCM-Ancient-Books/blob/"
f"{_COMMIT}/123-%E6%B5%8B%E8%AF%95%E5%8F%A4%E7%B1%8D.txt#L42"
)
def test_recorded_ancient_book_reference_has_title_chapter_and_pinned_line() -> None:
lines = report_provenance_lines(
{
"prompt_version": "patient-longitudinal-report-nihaixia-ancient-v4",
"ancient_book_sources": [
{
"title": "测试古籍",
"chapter": "消渴篇",
"path": "123-测试古籍.txt",
"line": 42,
"excerpt": "消渴者,当辨其证。",
"url": _URL,
"commit": _COMMIT,
}
],
}
)
assert any(
"《测试古籍》「消渴篇」" in line
and "server/knowledge/tcm-ancient-books/123-测试古籍.txt 第42行" in line
and "版本 db0155dc7c42" in line
and "摘录:消渴者,当辨其证。" in line
for line in lines
)
assert "https://github.com" not in "\n".join(lines)
def test_locally_bundled_sources_render_without_external_urls() -> None:
lines = report_provenance_lines({
"prompt_version": "patient-longitudinal-report-nihaixia-ancient-v4",
"knowledge_source": {
"commit": "270e94e637c4249dc411e54ac6715f21247de3cb",
"path": "SKILL.md",
"url": "",
},
"ancient_book_sources": [{
"title": "测试古籍",
"chapter": "消渴篇",
"path": "123-测试古籍.txt",
"line": 42,
"excerpt": "消渴者,当辨其证。",
"commit": _COMMIT,
"url": "",
}],
})
assert any("server/knowledge/nihaixia-skill/SKILL.md" in line for line in lines)
assert any("server/knowledge/tcm-ancient-books/123-测试古籍.txt 第42行" in line for line in lines)
assert "https://github.com" not in "\n".join(lines)
def test_ancient_book_reference_rejects_conflicting_local_metadata() -> None:
lines = report_provenance_lines({
"ancient_book_sources": [
{"title": "测试古籍", "path": "别的书.txt", "line": 42, "url": _URL, "commit": _COMMIT},
{"title": "测试古籍", "path": "123-测试古籍.txt", "line": 43, "url": _URL, "commit": _COMMIT},
],
})
assert all("古籍参考:《" not in line for line in lines)
def test_old_or_unverified_report_does_not_gain_ancient_citation() -> None:
lines = report_provenance_lines(
{
"prompt_version": "patient-longitudinal-report-nihaixia-v3",
"ancient_book_sources": [
{"title": "伪造", "url": _URL.replace(_COMMIT, "0" * 40), "commit": _COMMIT}
],
}
)
assert all("古籍参考:《" not in line for line in lines)
+61 -3
View File
@@ -8,7 +8,13 @@ from typing import Any
import pytest
from doctor_workstation.core.errors import ApiBusinessError, ApiHttpError, ApiProtocolError
from doctor_workstation.core.errors import (
ApiBusinessError,
ApiHttpError,
ApiProtocolError,
ApiTimeoutError,
ApiTransportError,
)
from doctor_workstation.core.models import Appointment, Consultation, PageResult, Prescription
from doctor_workstation.services.mock_repository import DemoDoctorRepository
from doctor_workstation.services.repository import (
@@ -774,10 +780,11 @@ def test_remote_diagnosis_ai_stream_normalises_chunks_in_order() -> None:
assert client.post_calls == []
def test_remote_diagnosis_ai_stream_falls_back_once_but_not_for_error_event() -> None:
@pytest.mark.parametrize("status_code", [404, 405])
def test_remote_diagnosis_ai_stream_falls_back_for_missing_route(status_code: int) -> None:
class MissingStreamClient(RecordingClient):
def post_event_stream(self, *args: Any, **kwargs: Any):
raise ApiHttpError("missing", status_code=404)
raise ApiHttpError("missing", status_code=status_code)
missing_client = MissingStreamClient()
events = list(
@@ -789,6 +796,57 @@ def test_remote_diagnosis_ai_stream_falls_back_once_but_not_for_error_event() ->
"tcm.diagnosis/aiAssistant"
]
@pytest.mark.parametrize(
"stream_error",
[
ApiHttpError("server error", status_code=500),
ApiTimeoutError("timed out"),
ApiTransportError("disconnected"),
ApiProtocolError("invalid event stream"),
],
)
def test_remote_diagnosis_ai_stream_failures_do_not_issue_full_request(
stream_error: Exception,
) -> None:
class FailedStreamClient(RecordingClient):
def post_event_stream(self, *args: Any, **kwargs: Any):
raise stream_error
client = FailedStreamClient()
with pytest.raises(type(stream_error)):
list(RemoteDoctorRepository(client).stream_diagnosis_ai(501, "请分析"))
assert client.post_calls == []
@pytest.mark.parametrize("after_start", [False, True])
def test_remote_diagnosis_ai_stream_incomplete_response_does_not_fall_back(
after_start: bool,
) -> None:
class IncompleteStreamClient(RecordingClient):
def post_event_stream(self, *args: Any, **kwargs: Any):
if after_start:
yield {"event": "start", "data": {"model_key": "qwen"}}
client = IncompleteStreamClient()
with pytest.raises(ApiProtocolError, match="ended before done"):
list(RemoteDoctorRepository(client).stream_diagnosis_ai(501, "请分析"))
assert client.post_calls == []
def test_remote_diagnosis_ai_stream_does_not_fall_back_after_start() -> None:
class FailedAfterStartClient(RecordingClient):
def post_event_stream(self, *args: Any, **kwargs: Any):
yield {"event": "start", "data": {"model_key": "qwen"}}
raise ApiHttpError("missing", status_code=404)
client = FailedAfterStartClient()
with pytest.raises(ApiHttpError):
list(RemoteDoctorRepository(client).stream_diagnosis_ai(501, "请分析"))
assert client.post_calls == []
def test_remote_diagnosis_ai_stream_error_event_does_not_fall_back() -> None:
class ErrorStreamClient(RecordingClient):
def post_event_stream(self, *args: Any, **kwargs: Any):
yield {"event": "error", "data": {"message": "模型繁忙"}}
+145
View File
@@ -0,0 +1,145 @@
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QApplication, QDialog, QMainWindow
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui.appointment_drawer import AppointmentDrawer
from doctor_workstation.ui.dialogs.ai_consult_picker import AiConsultTargetDialog
from doctor_workstation.ui.dialogs.diagnosis import DiagnosisDialog, OrderDetailDrawer
from doctor_workstation.ui.dialogs.prescription import PrescriptionEditorDialog
from doctor_workstation.ui.shell import ShellWindow
from doctor_workstation.ui.theme import _install_business_dialog_styling
def test_new_dialog_and_im_window_use_85_percent_of_main_window() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(40, 60, 1200, 800)
main.show()
app.processEvents()
dialog = QDialog(main)
dialog.setMinimumSize(1100, 700)
im_window = QMainWindow()
im_window.resize(1120, 760)
try:
for window in (dialog, im_window):
window.show()
app.processEvents()
assert window.size().width() == round(main.frameGeometry().width() * 0.85)
assert window.size().height() == round(main.frameGeometry().height() * 0.85)
assert abs(window.frameGeometry().center().x() - main.frameGeometry().center().x()) <= 1
assert abs(window.frameGeometry().center().y() - main.frameGeometry().center().y()) <= 1
window.hide()
main.resize(1400, 900)
app.processEvents()
for window in (dialog, im_window):
window.show()
app.processEvents()
assert window.width() == round(main.frameGeometry().width() * 0.85)
assert window.height() == round(main.frameGeometry().height() * 0.85)
finally:
im_window.close()
dialog.close()
main.close()
def test_frameless_drawer_keeps_its_owner_layout() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.resize(1200, 800)
main.show()
app.processEvents()
drawer = QDialog(main)
drawer.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
drawer.resize(500, 400)
try:
drawer.show()
app.processEvents()
assert drawer.size().width() == 500
assert drawer.size().height() == 400
finally:
drawer.close()
main.close()
def test_modal_exec_uses_main_window_geometry() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(30, 50, 1200, 800)
main.show()
app.processEvents()
dialog = QDialog(main)
try:
QTimer.singleShot(0, dialog.accept)
dialog.exec()
assert dialog.width() == round(main.frameGeometry().width() * 0.85)
assert dialog.height() == round(main.frameGeometry().height() * 0.85)
finally:
dialog.close()
main.close()
def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(30, 50, 1400, 900)
main.show()
app.processEvents()
repository = DemoDoctorRepository()
dialogs = [
AppointmentDrawer({"id": 501, "diagnosis_id": 501}, repository, main, autoload=False),
DiagnosisDialog(repository, main),
OrderDetailDrawer(main),
PrescriptionEditorDialog(repository, parent=main),
]
try:
for dialog in dialogs:
dialog.show()
app.processEvents()
app.processEvents()
assert dialog.width() == round(main.frameGeometry().width() * 0.85)
assert dialog.height() == round(main.frameGeometry().height() * 0.85)
dialog.hide()
finally:
for dialog in dialogs:
dialog.close()
main.close()
def test_maximized_workstation_opens_patient_picker_at_85_percent() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
repository = DemoDoctorRepository()
permissions = PermissionSet(["*"])
main = ShellWindow(
repository,
{"user": {"name": "测试医生"}, "demo_mode": True},
permissions,
)
main.showMaximized()
app.processEvents()
picker = AiConsultTargetDialog(repository, permissions, main)
try:
picker.show()
app.processEvents()
assert main.isMaximized()
assert picker.width() == round(main.frameGeometry().width() * 0.85)
assert picker.height() == round(main.frameGeometry().height() * 0.85)
finally:
picker.close()
main.close()
@@ -0,0 +1,12 @@
*
!Dockerfile
!audio-requirements.txt
!cpu_preflight.py
__pycache__/
*.pyc
acceptance/
.gpu1-mode*
@@ -0,0 +1,4 @@
# Copying this placeholder is insufficient: init-env.py creates random secret .env.
ASR_IMAGE=sha256:REPLACE_WITH_BUILT_IMAGE_ID
ASR_API_KEY=REPLACE_WITH_RANDOM_SECRET
ASR_GPU_MEMORY_UTILIZATION=0.15
+12
View File
@@ -0,0 +1,12 @@
.env
*.log
image-id.txt
fixtures/
__pycache__/
*.pyc
acceptance/
.gpu1-mode*
+7
View File
@@ -0,0 +1,7 @@
ARG BASE_IMAGE=local/qwen-asr-base:20261008-251eba5cc7c1
FROM ${BASE_IMAGE}
LABEL org.opencontainers.image.description="Isolated Qwen3-ASR audio dependencies" \
local.base_image_id="sha256:251eba5cc7c12fed0b75da22a9240e582b1c9e39f6fbc064f86781b963bd814f"
COPY audio-requirements.txt /opt/qwen-asr/audio-requirements.txt
RUN python3 -m pip install --no-cache-dir --no-deps --only-binary=:all: -r /opt/qwen-asr/audio-requirements.txt
COPY cpu_preflight.py /opt/qwen-asr/cpu_preflight.py
+116
View File
@@ -0,0 +1,116 @@
# Qwen3-ASR isolated preparation package
This package prepares a **separate** ASR image and immutable model snapshot. It does
not change, replace, stop, or restart the existing `qwen36-35b` deployment.
No GPU process is started by `download_model.py`, `build-image.sh`, or `init-env.py`.
## Fixed identities
- Base image ID: `sha256:251eba5cc7c12fed0b75da22a9240e582b1c9e39f6fbc064f86781b963bd814f`
- Base: vLLM 0.24.0, torch 2.11.0+cu130, transformers 5.12.1, numpy 2.2.6.
- Official model: `Qwen/Qwen3-ASR-1.7B`.
- Official ModelScope snapshot: `a04930dbe5419bfee073f7cade734f572689a3a8`.
- Weights total 4,698,521,512 bytes; do not use the earlier ~3.5GB estimate.
- New service root: `/home/www/qwen-vllm/asr`.
- Model root: `/home/www/qwen-vllm/asr/models/Qwen3-ASR-1.7B`.
- `DOWNLOAD_MANIFEST.json` preserves official SHA256 and size for every payload.
- Runtime image is pinned to the built immutable image ID in private `.env`.
The existing base contains the Qwen3ASR model registry and transcription implementation
but lacks audio extras. The independent thin image adds only `av`, `scipy`,
`soundfile`, and `soxr` with explicit versions and `--no-deps`; it preserves torch,
transformers, numpy and the original image bytes. CPU preflight performs actual WAV
encode/decode, resampling, and Whisper feature extraction plus static route checks.
This is **not** GPU inference or endpoint acceptance.
## Prepare without GPU execution
```sh
cd /home/www/qwen-vllm/asr
python3 download_model.py /home/www/qwen-vllm/asr/models/Qwen3-ASR-1.7B
./build-image.sh
python3 init-env.py
docker compose --env-file .env -f compose.yaml config --quiet
```
`init-env.py` creates a random API key in a new mode-0600 `.env`, refuses to overwrite
an existing file, and never prints the key. Do not publish `.env`, full compose
config output, container environment, or API Authorization headers.
## Start only after the project controller has released GPU1
**The controller must first verify that Qwen is healthy on GPU0 alone, GPU1 has no
competing process, and the shared-card guard permits ASR. Preparation is not this gate.**
```sh
cd /home/www/qwen-vllm/asr
docker compose --env-file .env -f compose.yaml up -d --no-build --pull never asr
```
Host GPU1 alone is exposed via Docker DeviceIDs `["1"]`; it appears as logical
CUDA device 0 inside the one-GPU container. Host port is only `127.0.0.1:8001`.
`restart: unless-stopped` supports reboot persistence without reactivating an
explicitly stopped service. Initial `gpu_memory_utilization=0.15` is adjustable
in `.env`; do not increase without measuring allocation and the shared-card budget.
`max-num-seqs=1`, `max-model-len=32768`, eager execution and max batched tokens 4096
bound the initial test workload. The model native text context is 65536. The installed
vLLM audio encoder maps about 13 audio tokens/second: 745 seconds is about 9685
audio tokens before output, so 4096 is not safe for an unsplit 7–12 minute input.
A 32768-token BF16 KV cache is approximately 3.5 GiB from the model configuration
(28 layers, 8 KV heads, head dimension 128); this is an estimate, not measured VRAM.
Keep the 0.15 allocation cap and verify actual startup/long-audio behavior. The
OpenAI transcription implementation has internal clip splitting based on the
feature extractor's 30-second clip limit, but the application should still segment
recordings into at most 5-minute bounded jobs with overlap and ordered merging.
An hour-long recording must be split; this package does not claim a one-hour
single-request acceptance. Long calls need a separate chunking/quality gate.
No forced aligner is loaded; word timestamps are not promised.
## Verify after controller start
```sh
cd /home/www/qwen-vllm/asr
python3 probe.py /absolute/path/to/non-sensitive-speech.wav
```
The probe requires `/health` HTTP 200, rejects unauthenticated `/v1/models` with
401, confirms the served model with authentication, and requires nonempty text
from an actual multipart `/v1/audio/transcriptions` request. The authenticated
probe reads the key locally and does not print it. A public or synthetic fixture is
required; never use patient recordings for this gate. Recognition accuracy needs
an expected-text comparison/listening in addition to a successful HTTP response.
## Stop / rollback only the new ASR service
```sh
cd /home/www/qwen-vllm/asr
docker compose --env-file .env -f compose.yaml stop asr
```
This releases ASR's GPU allocation while retaining model/image/config artifacts.
Do not start ComfyUI on GPU1 until the parent-controlled shared-card guard has
confirmed ASR stopped and memory released. ComfyUI is not deployed by this package.
Official references:
- https://github.com/QwenLM/Qwen3-ASR#deployment-with-vllm
- https://modelscope.cn/models/Qwen/Qwen3-ASR-1.7B
- https://huggingface.co/Qwen/Qwen3-ASR-1.7B
## GPU 1 与未来 ComfyUI 测试的互斥使用
在 ai 服务器运行:
```sh
python3 /home/www/qwen-vllm/asr/gpu1-mode.py status
# 等待 ASR 在途/排队请求结束并停止它,确认 GPU 1 空闲;不会启动或停止 ComfyUI。
python3 /home/www/qwen-vllm/asr/gpu1-mode.py test
# 测试实例完全退出、GPU 1 空闲后恢复 ASR,并等待健康检查。
python3 /home/www/qwen-vllm/asr/gpu1-mode.py asr
```
控制器遇到未知 GPU 1 进程会拒绝操作,不强杀。ComfyUI 测试实例尚未创建;未来应显式绑定 GPU 1,不修改当前 GPU 2/3 上的服务。请通过此控制器切换,而非同时启动两个占卡服务。`unless-stopped` 保留手工停止状态,新服务同时设置 600 秒引擎优雅关闭和 660 秒容器停止宽限。
Qwen 单卡切换的原始配置、候选配置、合成文本/长文本/图片检查与回滚控制器保存在 ai 的 `/home/www/qwen-vllm/rollouts/20261008-single-gpu/`。需要回退双卡时,先释放 GPU 1,再运行该目录的 `deploy.py rollback`;它拒绝覆盖不认识的配置或驱逐 GPU 1 上的其他进程。此操作会重启 Qwen,需维护窗口。源码回滚和服务器运行状态回滚不是同一件事。
控制器无 GPU 单元检查:`python3 deployment/followup-audio-asr/test_gpu1_mode.py`。真实启动、转录和卡交接结果请以本次部署证据为准,不把 CPU-only 准备检查当 GPU 运行成功。
@@ -0,0 +1,5 @@
# Small isolated audio layer; base torch/transformers/numpy must not be replaced.
av==16.0.1
scipy==1.16.3
soundfile==0.13.1
soxr==1.0.0
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
cd "$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
base=sha256:251eba5cc7c12fed0b75da22a9240e582b1c9e39f6fbc064f86781b963bd814f
base_tag=local/qwen-asr-base:20261008-251eba5cc7c1
actual=$(docker image inspect "$base" --format '{{.Id}}')
[ "$actual" = "$base" ] || { echo 'Base image mismatch' >&2; exit 1; }
docker tag "$base" "$base_tag"
docker build --pull=false --build-arg BASE_IMAGE="$base_tag" -t local/qwen-asr:20261008 .
docker image inspect local/qwen-asr:20261008 --format '{{.Id}}' > image-id.txt
printf 'ASR_IMAGE='; cat image-id.txt
# Explicitly no --gpus. This checks imports and signal processing only.
docker run --rm --network none -e NVIDIA_VISIBLE_DEVICES=void --entrypoint python3 "$(cat image-id.txt)" /opt/qwen-asr/cpu_preflight.py
@@ -0,0 +1,67 @@
name: followup-audio-asr
services:
asr:
image: ${ASR_IMAGE:?Run build-image.sh and init-env.py first}
pull_policy: never
container_name: followup-audio-asr
restart: unless-stopped
stop_grace_period: 660s
init: true
ports:
- "127.0.0.1:8001:8000"
environment:
CUDA_VISIBLE_DEVICES: "0"
VLLM_API_KEY: ${ASR_API_KEY:?Initialize the private .env first}
HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1"
HF_HUB_DISABLE_TELEMETRY: "1"
DO_NOT_TRACK: "1"
VLLM_NO_USAGE_STATS: "1"
OMP_NUM_THREADS: "4"
volumes:
- /home/www/qwen-vllm/asr/models/Qwen3-ASR-1.7B:/model:ro
shm_size: "2gb"
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
deploy:
resources:
reservations:
devices:
- driver: nvidia
device_ids: ["1"]
capabilities: [gpu]
command:
- /model
- --served-model-name
- Qwen/Qwen3-ASR-1.7B
- --host
- 0.0.0.0
- --port
- "8000"
- --dtype
- bfloat16
- --tensor-parallel-size
- "1"
- --gpu-memory-utilization
- ${ASR_GPU_MEMORY_UTILIZATION:-0.15}
- --max-num-seqs
- "1"
- --max-model-len
- "32768"
- --max-num-batched-tokens
- "4096"
- --shutdown-timeout
- "600"
- --enforce-eager
- --no-enable-log-requests
healthcheck:
test: [CMD, python3, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=5).read()"]
interval: 20s
timeout: 8s
start_period: 180s
retries: 6
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""CPU-only dependency, format and route checks. Does not instantiate a model."""
import importlib.metadata as metadata
import io
import json
from pathlib import Path
import numpy as np
import soundfile as sf
import soxr
import scipy
import av
import vllm
import torch
from transformers import WhisperFeatureExtractor
signal=np.zeros(16000,dtype=np.float32)
encoded=io.BytesIO()
sf.write(encoded,signal,16000,format='WAV')
encoded.seek(0)
decoded,rate=sf.read(encoded,dtype='float32')
assert rate==16000 and decoded.shape==(16000,)
resampled=soxr.resample(decoded,16000,8000)
assert len(resampled)==8000
features=WhisperFeatureExtractor()(decoded,sampling_rate=rate,return_tensors='np')
assert features['input_features'].shape[0]==1
root=Path(vllm.__file__).parent
model_source=(root/'model_executor/models/qwen3_asr.py').read_text()
registry_source=(root/'model_executor/models/registry.py').read_text()
assert 'Qwen3ASRForConditionalGeneration' in registry_source
assert 'SupportsTranscription' in model_source
routes=[str(path.relative_to(root)) for path in (root/'entrypoints').rglob('*.py') if '"/v1/audio/transcriptions"' in path.read_text()]
assert routes, 'Transcription route missing'
assert not Path('/dev/nvidia0').exists(), 'This test must not have GPU device access'
assert vllm.__version__=='0.24.0'
assert metadata.version('numpy')=='2.2.6'
assert metadata.version('torch')=='2.11.0+cu130'
assert metadata.version('transformers')=='5.12.1'
print(json.dumps({'event':'cpu_preflight_pass','versions':{name:metadata.version(name) for name in ['vllm','torch','transformers','numpy','soundfile','scipy','soxr','av']},'wav_roundtrip_shape':list(decoded.shape),'resampled_shape':list(resampled.shape),'feature_shape':list(features['input_features'].shape),'transcription_route_files':routes,'gpu_device_access':False}))
# Validate only the installed CLI option declarations. Constructing the full vLLM
# config on a no-GPU preflight host would try to infer a device.
import argparse
import ast
import inspect
from vllm.engine.arg_utils import AsyncEngineArgs
parser = argparse.ArgumentParser()
tree = ast.parse(Path(inspect.getfile(AsyncEngineArgs)).read_text())
found = set()
for node in ast.walk(tree):
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name) and node.func.value.id == "parser"
and node.func.attr == "add_argument" and node.args
and isinstance(node.args[0], ast.Constant)
and node.args[0].value in {"--enable-log-requests", "--shutdown-timeout"}):
eval(compile(ast.Expression(node), "<installed-option-declaration>", "eval"),
{"parser": parser, "argparse": argparse, "AsyncEngineArgs": AsyncEngineArgs, "int": int})
found.add(node.args[0].value)
assert len(found) == 2
args = parser.parse_args(["--no-enable-log-requests", "--shutdown-timeout", "600"])
assert args.enable_log_requests is False and args.shutdown_timeout == 600
print("CLI_PRIVACY_AND_SHUTDOWN_DECLARATIONS_PASS")
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Download a pinned official ModelScope snapshot; never replace mismatched files."""
import hashlib
import json
import os
from pathlib import Path
import sys
import urllib.parse
import urllib.request
MODEL = 'Qwen/Qwen3-ASR-1.7B'
REVISION = 'a04930dbe5419bfee073f7cade734f572689a3a8'
ROOT = Path(sys.argv[1] if len(sys.argv) > 1 else '/home/www/qwen-vllm/asr/models/Qwen3-ASR-1.7B')
API = f'https://modelscope.cn/api/v1/models/{MODEL}/repo'
def digest(path):
h = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
ROOT.mkdir(parents=True, exist_ok=True)
url = API + '/files?' + urllib.parse.urlencode({'Revision': REVISION, 'Recursive': 'true'})
with urllib.request.urlopen(url, timeout=60) as response:
listing = json.load(response)
assert listing['Code'] == 200 and listing['Success'], listing
files = [x for x in listing['Data']['Files'] if x['Type'] == 'blob' and x['Path'] != '.gitattributes']
manifest = {'provider': 'ModelScope', 'model': MODEL, 'revision': REVISION, 'api': url, 'files': files}
manifest_path = ROOT / 'DOWNLOAD_MANIFEST.json'
if manifest_path.exists():
old = json.loads(manifest_path.read_text())
assert old == manifest, 'Existing manifest differs; preserve and abort'
else:
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
for row in files:
relative = Path(row['Path'])
assert not relative.is_absolute() and '..' not in relative.parts
path = ROOT / relative
if path.exists():
assert path.stat().st_size == row['Size'] and digest(path) == row['Sha256'], f'Existing file mismatch: {path}'
print(json.dumps({'event': 'download_reused', 'path': str(path), 'sha256': row['Sha256'], 'bytes': row['Size']}), flush=True)
continue
path.parent.mkdir(parents=True, exist_ok=True)
partial = path.with_name(path.name + '.partial')
# A partial file is only a disposable incomplete transfer created by this script.
target = API + '?' + urllib.parse.urlencode({'Revision': REVISION, 'FilePath': row['Path']})
print(json.dumps({'event': 'download_started', 'file': row['Path'], 'bytes': row['Size'], 'revision': REVISION}), flush=True)
h = hashlib.sha256()
size = 0
with urllib.request.urlopen(target, timeout=120) as source, partial.open('wb') as output:
while True:
chunk = source.read(8 * 1024 * 1024)
if not chunk:
break
output.write(chunk)
h.update(chunk)
size += len(chunk)
assert size == row['Size'] and h.hexdigest() == row['Sha256'], f'Download integrity mismatch: {path}'
os.replace(partial, path)
print(json.dumps({'event': 'download_verified', 'path': str(path), 'sha256': h.hexdigest(), 'bytes': size}), flush=True)
config = json.loads((ROOT / 'config.json').read_text())
assert config['architectures'] == ['Qwen3ASRForConditionalGeneration'], config['architectures']
weights = json.loads((ROOT / 'model.safetensors.index.json').read_text())
assert set(weights['weight_map'].values()) <= {x['Path'] for x in files}
# Public model weights must remain readable through a read-only bind mount with cap_drop=ALL.
# This does not change the private service .env or acceptance directory permissions.
ROOT.chmod(0o755)
manifest_path.chmod(0o644)
for row in files:
(ROOT / row['Path']).chmod(0o644)
print(json.dumps({'event': 'model_ready', 'model': MODEL, 'revision': REVISION, 'manifest_sha256': digest(manifest_path), 'total_bytes': sum(x['Size'] for x in files), 'architectures': config['architectures'], 'model_type': config.get('model_type'), 'dtype': config.get('torch_dtype', config.get('dtype')), 'weight_metadata': weights['metadata']}), flush=True)
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Exclusive operational handoff: ASR on GPU1, or GPU1 released for future tests.
Never starts/stops ComfyUI, never kills unknown GPU processes, never prints API keys.
"""
import argparse,fcntl,json,pathlib,subprocess,time,urllib.request
ROOT=pathlib.Path(__file__).resolve().parent
CONTAINER='followup-audio-asr'
def command(args):
p=subprocess.run(args,capture_output=True,text=True,timeout=700)
if p.returncode: raise RuntimeError('COMMAND_FAILED: '+args[0])
return p.stdout
def gpu_pids():
text=command(['nvidia-smi','--id=1','--query-compute-apps=pid','--format=csv,noheader,nounits'])
return {int(line.strip()) for line in text.splitlines() if line.strip()}
def container_state():
p=subprocess.run(['docker','inspect','--format','{{json .State}}',CONTAINER],capture_output=True,text=True)
if p.returncode:
if 'no such object' in p.stderr.lower() or 'no such container' in p.stderr.lower():return {'Running':False,'Status':'absent'}
raise RuntimeError('CONTAINER_STATE_UNKNOWN')
return json.loads(p.stdout)
def owned_pids(state):
if not state.get('Running'):return set()
lines=command(['docker','top',CONTAINER,'-eo','pid']).splitlines()[1:]
return {int(line.strip()) for line in lines if line.strip()}
def ensure_exclusive(active,owned):
if active-owned: raise RuntimeError('GPU1_HAS_OTHER_WORKLOAD: refusing to stop or replace it')
def idle_values(body):
values=[]
for name in ['vllm:num_requests_running','vllm:num_requests_waiting']:
rows=[float(l.rsplit(' ',1)[1]) for l in body.splitlines() if l.startswith(name+'{')]
if not rows:raise RuntimeError('ASR_DRAIN_METRICS_MISSING')
values.append(sum(rows))
return values
def drain():
zeros=0;deadline=time.monotonic()+600
while time.monotonic()<deadline:
with urllib.request.urlopen('http://127.0.0.1:8001/metrics',timeout=5) as r: values=idle_values(r.read().decode())
zeros=zeros+1 if values==[0,0] else 0
if zeros>=3:return
time.sleep(5)
raise RuntimeError('ASR_BUSY: unchanged; wait for requests to finish')
def main():
p=argparse.ArgumentParser();p.add_argument('mode',choices=['status','asr','test']);args=p.parse_args()
lock=open(ROOT/'.gpu1-mode.lock','a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
state=container_state();active=gpu_pids();owned=owned_pids(state)
if args.mode=='status':
print(json.dumps({'asr_status':state['Status'],'asr_running':state['Running'],'gpu1_processes':sorted(active),'other_gpu1_processes':sorted(active-owned),'test_service_started':False}));return
ensure_exclusive(active,owned)
compose=['docker','compose','--project-directory',str(ROOT),'--env-file',str(ROOT/'.env'),'-f',str(ROOT/'compose.yaml')]
if args.mode=='test':
if state['Running']:
drain();ensure_exclusive(gpu_pids(),owned_pids(container_state()))
command(compose+['stop','--timeout','660','asr'])
if gpu_pids():raise RuntimeError('GPU1_NOT_FREE')
result={'mode':'test','asr_stopped':True,'gpu1_free':True,'comfyui_test_started':False}
else:
if not state['Running']:
if active:raise RuntimeError('GPU1_NOT_FREE')
command(compose+['up','-d','--no-build','--pull','never','asr'])
deadline=time.monotonic()+480
while time.monotonic()<deadline:
state=container_state()
if state.get('Health',{}).get('Status')=='healthy':break
if state['Status'] in ['exited','dead','restarting']:raise RuntimeError('ASR_START_FAILED')
time.sleep(5)
else:raise RuntimeError('ASR_READINESS_TIMEOUT')
result={'mode':'asr','asr_healthy':True,'gpu1_processes':sorted(gpu_pids()),'comfyui_test_started':False}
target=ROOT/'.gpu1-mode.json';stage=target.with_suffix('.tmp');stage.write_text(json.dumps(result)+'\n');stage.chmod(0o600);stage.replace(target)
print(json.dumps(result))
if __name__=='__main__':main()
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""Create a new local secret without displaying it; never replace existing .env."""
import os
from pathlib import Path
import re
import secrets
root=Path(__file__).resolve().parent
image=(root/'image-id.txt').read_text().strip()
assert re.fullmatch(r'sha256:[0-9a-f]{64}', image), 'Invalid immutable image ID'
path=root/'.env'
fd=os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd,'w') as stream:
stream.write(f'ASR_IMAGE={image}\nASR_API_KEY={secrets.token_urlsafe(48)}\nASR_GPU_MEMORY_UTILIZATION=0.15\n')
print('ENV_CREATED mode=0600 secret=not-displayed image='+image)
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Acceptance probe: requires a local non-sensitive speech WAV argument."""
import argparse
import json
from pathlib import Path
import urllib.error
import urllib.request
import uuid
parser=argparse.ArgumentParser()
parser.add_argument('audio',type=Path,help='Non-sensitive public or synthetic speech WAV')
parser.add_argument('--base-url',default='http://127.0.0.1:8001')
args=parser.parse_args()
root=Path(__file__).resolve().parent
values=dict(line.strip().split('=',1) for line in (root/'.env').read_text().splitlines() if line and not line.startswith('#'))
secret=values['ASR_API_KEY']
base=args.base_url.rstrip('/')
assert base in ('http://127.0.0.1:8001','http://localhost:8001'), 'Probe only supports loopback'
def request(path,data=None,headers=None):
req=urllib.request.Request(base+path,data=data,headers=headers or {})
with urllib.request.urlopen(req,timeout=180) as response:
return response.status,response.read()
status,body=request('/health')
assert status==200
print(json.dumps({'event':'health_pass','http_status':status,'body':body.decode()}))
try:
status,body=request('/v1/models')
except urllib.error.HTTPError as error:
assert error.code==401,error.code
print(json.dumps({'event':'unauthenticated_denied','http_status':error.code}))
else:
raise AssertionError('Unauthenticated model request was not denied')
headers={'Authorization':'Bearer '+secret}
status,body=request('/v1/models',headers=headers)
models=json.loads(body)
assert any(row['id']=='Qwen/Qwen3-ASR-1.7B' for row in models['data']),models
print(json.dumps({'event':'models_pass','http_status':status,'body':models}))
audio=args.audio.read_bytes()
assert 44<len(audio)<=25*1024*1024, 'Speech fixture must be 44 bytes..25MiB'
boundary='asr-probe-'+uuid.uuid4().hex
prefix=(f'--{boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\nQwen/Qwen3-ASR-1.7B\r\n'
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="fixture.wav"\r\nContent-Type: audio/wav\r\n\r\n').encode()
payload=prefix+audio+f'\r\n--{boundary}--\r\n'.encode()
headers['Content-Type']='multipart/form-data; boundary='+boundary
status,body=request('/v1/audio/transcriptions',data=payload,headers=headers)
transcript=json.loads(body)
assert status==200 and isinstance(transcript.get('text'),str) and transcript['text'].strip(),transcript
print(json.dumps({'event':'transcription_pass','http_status':status,'body':transcript},ensure_ascii=False))
@@ -0,0 +1,19 @@
import importlib.util,pathlib,unittest
from unittest.mock import patch
from types import SimpleNamespace
s=importlib.util.spec_from_file_location('manager',pathlib.Path(__file__).with_name('gpu1-mode.py'));m=importlib.util.module_from_spec(s);s.loader.exec_module(m)
class Safety(unittest.TestCase):
def test_absent_container_case_insensitive(self):
with patch.object(m.subprocess,'run',return_value=SimpleNamespace(returncode=1,stderr='error: no such object: followup-audio-asr',stdout='')):self.assertEqual(m.container_state()['Status'],'absent')
def test_daemon_error_not_absent(self):
with patch.object(m.subprocess,'run',return_value=SimpleNamespace(returncode=1,stderr='permission denied',stdout='')):
with self.assertRaisesRegex(RuntimeError,'STATE_UNKNOWN'):m.container_state()
def test_foreign_process_refused(self):
with self.assertRaisesRegex(RuntimeError,'OTHER_WORKLOAD'):m.ensure_exclusive({1,2},{1})
def test_owned_allowed(self):m.ensure_exclusive({1},{1})
def test_empty_allowed(self):m.ensure_exclusive(set(),set())
def test_idle(self):self.assertEqual(m.idle_values('vllm:num_requests_running{engine="0"} 0\nvllm:num_requests_waiting{engine="0"} 0'),[0,0])
def test_busy(self):self.assertEqual(m.idle_values('vllm:num_requests_running{engine="0"} 1\nvllm:num_requests_waiting{engine="0"} 2'),[1,2])
def test_missing_metrics_refused(self):
with self.assertRaisesRegex(RuntimeError,'METRICS_MISSING'):m.idle_values('')
if __name__=='__main__':unittest.main()
@@ -0,0 +1,5 @@
__pycache__/
*.pyc
*.env
*.private.*
asr-key
+34
View File
@@ -0,0 +1,34 @@
# Isolated Dify ASR deployment — 2026-10-09
This directory adds only a CPU-only fixed-upstream bridge, a new speech2text model/default, and an independent Dify chat App. Do not apply its compose file to the old Dify or ASR project. The two networks are external and must not be deleted.
- AI host deployment root: `/home/www/qwen-vllm/dify-integration-20261009`
- Public API base: `https://ai.zhenyangtang.com.cn/v1`
- New App: `ea0d7293-3d89-425d-a236-015fac7e2470`
- App mode chat; public site disabled; API enabled; max active chat requests 1.
- ASR: `Qwen/Qwen3-ASR-1.7B`; extraction: existing `qwen3.6-35b`.
- App max_tokens 8192, temperature 0, enable_thinking false; JSON requested in the system/query prompts, not native JSON-schema enforcement. Existing Qwen model has strict compatibility/not_supported thinking; SDK may filter the explicit false parameter. The existing Qwen server's `--default-chat-template-kwargs {"enable_thinking":false}` is the effective server control, verified without changing it.
- Binding revision: `followup-dify-20261009-v1-99ebe159aef4dce6`. Any App/provider/default/model-serving/bridge change requires a new revision and new acceptance. This is a version binding, not an automatic remote drift monitor.
- Bridge: existing pinned Python 3.12 image, two Docker networks, no host port, no GPU, UID1000, read-only root, all capabilities dropped, no-new-privileges, 256MiB/0.5CPU/64PIDs; in-flight 1, token bucket 120/min burst4, 30MiB+64KiB multipart limit, 180s fixed-upstream timeout, no redirects or POST retry.
- Secrets exist only in private 0600 host files and encrypted Dify credentials. Never print `resources.private.json`, `asr-key`, `dify-runtime.env`, or `operator-error.private.log`.
- Provisioning uses deployed `ModelProviderService`, `AppService`, model-config and key controllers, including provider validation/encryption. It never handcrafts encrypted provider rows. Provision is single-use; inspect exact state after any failure before resuming.
## Validation
Run `python3 test_bridge.py` locally for eight synthetic mock-server tests. `public_probe.py PRIVATE_ENV SYNTHETIC_WAV [all|asr|chat] [EXPECTED_CANARIES_JSON]` always verifies HTTPS certificates/hostname, never emits keys, and sends canary strings only in audio, not in ASR form prompts. Optional expected canaries are verifier inputs only. Preserve failures; passing connection tests do not establish full transcription accuracy.
Initial ASR fixture reproduced a homophone error: `红色石榴` became `红色石流`; its strict four-canary result remains failed even though the other three unique canaries match and HTTPS ASR returns 200. This release is for synthetic/preview-only validation, not clinical writeback or an assertion of complete accuracy.
Webhost Python/OpenSSL validates this TLS endpoint. Webhost legacy PHP/cURL NSS certificate-key-usage behavior requires independent acceptance; do not disable TLS verification or infer PHP success from Python success.
## Exact rollback
On AI host, execute only this release's `/home/www/qwen-vllm/dify-integration-20261009/ROLLBACK.sh`:
- `--quiesce`: disable only the new App API and stop only its recorded bridge container; verified live.
- `--restore`: start the same new bridge, check health, re-enable only the new App API; verified live.
- `--remove-new-objects`: revoke the precise new key, delete the precise new App, remove this newly introduced non-secret speech2text default and credential through guarded ORM/service operations, and remove only this bridge. This final removal is packaged, not exercised against the live desired deployment. It aborts if another App now uses speech2text or resource IDs differ.
No command deletes shared networks, old providers/models/apps, model files, or old containers. Apply rollback before removing the private resource manifest; preserve it for identity checks. No old source files or global configuration are edited.
After live quiesce/restore, a separate 13.03075s synthetic fixture (`蓝色风筝/绿色森林/白色帆船/黑色雨伞`) passed all four audio-only canaries through the Webhost's fully verified HTTPS Python/OpenSSL route (ASR 200, 1.284s); the JSON chat canary also passed (200, 0.539s). This additional successful connection case does not overwrite the retained first fixture's homophone failure.
+36
View File
@@ -0,0 +1,36 @@
#!/bin/sh
# Only this release. Default reversible quiesce; --remove-new-objects is permanent.
set -eu
BASE=/home/www/qwen-vllm/dify-integration-20261009
ID=7c3ca77d77cac063d6b98310e59d2a73b896a0f5171ba002d41eccab1c067a59
MODE=${1:---quiesce}
case "$MODE" in --quiesce|--restore|--remove-new-objects) ;; *) echo 'usage: ROLLBACK.sh [--quiesce|--restore|--remove-new-objects]' >&2; exit 2;; esac
python3 - "$BASE" <<'PY'
import json,pathlib,sys
r=json.loads((pathlib.Path(sys.argv[1])/'resources.private.json').read_text())
expected={'app_id':'ea0d7293-3d89-425d-a236-015fac7e2470','key_id':'ecfb7628-1369-41fa-b132-d24074af8470','asr_model_id':'e55a7374-a43e-4b86-9323-005a2a72458b','asr_credential_id':'01a11f7e-a148-7b9c-82c7-ffc1425b40ee','asr_default_id':'56ca4093-61fa-446b-ad77-b10deb9daaa4'}
assert all(r.get(k)==v for k,v in expected.items()),'RESOURCE_IDENTITY_MISMATCH'
print('EXACT_NEW_RESOURCES_VERIFIED')
PY
ACTUAL=$(docker inspect --format '{{.Id}}' followup-asr-bridge-20261009)
[ "$ACTUAL" = "$ID" ] || { echo 'BRIDGE_IDENTITY_MISMATCH' >&2; exit 3; }
[ "$(docker inspect --format '{{index .Config.Labels "com.zyt.release"}}' "$ID")" = followup-dify-20261009 ] || exit 4
if [ "$MODE" = --restore ]; then
docker start "$ID"
for n in 1 2 3 4 5 6 7 8 9 10; do
if docker exec "$ID" python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health',timeout=4).read()"; then break; fi
sleep 1
done
docker exec "$ID" python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health',timeout=4).read()"
python3 "$BASE/host_operator.py" enable
echo RESTORED_NEW_ASR_APP_AND_BRIDGE
elif [ "$MODE" = --quiesce ]; then
python3 "$BASE/host_operator.py" disable
docker stop --time 10 "$ID"
echo NEW_ASR_APP_AND_BRIDGE_QUIESCED
else
python3 "$BASE/host_operator.py" remove
docker stop --time 10 "$ID"
docker rm "$ID"
echo NEW_APP_MODEL_DEFAULT_BRIDGE_REMOVED_SHARED_RESOURCES_PRESERVED
fi
+165
View File
@@ -0,0 +1,165 @@
"""Fixed-upstream ASR gateway: stdlib only, no retry, no body/header logging."""
from __future__ import annotations
import hmac
import http.client
import json
import os
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
MAX_BODY = 30 * 1024 * 1024 + 65536 # Dify accepts 30 MiB file; multipart allowance.
MAX_RESPONSE = 4 * 1024 * 1024
UPSTREAM_HOST = 'followup-audio-asr'
UPSTREAM_PORT = 8000
RATE_PER_MINUTE = 120
RATE_BURST = 4
class Gate:
def __init__(self, rate=RATE_PER_MINUTE, burst=RATE_BURST):
self.rate, self.burst = rate, burst
self.tokens, self.at = float(burst), time.monotonic()
self.lock = threading.Lock()
self.active = threading.BoundedSemaphore(1)
def take(self):
with self.lock:
now = time.monotonic()
self.tokens = min(float(self.burst), self.tokens + (now - self.at) * self.rate / 60)
self.at = now
if self.tokens < 1:
return False
self.tokens -= 1
return True
class Server(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
request_queue_size = 8
def __init__(self, address, handler, *, key, upstream=(UPSTREAM_HOST, UPSTREAM_PORT), rate=RATE_PER_MINUTE, burst=RATE_BURST, timeout=180):
super().__init__(address, handler)
self.key, self.upstream, self.timeout = key, upstream, timeout
self.gate = Gate(rate, burst)
self.connections = threading.BoundedSemaphore(8)
def process_request(self, request, client_address):
if not self.connections.acquire(blocking=False):
try:
request.sendall(b'HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
finally:
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.connections.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.connections.release()
def handle_error(self, request, client_address):
# Deliberately suppress tracebacks/request fragments from client errors.
print(json.dumps({'event': 'client_error'}), flush=True)
class Handler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
server_version = 'FollowupASRBridge/1'
sys_version = ''
def setup(self):
super().setup()
self.connection.settimeout(30)
def log_message(self, format, *args):
pass
def reply(self, code, body, content_type='application/json'):
self.close_connection = True
self.send_response(code)
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', str(len(body)))
self.send_header('Connection', 'close')
self.send_header('Cache-Control', 'no-store')
if code == 429:
self.send_header('Retry-After', '1')
self.end_headers()
self.wfile.write(body)
def error_json(self, code, label):
self.reply(code, json.dumps({'error': label}).encode())
def authorized(self):
supplied = self.headers.get('Authorization', '')
return hmac.compare_digest(supplied.encode(), b'Bearer ' + self.server.key)
def upstream_call(self, method, path, body=None, content_type=None, health=False):
conn = http.client.HTTPConnection(*self.server.upstream, timeout=3 if health else self.server.timeout)
try:
headers = {} if health else {'Authorization': 'Bearer ' + self.server.key.decode()}
if content_type:
headers['Content-Type'] = content_type
conn.request(method, path, body=body, headers=headers)
response = conn.getresponse()
result = response.read(MAX_RESPONSE + 1)
if len(result) > MAX_RESPONSE:
return self.error_json(502, 'upstream_response_too_large')
if health:
return self.reply(200 if response.status == 200 else 503, b'{"status":"ok"}' if response.status == 200 else b'{"status":"unhealthy"}')
self.reply(response.status, result, response.getheader('Content-Type', 'application/json'))
except (OSError, http.client.HTTPException, TimeoutError):
self.error_json(503 if health else 502, 'upstream_unavailable')
finally:
conn.close()
def do_GET(self):
if self.path == '/health':
return self.upstream_call('GET', '/health', health=True)
if self.path != '/v1/models':
return self.error_json(404, 'not_found')
if not self.authorized():
return self.error_json(401, 'unauthorized')
return self.upstream_call('GET', '/v1/models')
def do_POST(self):
if self.path != '/v1/audio/transcriptions':
return self.error_json(404, 'not_found')
if not self.authorized():
return self.error_json(401, 'unauthorized')
if self.headers.get('Transfer-Encoding') or not self.headers.get('Content-Length', '').isdigit():
return self.error_json(411, 'content_length_required')
length = int(self.headers['Content-Length'])
if length > MAX_BODY:
return self.error_json(413, 'body_too_large')
if length <= 0:
return self.error_json(400, 'empty_body')
content_type = self.headers.get('Content-Type', '')
if not content_type.startswith('multipart/form-data;') or 'boundary=' not in content_type:
return self.error_json(415, 'multipart_required')
if not self.server.gate.active.acquire(blocking=False):
return self.error_json(429, 'asr_busy')
try:
if not self.server.gate.take():
return self.error_json(429, 'rate_limit')
try:
body = self.rfile.read(length)
except (OSError, socket.timeout):
return self.error_json(408, 'upload_timeout')
if len(body) != length:
return self.error_json(400, 'incomplete_body')
return self.upstream_call('POST', '/v1/audio/transcriptions', body, content_type)
finally:
self.server.gate.active.release()
if __name__ == '__main__':
key = Path('/run/secrets/asr-key').read_bytes().strip()
if len(key) < 16 or b'\n' in key or b'\r' in key:
raise SystemExit('invalid_secret_file')
print(json.dumps({'event': 'started', 'rate_per_minute': RATE_PER_MINUTE, 'inflight': 1, 'host_ports': False}), flush=True)
Server(('0.0.0.0', 8080), Handler, key=key).serve_forever()
@@ -0,0 +1,41 @@
services:
bridge:
image: sha256:34386ef0cb081344d7ec1c103ba398e6e9f64e9ab3a1509accc92a4e24a07258
container_name: followup-asr-bridge-20261009
user: '1000:1000'
entrypoint: ['python', '-B', '/app/bridge.py']
working_dir: /app
restart: unless-stopped
read_only: true
cap_drop: [ALL]
security_opt: ['no-new-privileges:true']
pids_limit: 64
cpus: 0.50
mem_limit: 256m
memswap_limit: 256m
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
volumes:
- './bridge.py:/app/bridge.py:ro'
- './asr-key:/run/secrets/asr-key:ro'
networks:
dify:
aliases: [followup-asr-bridge]
asr: {}
healthcheck:
test: ['CMD', 'python', '-c', "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health',timeout=4).read()"]
interval: 15s
timeout: 5s
retries: 3
start_period: 10s
logging:
driver: json-file
options: {max-size: 1m, max-file: '2'}
labels:
com.zyt.release: followup-dify-20261009
networks:
dify:
external: true
name: dify_v1110_eera_default
asr:
external: true
name: followup-audio-asr_default
@@ -0,0 +1,119 @@
"""Execute in Dify API Python with PAYLOAD supplied by private host wrapper.
Uses deployed services/controllers for credential encryption and app config.
Never print this process output to public logs: create returns a new app key to
its private caller; the wrapper writes it 0600 and emits only public metadata.
"""
import hashlib
import inspect
import json
import logging
import sys
logging.disable(logging.CRITICAL)
from app_factory import create_app
app = create_app()
from sqlalchemy import select
from extensions.ext_database import db
from models.account import Account, Tenant, TenantAccountJoin
from models.model import App, ApiToken
from models.provider import ProviderModel, ProviderModelCredential, TenantDefaultModel
from services.app_service import AppService
from services.model_provider_service import ModelProviderService
PROVIDER = 'langgenius/openai_api_compatible/openai_api_compatible'
ASR = 'Qwen/Qwen3-ASR-1.7B'
APP_NAME = 'followup-audio-isolated-20261009'
ENDPOINT = 'http://followup-asr-bridge:8080/v1'
CONFIG = {
'model': {'provider': PROVIDER, 'name': 'qwen3.6-35b', 'mode': 'chat',
'completion_params': {'max_tokens': 8192, 'temperature': 0.0, 'top_p': 1.0, 'enable_thinking': False}},
'pre_prompt': '仅依据本次用户请求处理提供的文本。遵循用户给定的 JSON 格式,只返回最终 JSON,不输出思考过程、解释或 Markdown。不得把示例当成事实。',
'prompt_type': 'simple', 'user_input_form': [],
'speech_to_text': {'enabled': True}, 'text_to_speech': {'enabled': False},
'suggested_questions_after_answer': {'enabled': False},
'retriever_resource': {'enabled': False}, 'sensitive_word_avoidance': {'enabled': False},
'file_upload': {'enabled': False},
}
with app.app_context():
# Anchor only to the existing default Qwen workspace. Fail if ambiguous.
tenant_ids = db.session.scalars(select(TenantDefaultModel.tenant_id).where(
TenantDefaultModel.model_type == 'text-generation', TenantDefaultModel.model_name == 'qwen3.6-35b')).all()
assert len(tenant_ids) == 1, 'AMBIGUOUS_WORKSPACE'
tenant_id = tenant_ids[0]
tenant = db.session.get(Tenant, tenant_id)
owner = db.session.scalars(select(Account).join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id).where(
TenantAccountJoin.tenant_id == tenant_id, TenantAccountJoin.role == 'owner')).one()
owner.current_tenant = tenant
def current_app_owned():
resource = PAYLOAD['resources']
obj = db.session.get(App, resource['app_id'])
assert obj and obj.name == APP_NAME and obj.tenant_id == tenant_id, 'APP_IDENTITY_MISMATCH'
return obj
def public_state(obj):
model = db.session.scalars(select(ProviderModel).where(ProviderModel.tenant_id == tenant_id,
ProviderModel.provider_name == PROVIDER, ProviderModel.model_name == ASR, ProviderModel.model_type == 'speech2text')).one()
default = db.session.scalars(select(TenantDefaultModel).where(TenantDefaultModel.tenant_id == tenant_id,
TenantDefaultModel.model_type == 'speech2text')).one()
config = obj.app_model_config.to_dict()
return {'app_id':obj.id,'app_name':obj.name,'tenant_id':tenant_id,'app_mode':obj.mode,
'enable_api':obj.enable_api,'enable_site':obj.enable_site,'config_id':obj.app_model_config_id,
'speech_to_text':obj.app_model_config.speech_to_text_dict,
'model':obj.app_model_config.model_dict,'pre_prompt_sha256':hashlib.sha256(obj.app_model_config.pre_prompt.encode()).hexdigest(),
'config_sha256':hashlib.sha256(json.dumps(config,ensure_ascii=False,sort_keys=True,default=str).encode()).hexdigest(),
'asr_model_id':model.id,'asr_credential_id':model.credential_id,'asr_default_id':default.id,
'asr_model':model.model_name,'asr_default':default.model_name,'provider':PROVIDER,'endpoint':ENDPOINT,
'base_url':'https://ai.zhenyangtang.com.cn/v1','max_active_requests':obj.max_active_requests}
result = {}
with app.test_request_context('/', method='POST', json=CONFIG):
app.login_manager._update_request_context_with_user(owner)
svc = AppService()
action = PAYLOAD['action']
if action == 'create':
assert not db.session.scalar(select(App.id).where(App.name == APP_NAME)), 'APP_NAME_ALREADY_EXISTS'
assert not db.session.scalar(select(ProviderModel.id).where(ProviderModel.tenant_id == tenant_id,ProviderModel.model_type == 'speech2text')), 'SPEECH2TEXT_NOT_EMPTY'
assert not db.session.scalar(select(TenantDefaultModel.id).where(TenantDefaultModel.tenant_id == tenant_id,TenantDefaultModel.model_type == 'speech2text')), 'DEFAULT_NOT_EMPTY'
ModelProviderService().create_model_credential(tenant_id,PROVIDER,'speech2text',ASR,
{'api_key':PAYLOAD['asr_key'],'endpoint_url':ENDPOINT,'endpoint_model_name':ASR,'language':'zh','initial_prompt':'','display_name':'Followup ASR isolated'},
'followup-asr-isolated-20261009')
ModelProviderService().update_default_model_of_model_type(tenant_id,'speech2text',PROVIDER,ASR)
obj=svc.create_app(tenant_id,{'mode':'chat','name':APP_NAME,'description':'Isolated synthetic-verified ASR and JSON extraction. Preview only; no clinical writes.','icon_type':'emoji','icon':'🎙️','icon_background':'#E4FBCC'},owner)
svc.update_app_site_status(obj,False)
from controllers.console.app.model_config import ModelConfigResource
inspect.unwrap(ModelConfigResource.post)(ModelConfigResource(),obj)
svc.update_app(obj, {'name':APP_NAME,'description':obj.description,'icon_type':obj.icon_type,'icon':obj.icon,'icon_background':obj.icon_background,'use_icon_as_answer_icon':False,'max_active_requests':1})
svc.update_app_api_status(obj,True)
from controllers.console.apikey import AppApiKeyListResource, BaseApiKeyListResource
token,status=inspect.unwrap(BaseApiKeyListResource.post)(AppApiKeyListResource(),obj.id)
assert status == 201
result={'public':public_state(obj),'private':{'api_key':token.token,'key_id':token.id}}
elif action in ('status','disable','enable'):
obj=current_app_owned()
if action != 'status':svc.update_app_api_status(obj,action == 'enable')
result={'public':public_state(obj)}
elif action == 'remove':
resource=PAYLOAD['resources'];obj=current_app_owned()
credential=db.session.get(ProviderModelCredential,resource['asr_credential_id'])
recorded_default=db.session.get(TenantDefaultModel,resource['asr_default_id'])
assert credential and credential.tenant_id==tenant_id and credential.model_name==ASR and credential.model_type=='speech2text', 'CREDENTIAL_IDENTITY_MISMATCH'
assert recorded_default and recorded_default.tenant_id==tenant_id and recorded_default.model_name==ASR and recorded_default.model_type=='speech2text', 'DEFAULT_IDENTITY_MISMATCH'
for other in db.session.scalars(select(App).where(App.tenant_id==tenant_id,App.id!=obj.id)).all():
features=(other.workflow.features_dict if other.workflow else {}) if other.mode in ('advanced-chat','workflow') else ({'speech_to_text':other.app_model_config.speech_to_text_dict} if other.app_model_config else {})
assert not features.get('speech_to_text',{}).get('enabled'), 'ANOTHER_APP_NOW_USES_ASR'
svc.update_app_api_status(obj,False)
# Only the precise new app key, via the deployed API controller.
from controllers.console.apikey import AppApiKeyResource, BaseApiKeyResource
key_id=resource['key_id']
if db.session.get(ApiToken,key_id):
inspect.unwrap(BaseApiKeyResource.delete)(AppApiKeyResource(),obj.id,key_id)
svc.delete_app(obj)
default=db.session.get(TenantDefaultModel,resource['asr_default_id'])
assert default and default.tenant_id==tenant_id and default.model_type=='speech2text' and default.model_name==ASR, 'DEFAULT_IDENTITY_MISMATCH'
# No service offers reset-to-empty; remove only this recorded, new, non-secret default row.
db.session.delete(default);db.session.commit()
ModelProviderService().remove_model_credential(tenant_id,PROVIDER,'speech2text',ASR,resource['asr_credential_id'])
assert not db.session.scalar(select(App.id).where(App.id==resource['app_id']))
assert not db.session.scalar(select(ProviderModel.id).where(ProviderModel.id==resource['asr_model_id']))
result={'public':{'removed_app_id':resource['app_id'],'speech2text_restored_empty':True}}
else:raise ValueError('UNKNOWN_ACTION')
print('OPERATOR_RESULT='+json.dumps(result,ensure_ascii=False,default=str))
@@ -0,0 +1,27 @@
"""Host-private Dify service invocation, emits no credentials."""
import json,os,pathlib,subprocess,sys
BASE=pathlib.Path(__file__).resolve().parent
os.umask(0o077)
action=sys.argv[1]
payload={'action':action}
resources=BASE/'resources.private.json'
if action=='create':
payload['asr_key']=(BASE/'asr-key').read_text().strip()
assert not resources.exists(), 'RESOURCE_FILE_ALREADY_EXISTS'
else:payload['resources']=json.loads(resources.read_text())
code='PAYLOAD='+repr(payload)+'\n'+(BASE/'dify_operator.py').read_text()
p=subprocess.run(['docker','exec','-i','dify_v1110_eera-api-1','python','-'],input=code,text=True,capture_output=True)
# Never print raw stdout/stderr: credentials may exist in structured output/errors.
lines=[s for s in p.stdout.splitlines() if s.startswith('OPERATOR_RESULT=')]
if p.returncode or len(lines)!=1:
# Private diagnostic file; callers must not copy it into public artifacts.
(BASE/'operator-error.private.log').write_text(p.stdout+'\n'+p.stderr)
print(json.dumps({'action':action,'exit_status':p.returncode,'result':'FAILED','diagnostic_private':True}))
sys.exit(p.returncode or 1)
data=json.loads(lines[0].split('=',1)[1])
if action=='create':
value={**data['public'],**data['private']}
resources.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n');resources.chmod(0o600)
env='DIFY_ASR_APP_KEY='+value['api_key']+'\nDIFY_ASR_APP_ID='+value['app_id']+'\nDIFY_ASR_BASE_URL='+value['base_url']+'\nDIFY_ASR_EXPECTED_MODEL=Qwen/Qwen3-ASR-1.7B\nDIFY_EXTRACTION_EXPECTED_MODEL=qwen3.6-35b\nDIFY_BINDING_REVISION=followup-dify-20261009-v1-'+value['config_sha256'][:16]+'\n'
(BASE/'dify-runtime.env').write_text(env);(BASE/'dify-runtime.env').chmod(0o600)
print(json.dumps({'action':action,'exit_status':p.returncode,'result':'PASS',**data['public']},ensure_ascii=False))
@@ -0,0 +1,42 @@
"""Synthetic-only HTTPS acceptance; Python 3.6+, never disables TLS checks."""
import hashlib,json,pathlib,re,ssl,sys,time,urllib.error,urllib.request,uuid
ENV=pathlib.Path(sys.argv[1])
WAV=pathlib.Path(sys.argv[2])
MODE=sys.argv[3] if len(sys.argv)>3 else 'all'
CANARIES=json.loads(pathlib.Path(sys.argv[4]).read_text(encoding='utf-8')) if len(sys.argv)>4 else ['紫色海豚','金色河流','银色树叶','红色石榴']
env=dict(line.split('=',1) for line in ENV.read_text(encoding='utf-8').splitlines() if '=' in line)
base=env['DIFY_ASR_BASE_URL'];key=env['DIFY_ASR_APP_KEY']
ctx=ssl.create_default_context()
def request(path,data,content_type,auth=True):
h={'Content-Type':content_type}
if auth:h['Authorization']='Bearer '+key
req=urllib.request.Request(base+path,data=data,headers=h,method='POST')
start=time.monotonic()
try:
with urllib.request.urlopen(req,context=ctx,timeout=200) as response:
code=response.status;body=response.read().decode()
except urllib.error.HTTPError as error:
code=error.code;body=error.read().decode()
return {'status':code,'elapsed_seconds':round(time.monotonic()-start,3),'body':json.loads(body)}
def audio():
boundary='synthetic'+uuid.uuid4().hex
body=('--'+boundary+'\r\nContent-Disposition: form-data; name="user"\r\n\r\nsynthetic-asr-acceptance-20261009\r\n--'+boundary+'\r\nContent-Disposition: form-data; name="file"; filename="synthetic.wav"\r\nContent-Type: audio/wav\r\n\r\n').encode()+WAV.read_bytes()+('\r\n--'+boundary+'--\r\n').encode()
return request('/audio-to-text',body,'multipart/form-data; boundary='+boundary)
r={'synthetic':True,'tls_verify':True,'check_hostname':ctx.check_hostname,'ssl':ssl.OPENSSL_VERSION,'mode':MODE,'app_id':env['DIFY_ASR_APP_ID'],'base_url':base,'binding_revision':env['DIFY_BINDING_REVISION']}
if MODE in ('all','asr'):
r['unauthorized']=request('/audio-to-text',b'','application/octet-stream',False)
r['asr']=audio()
text=r['asr']['body'].get('text','')
r['audio_only_canaries']={x:x in text for x in CANARIES}
r['asr_pass']=r['unauthorized']['status']==401 and r['asr']['status']==200 and all(r['audio_only_canaries'].values())
if MODE in ('all','chat'):
query='这是独立的合成 JSON 验收,不包含患者数据。请只输出 JSON 对象:{"canary":"BLUE_KITE_20261009","sum":42,"preview_only":true}。不要添加其他字段、解释或 Markdown。'
payload={'inputs':{},'query':query,'response_mode':'blocking','user':'synthetic-chat-acceptance-20261009','auto_generate_name':False}
r['chat']=request('/chat-messages',json.dumps(payload,ensure_ascii=False).encode(),'application/json')
answer=r['chat']['body'].get('answer','')
try:parsed=json.loads(answer)
except ValueError:parsed=None
r['chat_pass']=r['chat']['status']==200 and parsed=={'canary':'BLUE_KITE_20261009','sum':42,'preview_only':True} and bool(r['chat']['body'].get('message_id')) and '<think>' not in answer
r['passed']=all(r.get(k,True) for k in ['asr_pass','chat_pass'])
print(json.dumps(r,ensure_ascii=True,indent=2))
sys.exit(0 if r['passed'] else 1)
@@ -0,0 +1,56 @@
"""Local synthetic mock-server tests, no model calls or secrets."""
import http.client
import json
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import bridge
KEY = b'synthetic-only-unit-test-secret'
class Upstream(BaseHTTPRequestHandler):
calls = 0
slow = False
entered = threading.Event()
def log_message(self, *args): pass
def do_GET(self):
body = b'{}'; self.send_response(200); self.send_header('Content-Length','2'); self.end_headers(); self.wfile.write(body)
def do_POST(self):
type(self).calls += 1
type(self).entered.set()
self.rfile.read(int(self.headers['Content-Length']))
if type(self).slow: time.sleep(0.25)
assert self.headers['Authorization'] == 'Bearer ' + KEY.decode()
body = b'{"text":"synthetic-only-canary"}'
self.send_response(200);self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
class BridgeTests(unittest.TestCase):
def setUp(self):
Upstream.calls=0;Upstream.slow=False;Upstream.entered.clear()
self.u=ThreadingHTTPServer(('127.0.0.1',0),Upstream)
self.b=bridge.Server(('127.0.0.1',0),bridge.Handler,key=KEY,upstream=self.u.server_address)
for s in [self.u,self.b]: threading.Thread(target=s.serve_forever,daemon=True).start()
def tearDown(self):
for s in [self.b,self.u]:s.shutdown();s.server_close()
def call(self,body=b'x',headers=None,path='/v1/audio/transcriptions',method='POST'):
h={'Authorization':'Bearer '+KEY.decode(),'Content-Type':'multipart/form-data; boundary=test'}
if headers: h.update(headers)
c=http.client.HTTPConnection(*self.b.server_address,timeout=2);c.request(method,path,body,h);r=c.getresponse();result=(r.status,r.read());c.close();return result
def test_valid_fixed_upstream(self):
self.assertEqual(self.call(),(200,b'{"text":"synthetic-only-canary"}'));self.assertEqual(Upstream.calls,1)
def test_auth_denied_without_upstream(self):
self.assertEqual(self.call(headers={'Authorization':'Bearer wrong'})[0],401);self.assertEqual(Upstream.calls,0)
def test_body_bound_before_read(self):
self.assertEqual(self.call(headers={'Content-Length':str(bridge.MAX_BODY+1)})[0],413);self.assertEqual(Upstream.calls,0)
def test_fixed_path_only(self):
self.assertEqual(self.call(path='/v1/chat/completions')[0],404);self.assertEqual(Upstream.calls,0)
def test_concurrency_exactly_one(self):
Upstream.slow=True;out=[];t=threading.Thread(target=lambda:out.append(self.call()[0]));t.start();self.assertTrue(Upstream.entered.wait(1));self.assertEqual(self.call()[0],429);t.join();self.assertEqual(out,[200]);self.assertEqual(Upstream.calls,1)
def test_rate_429_no_retry(self):
self.b.gate=bridge.Gate(rate=0,burst=1);self.assertEqual(self.call()[0],200);self.assertEqual(self.call()[0],429);self.assertEqual(Upstream.calls,1)
def test_upstream_down_no_retry(self):
self.b.upstream=('127.0.0.1',1);self.assertEqual(self.call()[0],502);self.assertEqual(Upstream.calls,0)
def test_wrong_content_type(self):
self.assertEqual(self.call(headers={'Content-Type':'application/json'})[0],415);self.assertEqual(Upstream.calls,0)
if __name__=='__main__':unittest.main(verbosity=2)
@@ -0,0 +1,40 @@
# Follow-up preview runtime (2026-10-09)
This is an opt-in, diagnosis-ID-scoped preview. It never permits clinical adoption; full audio/semantic verification remains false. Do not use a preview fingerprint as full verification. Preview-origin tasks remain non-adoptable after configuration changes.
## Dedicated media tools
The CentOS 7 Webhost needs a private FFmpeg/FFprobe path, not a system upgrade. Installed location is `/opt/followup-audio-tools/ffmpeg-9.0.2/` (no PATH or OS package changes). Source was downloaded from `https://ffmpeg.org/releases/ffmpeg-9.0.2.tar.xz`, SHA256 `8c3850283eb25fa026482078a04051e0be17347b09ef81a0849bec15a96e002e`, with detached PGP signature verified against the official release key `FCF986EA15E6E293A5644F10B4322F04D67658D8`.
It was built on the AI host using GCC 12, `nice -n 19 make -j1`, static libc, generic x86-64 / Linux 3.2 baseline, without network protocols or optional external codec libraries. Build flags:
```sh
./configure --prefix=/opt/followup-audio-tools/ffmpeg-9.0.2 \
--disable-autodetect --disable-shared --enable-static --extra-cflags=-O2 --extra-ldflags=-static \
--disable-x86asm --disable-doc --disable-debug --disable-network --disable-everything \
--enable-ffmpeg --enable-ffprobe --enable-avcodec --enable-avformat --enable-avfilter --enable-swresample \
--enable-protocol=file,pipe --enable-demuxer=mov,mp3,wav,amr,aac \
--enable-parser=aac,aac_latm,mpegaudio \
--enable-decoder=mp3,mp3float,mp3adu,mp3adufloat,mp3on4,mp3on4float,aac,aac_latm,amrnb,amrwb,pcm_s16le,pcm_s16be,pcm_u8,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le \
--enable-encoder=pcm_s16le --enable-muxer=wav \
--enable-filter=aresample,pan,anull,aformat,atrim,asetpts,abuffer,abuffersink
nice -n 19 make -j1 ffmpeg ffprobe
```
Binary SHA256: ffmpeg `a2c81c9049a5e919d8f5ce9c246580f9f6cf8a38aaece8c79ed0fd893c35453e`; ffprobe `af8f5eb67ea87beca9ec7fb27f3355cf918fabee0d88a7db628bf511c691a680`. Both executed successfully on the Webhost; synthetic stereo WAV was decoded and split. This minimal build is for the PCM two-stage driver, not an assertion that legacy MP3 re-encoding, all media encodings, or real hour-long ASR has passed.
## Dify and TLS
Use the isolated App provisioned by `../followup-audio-dify/`, HTTPS only. On this host PHP cURL/NSS rejects the current certificate; native PHP OpenSSL verifies it successfully. Set the feature's explicit `HTTP_TRANSPORT=openssl_stream`, not TLS verification off and not automatic fallback. The controlled child process maintains parent authorization/lease heartbeats. Other application HTTP clients are unchanged.
The Dify App owns model/generation parameters. Configure both explicit stage protocols, expected models and binding revisions; changing App/default/provider configuration requires a new revision and preview verification. Keep extraction thinking unset locally and `EXTRACTION_RESPONSE_FORMAT=prompt_json`; no claim that local OpenAI response_format/max_tokens are transmitted through Dify.
## Release constraints
- `ENABLED=true` only with `PREVIEW_ONLY=true`, explicit `TEST_DIAGNOSIS_IDS`, fresh preview fingerprint, stable private encryption key; `AUDIO_VERIFIED=false`.
- Use an independent `followup-audio-preview` consumer, concurrency 1. Do not restart prescription workers, PHP, Dify or GPU services.
- Back up source/env/static assets and affected schema/data. Additive DDL must use a bounded session lock budget; prefer explicit INSTANT columns and fail instead of silently table-copying.
- Keep existing untracked production overlays. Coordinate the two existing auto-pull lock files; never reset/clean the live repository.
- Build with `vite build` only. Copy new hashed assets additively, retain old assets for active browsers, then atomically replace index.html; do not invoke the destructive release.mjs on the live directory.
- Rollback stops only the new consumer and disables preview, restores changed source/index/env with hashes, and retains additive tables/columns/audit. Never roll back the entire business database or rewrite remote master to undo a release.
- Keep API credentials, raw recordings, clinical snapshots and runtime state outside Git. Application cleanup does not imply Dify copies were deleted.
+114
View File
@@ -0,0 +1,114 @@
# IAM v2 关联管理与本人跨平台快捷登录
## 默认状态与部署次序
首次部署 `iam.v2_enabled`、`iam.v2_management_enabled`、`iam.v2_launch_enabled` 都默认 **false**。全局未启用时不登记新来源会话,原密码、企微、IAM 入站登录保持原路径。产生v2关联后,全局核心必须保持true以持续中央停用检查、签名事件和代际补偿;维护/回退优先关闭management与launch两个新流程开关,不能以关闭全局核心绕过这些检查。本文只描述源码;生产开关、迁移、真实浏览器及三端联调需另行验收。
1. 备份部署版本与配置,审查并执行 `server/database/migrations/20261029_iam_v2.sql`(按实际表前缀调整)。此迁移只加七张表及独立菜单/权限,不给现有角色自动授予权限,不改账号与角色。
2. 中央先部署 v2 绑定墓碑、幂等恢复、固定来源回查、版本检查、源/目标访问授权、密码设置协议与签名事件。旧 v1 token 不得获得新管理权限。
3. 向 IAM 注册 application `zyt` 的固定 HTTPS 回调;ZYT→ERP 固定目标 `zmxy-erp`;IAM 管理后台/员工工作台可进入本人 ZYT 或 ERP,不增加 ERP→ZYT 按钮。OIDC client 追加精确 self-link 回调,禁用任意重定向。
4. 用一次性合成账号完成三端测试后再开启 v2。配置放服务器私密环境,不写仓库或日志。
```ini
[IAM]
V2_ENABLED = false
V2_MANAGEMENT_ENABLED = false
V2_LAUNCH_ENABLED = false
V2_TOKEN = <dedicated-login-v2-credential-at-least-32-chars>
V2_MANAGEMENT_TOKEN = <different-management-v2-credential-at-least-32-chars>
V2_INTROSPECTION_TOKEN = <distinct-callback-credential-at-least-32-chars>
V2_EVENT_SECRET = <distinct-HMAC-event-key-at-least-32-chars>
ERP_URL = https://<ERP-origin>
ERP_CALLBACK_URL = https://<ERP-origin>/basic-api/api/erp/iam/v2/launch/callback
PORTAL_URL = https://<IAM-portal-origin>
V2_SOURCES_JSON = {"iam-admin":"https://<IAM-origin>/admin/v1/iam/v2/launch/continue","iam-portal":"https://<IAM-origin>/portal/v2/launch/continue"}
```
中央credentials数组分别注册:登录凭据 `V2_TOKEN` 仅 `binding:read,binding:self,password:setup,launch:issue,launch:accept`;管理凭据 `V2_MANAGEMENT_TOKEN` 仅 `identity:search,identity:create,binding:read,binding:manage`。identities/operations/audit/batch/jobs固定使用管理凭据,缺失时不fallback登录或v1凭据;target `zyt` 只接受 `iam-admin` / `iam-portal`。
`API_URL`、`PUBLIC_URL`、`ISSUER`、OIDC client 配置沿用原配置。`ERP_URL/PUBLIC_URL/PORTAL_URL` 是固定 origin,不接受浏览器 URL。新功能的 v2 凭据与原 `APPLICATION_TOKEN` 分离。
## 固定端点
源应用所有路径前缀 `/adminapi/iam/v2`:
- `POST /proofs/introspect`、`POST /sessions/check`:专用 Bearer callback credential,不接受业务 token 代替。回包为中央约定的原生 JSON,不包业务 envelope。
- `POST /events/revocation`:`X-IAM-Signature=sha256=<HMAC-SHA256(raw-body)>`,`X-IAM-Event-ID` 必须等于 `body.id`;RFC3339 occurredAt、未来最多 60 秒,持久化 event ID + digest 幂等;耐久outbox旧时间事件仍可重试,不因超过5分钟被拒绝。旧 bindingVersion 只撤销旧/未知来源代际,不覆盖较新关联或另一员工的新会话;同业务token仍有新代际SID时保留token。历史本地无镜像时按签名事件externalAccountId或中央employeeId精确查询补齐映射,不从姓名/手机号猜测;无代际人员/授权事件在event handler回查当前中央状态后决定撤销,避免晚到事件踢掉重新授权会话。
- `POST /launch/start`:同源、当前业务 token + 独立 HttpOnly source SID;只返回目标 `/iam/launch?source=zyt&intent=...`,在新标签页打开。
- `GET /launch/continue?transaction_id=...&intent=...`:IAM 注册的固定来源 continuation;目标 prepare 必须原样附加 opaque intent。比对源 HttpOnly intent cookie、源 SID、源 sessionVersion、固定两应用 ID 后,隐藏表单 POST 到 **`ERP_CALLBACK_URL`**(生产公开反代前缀为 `/basic-api/api/erp/...`,必须与中央注册精确一致)。grant 和业务 token 均不进 URL。
- `POST /self-link/start` → `GET /self-link/callback`:当前本地近期认证 + OIDC code/PKCE/nonce 证明 IAM 同一用户;后端提交已验证 ID token,中央独立验证。前端没有指定个人 employee ID 的能力。
- `POST /password-setup` → `GET /password-continue?request_id=...&state=...`:只对本人已验证且待设置密码的 IAM 账号;中央初始返回 url/expiry/requestId,源 cookie + SID 绑定请求;continuation 隐藏表单 POST 到固定 `PORTAL_URL/portal/password-setup/authorize`。实际密码只在 IAM 页面输入。
用户 API 使用原业务 `{code,data,msg}` envelope。管理:accounts/identities/operations/audit/batch/jobs。每次 mutation 使用前端稳定 `Idempotency-Key`,自动 HTTP retry 关闭;中央按同一业务 payload 和 key 恢复已执行结果(proof 可刷新,不重复副作用)。operation/job 查询限定创建操作者及当前目标数据范围。
## 账号、会话与权限
- 新建来源会话保存独立浏览器 SID、原数据库 session ID、业务 token 的 SHA-256、账号凭据版本指纹、绑定employee/version快照、不可被续期更新的认证方法/时间、撤销版本。数据库会话轮换/到期、账号停用/删除、密码/企微关联/管理员标记改变立即使来源证明失效。
- 密码登录登记前再次真正核对密码 hash,不接受开发免密开关。企微入口的 TLS 必须校验后才登记 `wecom`。旧会话首次通过密码验证,或用原企微入口重新登录后登记;普通未关联业务使用不受影响。OIDC 使用原始 `auth_time`,缺失时不算近期认证。
- 每次管理写要求 5 分钟内认证、独立动作权限、现有 DataScope。权限:`iamV2/read|bind|create|unbind|rebind|batch`;不存在“未登记路由默认许可”的依赖。
- root、管理员/系统管理员/超级管理员角色或持有 IAM 管理写权限的目标视为敏感账号;仅本地 root/管理员类角色具备对应动作权限并完成近期核验时,可提交单人待审操作。中央返回 pending + `PROTECTED_ACCOUNT_REVIEW_REQUIRED` + 固定 `/admin/iam/review?request=...`;界面新标签中央复核,批准后保持相同请求体/幂等键、新 proof 重试。无中央批准仍不执行,普通 IAM 管理角色不具备此特权。批量预检将其列为 review,不发送中央,不静默跳过核验。
- 中央身份和授权是真源;本地绑定表是最长 30 秒快照。已关联账号的活跃业务请求在快照超时后回查;失权、版本变更、签名事件撤销来源 SID 和业务会话。服务不可用时相关受保护请求失败关闭。不宣称空闲客户端会在 30 秒内主动收到推送。
- 解绑/换绑保留本地业务账号和历史记录。`iam_local_identity` 是开户幂等账本,不是历史绑定全量镜像,永不删除。v2 撤销墓碑拦截旧账本自动重绑;中央旧版 v1 必须同样维护墓碑。较旧或相同版本的 verified 状态不能覆盖本地 revoked。`binding_revoked.bindingVersion` 是旧代际撤销上界;人员停用/应用失权事件只撤销会话并过期快照,不建立永久绑定墓碑。中央审核的新显式绑定可恢复登录,但自动开户分支仍拒绝墓碑。
- 管理列表来自所有可见本地账号并回查中央,首次展示历史绑定;按状态筛选基于已对账快照,未读取过的历史行应先在“全部”中分页核验。姓名/手机号不是自动合并依据。批量用明确 local ID/employee ID 映射预检。
## IAM 管理后台/员工工作台 → ZYT target
中央注册 `zyt.launchUrl=PUBLIC_URL/admin/iam/launch`、`targetDeliveryUrl=PUBLIC_URL/adminapi/iam/v2/launch/callback`;`V2_SOURCES_JSON` 与中央两条 sourceContinueUrl 必须相同,来源只允许 iam-admin/iam-portal。
前端 `/admin/iam/launch` 先清除 URL 中的 intent/ticket,再调用 `POST /launch/prepare`。后端保存固定来源、PKCE、浏览器 hash 与已有本地账号,设置 HttpOnly Secure SameSite=None target cookie。中央 sourceContinueUrl 的 transaction_id 必须一致,后端追加原 opaque intent;已有 KC cookie 不是必要条件。
`POST /launch/callback` 核验固定来源 Origin、target cookie、单次事务后兑换 grant;已登录用户冲突在任何自动开户前拒绝。仍通过旧 IamAccountProvisioner 的持久账本/角色2开户,已有账号角色/密码不改。只读回查中央绑定完成后产生60秒一次票据。`POST /launch/exchange` 再比对当前 token 和独立 source cookie,成功才调用 LoginLogic 签发本地token,认证方法标记 iam_launch 并保留真实原authTime。账号不一致只显示显式退出当前浏览器并返回IAM重新发起,不静默替换。
目标来源代际保存在 `iam_v2_target_session`。活跃业务请求最长30秒调用中央 `/launch-authorizations/check`,仅检查employee/target授权与来源绑定代际,不把普通source logout当作全局登出。源 introspect/sessions-check 回调只查本地数据,绝不递归中央,避免中央state行锁死锁。
## 本地验证
```sh
php server/tests/IamV2SourceTest.php
php server/tests/IamV2TargetTest.php
php server/tests/IamV2RouteContractTest.php
NODE_PATH=admin/node_modules node server/tests/IamV2UiTest.mjs
php server/tests/IamLoginTransactionTest.php
php server/tests/IamProvisioningTest.php
php server/tests/IamOidcClientTest.php
NODE_PATH=admin/node_modules node server/tests/IamLoginUiContractTest.mjs
```
SQLite 合成测试不加载生产 `.env`、不发网络、不修改真实用户、角色或授权。UI 测试编译四个组件并执行新标签页处理逻辑,不能替代三端真实浏览器(Cookie/SameSite/新标签页)验收。原前端全量 typecheck 存量 60 条诊断,需按基线比较,不能批量掩盖。
## 回退
已有v2状态时先将 `V2_MANAGEMENT_ENABLED=false`、`V2_LAUNCH_ENABLED=false`,保持 `V2_ENABLED=true` 和当前安全核心;管理写/个人关联密码写/新的委托事务停止,普通授权核验、事件和代际补偿继续。仅可回到同样保持这些核心能力的兼容版本,不能盲退到无v2检查的旧代码。只有从未激活、七表无v2业务状态且全局仍false的首次部署,才可还原本次原文件与原index。保留七张新表、旧开户账本、事件与审计记录、所有真实账号和业务数据。关闭新流程开关停止新的委托登录/管理证明,不撤回中央已执行的人事操作;错误关联通过有审计的显式解绑/换绑恢复,而非删表或恢复旧数据库。
## 2026-10-29 只读生产入口核对与发布步骤
本轮只读核验(未部署、未迁移、未开关):
- SSH 别名 `zyt`;Nginx vhost `/www/server/panel/vhost/nginx/admin.zhenyangtang.com.cn.conf` 的实际 root 是 `/www/wwwroot/zyt/server/public`,PHP include 为 `enable-php-82.conf`,现有 rewrite 经 `index.php?s=...` 进入 ThinkPHP。
- 运行仓库 `/www/wwwroot/zyt` 的 HEAD 是 `e183e1cc62d3205576d5dfabd555e78bb86654c8`;它与开发基线 `bcd42a5c399904ec3f9454c6fe1a74bde511ca2c` 不同,禁止整树覆盖。首版9个原文件哈希与开发基线完全一致,17个新增路径未碰撞;本轮追加改动仍须对最终发布manifest重新核对。
- PHP 二进制 `/www/server/php/82/bin/php` 为 8.2.35;MySQL CLI 为5.7.44(此处不是数据库服务器版本声明)。服务私密配置留在 `/www/wwwroot/zyt/server/.env`,本轮未读取或输出凭据。
- 公网只读 `GET https://admin.zhenyangtang.com.cn/adminapi/iam/config` 返回 `code=1`、`enabled=true`、既有 `/adminapi/iam/start` 登录地址;v2 仍未发布。
- `admin/scripts/release.mjs` 会先删除整个 `server/public/admin`。不要在生产直接运行 `npm run build`;它与 `docs/iam-quick-login.md` 要求的保留旧哈希资源冲突。仓库中的 Docker 示例不是当前 Nginx/PHP-FPM 运行入口,ERP ACR 发布脚本也不是 ZYT 发布入口。
得到发布授权后的受控步骤:
1. 从指定已提交版本的干净副本构建,运行完整 `scripts/test-iam-v2.sh`、基线差分与 `vite build`;只打包本次明确变更清单和前端构建,附各文件SHA256。不要携带 `.env`、`.local`、上传目录或开发库。
2. 只读核对线上所有被替换文件与发布前manifest哈希、新增路径无碰撞;若不一致先重审,不覆盖他人的新发布。保留服务器原文件/静态index及独立备份目录,保存私密配置备份与正常数据库备份。
3. 在确认实际表前缀后执行 `20261029_iam_v2.sql`,使用既有受保护的MySQL凭据方式,不能把口令放命令行/日志。MySQL DDL不因后面的事务自动回退;逐表验证七表/索引和菜单节点,保留旧开户账本。菜单不自动给业务角色授权。
4. 中央先完成v2迁移、凭据/固定URL/回查注册、原生IAM本人入口和中央复核部署;ZYT新代码先保持 `V2_ENABLED=false`。配置完整的API/portal/ERP公开callback URL及两条来源映射,尤其ERP公开 `/basic-api` 前缀。
5. 后端按审核清单更新;静态资源先增量加入旧资源目录,最后原子切换index.html,不删旧哈希文件。按实际OPcache配置处理源码重载,不把CLI `opcache_reset()`当成FPM已刷新,不重启无关服务。
6. 先验证开关关闭时原登录/业务行为,再用授权测试账号开启v2验收:密码/企微→ERP、IAM管理后台本地session无KC cookie→ZYT/ERP、员工工作台→两端、同人/异人多标签、已有账号/角色2新开户、密码owner双阶段、敏感单人中央审批及批量跳过、签名事件/30秒补偿。逐项核对真实页面与后端会话,不以HTTP200代替登录验收。
7. 初次未激活部署(全局false且七表空)可恢复发布前文件/index;一旦已有v2状态,回退优先只关闭管理/新登录两个开关、保持全局安全核心true,不盲退到旧代码;保留七表、事件、绑定历史、中央操作与所有业务数据。不要用整库恢复或删除IAM员工来回退代码。普通source logout按约定不是全局登出。
### 最终发布基线差异(追加)
最终32个变更路径核验:12个原文件中11个与开发基线相同,`admin/src/stores/modules/user.ts` 在线另有 `serverTimeOffsetMs` 状态、reset清理及 `web_consultation_policy.server_time` 的偏移计算;20个新增路径未发现碰撞。该生产逻辑必须保留。**当前以bcd基线生成的整包前端仅为本地构建验证,不直接用于生产发布。** 发布方应先获取/核验实际 `e183e1c` 及线上工作区差异,以其为发布副本应用本次IAM提交(保留时间偏移逻辑)再重新构建;不能通过覆盖生产user store或忽略差异来通过哈希校验。生产回退使用真实发布前备份,而非本地bcd基线副本。
### 保留生产前端的独立发布副本
只读补核了实际 `admin/src`、`admin/public`、index.html、package/lock、Vite/PostCSS/Tailwind、typings与TS配置,共710个输入,发现22个已变更文件和17个新增文件,无缺失或symlink。已有网页问诊/接诊、文字记录、复诊到期提醒/统计、处方订单、桌面下载等生产逻辑均按哈希快照保留。
独立前端副本位于 `/Users/long/Work/zyt-iam-v2-release-20261029`,分支 `codex/zyt-iam-v2-live-frontend`。它基于实际文件快照,而不是线上Git HEAD;仅应用10个受控IAM前端文件,705个非IAM生产输入逐字节不变。该副本仅用于前端构建,不使用其基线PHP目录发布后端。主实现树已三方保留生产user store的服务端时间偏移,并验证getUserInfo/reset行为。
没有读取生产.env:通过公开已部署JS核实 `baseUrl="https://admin.zhenyangtang.com.cn//"`、`timeout=60000`,最终构建显式使用 `VITE_APP_BASE_URL=https://admin.zhenyangtang.com.cn/` 与 `VITE_APP_REQUEST_TIMEOUT=60000` 保持一致。发布审查应结合 `frontend-production-manifest.json`、`production-frontend-drift.patch`、`release-frontend-manifest.json`、`public-build-config-match.json` 与最终构建包,不采用前面bcd基线的旧构建结果。生产原文件CRLF/尾空白保留原样,不为通过格式检查改写业务源文件。
+53
View File
@@ -0,0 +1,53 @@
# 用甄养堂账号登录行知(AI 模块单点登录,2026-10-10)
行知(AI 工作助手)的登录页增加“使用甄养堂账号登录”:跳到甄养堂的登录确认页,确认后回到行知,行知首次登录自动开通成员账号,并同时完成“绑定甄养堂账号”(只读授权)。密码只在甄养堂输入和校验,不经过行知。
## 改动范围(都在 AI 模块 `server/app/mcp` 内,原有后台接口、Logic、中间件、配置未改)
| 文件 | 说明 |
|---|---|
| `controller/SsoController.php`(新增) | `GET /mcp/sso/authorize` 登录确认页;`POST /mcp/sso/whois`、`/approve`、`/login` 页面用;`POST /mcp/sso/token` 行知服务器换取结果 |
| `service/SsoService.php`(新增) | 客户端与回调地址校验、浏览器里已登录后台会话的识别、一次性授权码(2 分钟、只能用一次,文件锁防并发兑换) |
| `service/GrantService.php`(AI 模块自身) | `issue()` 拆成 `verifyPassword()` + `issueFor()`,`assertAdminUsable()` 改为 public;绑定接口 `/mcp/auth/grant` 的行为不变 |
| `service/McpConfig.php`(AI 模块自身) | 新增 `ssoEnabled / ssoClientId / ssoClientSecret / ssoRedirectUris` |
| `server/tests/AiMcpSsoTest.php`(新增) | 见“测试” |
不需要执行新的数据库迁移;不新增权限点(沿用 `ai.mcp/access`)。
## 流程与门禁
1. 行知把浏览器带到 `/mcp/sso/authorize?client_id&redirect_uri&state`。`client_id`、`redirect_uri` 必须与 .env 登记的完全一致,否则只显示原因、不显示登录框、不跳转。
2. 确认身份,两种方式:
- 浏览器里已登录甄养堂后台(localStorage `like_admin_token`):显示“你已登录甄养堂后台:某某”,点“以此账号登录”。只认电脑端、手机端的正常登录(terminal 1/2),AI 后台浏览器(8)、企微客服端(7/9)和过期会话一律不认。
- 输入账号密码:与“绑定甄养堂账号”同一套校验(按 IP 限流、连续错误锁定、停用、企微强制绑定、`ai.mcp/access` 权限点、未改初始密码)。
3. 带一次性授权码回到行知;行知服务器用客户端密钥调用 `/mcp/sso/token`(经过 `ALLOWED_IPS` / Origin 检查),得到账号信息和只读令牌(与绑定签发的授权相同,同一行知实例的旧授权自动作废)。
4. 页面:严格 CSP(脚本只认本页 nonce、`frame-ancestors 'none'`、`form-action 'none'`)、`X-Frame-Options: DENY`、`Cache-Control: no-store`、`Referrer-Policy: no-referrer`,并覆盖全局中间件的 `Access-Control-Allow-Origin: *`。
5. 审计:`zyt_ai_access_log` 的 `sso.approve`、`sso.login`(拒绝时)、`sso.token`。
## 上线步骤
1. 同步上面四个文件到生产(`SsoController.php`、`SsoService.php`、`GrantService.php`、`McpConfig.php`)。
2. 在行知管理端 → 组织连接器 → 甄养堂业务系统 → “账号登录行知” → “生成密钥”,把显示的四行加到生产 `.env` 的 `[AI_MCP]` 段(与 `ENABLED = true` 同一段),例如:
```ini
SSO_ENABLED = true
SSO_CLIENT_ID = xingzhi
SSO_CLIENT_SECRET = (行知管理端生成,只显示一次)
SSO_REDIRECT_URIS = http://xz.zhenyangtang.cn:8787/api/auth/sso/zyt/callback
```
3. 重新加载 PHP(PHP-FPM / 宝塔里重载或重启 PHP),然后在行知管理端勾选“开启:登录页显示这个按钮”并保存。
4. 如设置了 `ALLOWED_IPS`,需包含行知服务器的出口 IP(`/mcp/sso/token` 由行知服务器调用);登录确认页本身面向员工浏览器,不受这项限制。
5. 停用:把 `SSO_ENABLED` 改为 false(或删掉这几行)并重载 PHP;行知侧也可在管理端取消勾选。
## 测试
```bash
source ~/.cache/zyt-tools/scripts/zyt_env.sh # 本地 PHP 8.2 + MariaDB(zyt_mcp_test)
export PHP_AI_MCP_SSO_ENABLED=true PHP_AI_MCP_SSO_CLIENT_ID=xingzhi
export PHP_AI_MCP_SSO_CLIENT_SECRET=<至少 32 位> PHP_AI_MCP_SSO_REDIRECT_URIS=http://127.0.0.1:18787/api/auth/sso/zyt/callback
# 服务端与测试进程使用同一组 SSO 配置
AI_MCP_TEST_MYSQL=1 AI_MCP_TEST_BASE_URL=http://127.0.0.1:8099 $PHP server/tests/AiMcpSsoTest.php
```
覆盖:确认页只对登记的客户端显示(安全响应头、未登记地址不回显)、账号密码确认的各项门禁、一键确认只认电脑端/手机端会话、授权码要客户端密钥并与回调地址一致且只能用一次、确认后被停用的账号兑换失败、换来的令牌可直接使用并替换同一实例的旧授权、审计、原有绑定接口不受影响。原有 `AiMcpUnitTest`、`AiMcpHttpContractTest`、`AiMcpConsoleTest`、`AiMcpPerfTest` 回归通过。与行知的端到端联调(真实 zyt 代码 + 行知登录页,账号密码与一键两种方式)也已通过。
+177
View File
@@ -0,0 +1,177 @@
# 回访录音提炼:实现与发布门禁
## 当前交付边界
源码在隔离工作副本 `/Users/long/.codex/worktrees/followup-audio/zyt`。原目录 `/Users/long/Work/zyt` 的已有源码保持不变;功能位于 `codex/followup-audio` 分支,初始提交 `70be2fc70`。未推送、未迁移生产、未部署。入口默认关闭。
已完成网页患者编辑入口、诊单绑定私有分片上传、独立持久异步任务、Dify原始音频传递、可编辑审阅草稿、显式人工确认、多表原子写入、同日真实记录明细、历史跟踪备注、来源审核轨迹及90天清理。
**真实模型门禁仍未通过**:9月29日本地 Dify 探针返回 `CONFIG_MISSING`;10月7日已按用户指定兼容接口发起合成音频检查,返回 `AUDIO_NOT_PROCESSED`,详见文末。不能把 HTTP 200、上传成功或文本能力当成音频识别成功。媒体测试中的完整一小时WAV→MP3、HTTP回环模型和浏览器合成数据不是实际Dify识别验收;混合口音需代表性脱敏样例。
## 2026-10-08 双声道修订(优先于下方早先混音验收)
- `asr_then_llm` 对双声道默认按15秒原始时间窗分别转写左右声道,不再使用混音。`ASR_STEREO_CHUNK_SECONDS=15`(1..30)独立于mono的120秒设置;两声道总段数仍上限1000,>2声道明确拒绝。
- 新checkpoint v2和提供方指纹绑定声道数、`separate-fixed-windows-v1`策略、窗口长度与exact-zero策略。证据增加不可修改的`channel`、原始区间;mono/旧结果兼容读取,旧未知请求不能改绑/重放。
- 只有转换后的PCM16k/s16le逐字节全零,才以`local_silence`本地完成并保留区间,无上游请求ID。任何非零低音量仍送ASR;这不是VAD或按音量丢段。
- 页面增加左右声道片段、原音/左/右回听和人工角色映射:`unconfirmed`、`left_service`、`right_service`。患者侧标签是“患者/家属端”,不能只按声道推定本人。角色标注不自动重提炼;保存/切换角色取消全部选中,须重新逐项核对。新stereo未保存角色禁止apply,角色及审核人进入加密审计。
- 4份获准录音在私有一次性MySQL均通过完整Upload→queued→独立Worker→左右ASR→Qwen→review;338个声道时间窗全部覆盖,314次真实ASR、24个本地数字静音、4次提炼。原始文件不变,全部11个候选初始未选中且须复核。
- 按转写上下文核对,仍有约数变精确值、含混姓名/电话号码、未提及病史补阴性等错误,某样本还重复生成大量待核实文字。**分声道实现通过,不等于内容准确度通过;4份语义门槛仍FAIL**,也未取得逐字人工回听金标准。
- 隔离诊单实际测试13项通过:未确认角色不能写入、确认角色清选择、旧版本拒绝、伪造channel拒绝、切换角色重审、明确采纳1个有依据字段、审计带角色、重复新增0行;没有真实患者业务写入。
- 本轮后端26个脚本、前端64项、质量41项及独立复核通过;全量类型检查仍60项基线诊断,无本功能新增。完整前端构建通过,无发布脚本。原生浏览器WebAudio/实机听感验收仍缺,严格mock和源码审核不能替代实际试听。
- 所有生产开关继续关闭。本轮没有部署应用或改变模型服务/GPU;不会因为用户猜测一边客服一边患者,就预填已确认角色。下方早先混音、缓存导入与失败记录保留为历史证据。
## 2026-10-08 最新结论:两阶段链路可用,语义准确度门禁未通过
已增加 `asr_then_llm`:真实音频分片 → ASR 转写 → 可配置文本模型提炼 → 人工审阅。原件、转写、提炼响应分别留存,不把纯文本输入冒充模型听过音频;前端显示转写进度与失败后保留的原文。该结论优先于本文下方历史记录,**不等于功能已获准上线**。
- 用户授权的 4 段录音,独立转写共 23/23 片段成功,约 41.8 分钟。没有逐字人工听写金标准,不能据此报告 ASR 准确率,也不代表所有方言/一小时真实模型通过。
- 使用这些真实 ASR 缓存,当前 Qwen 的 4 份 V2 结果通过结构校验,但逐项对照原文发现提问当症状、约数精确化、未提及病史补阴性、说话人/机构归属错误。**4 份均未通过严格语义验收**;所有 13 个候选均需复核、未自动选中。身份可绑定任意本地测试诊单,不意味着可以忽略录音内的患者/家属区别。
- 完整原生 Upload → 持久队列 → 独立 Worker → 实际 ASR → 实际 Qwen → review 已用 1 段录音在隔离 MySQL 跑通;其他准确度评估复用缓存,不冒充重复执行完整链路。
- 只在一次性测试诊单明确审阅后采纳有支持的字段;含糊血糖、未经确认病史等不写入。另将已校验的真实缓存结果显式导入本地验收任务测试日常记录,不冒充新的 ASR 请求。冲突刷新会取消选择,必须重新审阅;重复确认不增行。
- 原生首轮有一个 ASR 片段超时终态不明,保留 `needs_reconciliation`,没有清除或盲目重发。独立缓存的成功不改变这个旧请求的状态。
- vLLM 对 `uniqueItems` 返回 HTTP400;生成 schema 已适配,服务端仍拒绝重复引用与重复枚举。开启 thinking 的 4 次请求耗尽 8192 输出预算而不完整;显式关闭 thinking 后结构输出完成,**但语义质量仍失败**,不可拿结构成功替代准确度。
- 所有生产开关保持关闭;未部署本功能、未执行生产迁移、未改真实患者记录。本轮本地 MySQL 使用专用随机 `fa_pipeline_*` 库和真实 Access/Store/Worker/Apply 服务,不是生产登录态浏览器验收。
### 两阶段配置与恢复约束
使用 `server/.env.followup-audio.example` 中 `QWEN_DRIVER=asr_then_llm` 及独立 `QWEN_ASR_*`、`QWEN_EXTRACTION_*` 配置;`openai` 槽位也支持同样结构。名称只是逻辑槽位,不自动更换供应商。模型地址、密钥、模型名、chunk策略、输出格式/schema/citation版本及 thinking 选项均绑定验证指纹。
- ASR 默认 120 秒 PCM16k 单声道分片,整段覆盖;未做说话人分离,片段边界不是逐字时间戳。小分片配置产生超过 1000 段时在首次网络请求前拒绝。
- `QWEN_EXTRACTION_RESPONSE_FORMAT=json_schema`、`QWEN_EXTRACTION_MAX_TOKENS=8192`;当前本地验收显式 `QWEN_EXTRACTION_ENABLE_THINKING=false`。这只是已测配置,不是质量通过凭证,不提供协议/模型自动回退。
- 服务端证据窗口由真实转写生成,模型只返回引用 ID。宽窗口不能证明每个事实;程序保留模型日期弃权,不把别句日期补给该事件,矛盾日期留空并强制审阅。
- 阶段检查点存入加密的 `pipeline_cipher`;先持久化 intent,再发请求。已完成 ASR 可复用;超时/未知结果锁定核验;已完成但不合格的提炼保留,不重新无限调用。
- 已部署旧表时补执行 `server/sql/2026_10_08_followup_audio_pipeline.sql`,**仍须正式发布授权和备份**。首次安装用更新后的主迁移,两个迁移均幂等。90 天清理覆盖新检查点全文,必要采纳证据仍按审核规则保留。
- HTTPS 为默认;仅经管理员明确建立的 SSH 隧道可启用 `QWEN_ALLOW_LOOPBACK_TUNNEL=true`,只接受字面 `127.0.0.1`/`[::1]`。不允许外网 HTTP、localhost 别名或跨地址重定向。不要把本地临时隧道地址直接当生产配置。
- 这次连接的是本单位 ASR 与 Qwen 服务。Dify 侧尚未配置/验收 speech2text 应用,不宣称已通过 Dify 音频链路。
下一质量门槛:取得人工回听/标注金标准,先解决主体、问答肯否、模糊数量和未提及字段问题,再测短/中/一小时及混合口音;门槛通过前不得打开真实客服入口。部署回退脚本恢复源码,不撤销任何已写业务记录。
## 2026-10-09 受控预览配置
本轮用户限定:仅测试患者“张三(系统占号)医生无需面诊”的现有诊单1;不新建诊单、不采纳任何录音资料。新增PREVIEW_ONLY、TEST_DIAGNOSIS_IDS/TEST_ADMIN_IDS及独立preview_verified_fingerprint;完整AUDIO_VERIFIED保持false。预览来源永久标记,即使将来切普通模式也禁止Apply。上传/转写/提炼/角色及草稿属于本功能资料,诊单、日常记录、跟踪备注及采纳审计均不得写入。
Dify独立App和ASR sidecar使用既有HTTPS域名;新增speech2text默认,不改旧App和其他类型默认。两阶段通过显式dify/dify_chat协议接入;配置、严格TLS兼容方式和受控部署约束见 `deployment/followup-audio-runtime/README.md` 及 `deployment/followup-audio-dify/README.md`。实际上线状态以本轮release验收账本为准,代码合并不等于部署成功。
## 使用与数据规则
- 入口:网页问诊列表→编辑患者→回访录音。PC/H5共用现有编辑组件;桌面客户端不增加入口。
- 每次一个文件,MP3/M4A/WAV/AMR,最多500MiB/3600秒,按服务端实际元数据检查,2MiB分片。
- 原件只在 `server/runtime/private/followup_audio/`;播放需登录令牌请求头及患者权限。没有公开录音URL,没有伪造医生通话记录。
- AMR或超出上游预算的录音生成私有临时32kbps/16kHz单声道MP3,校验完整时长,不截断、不自动分段改语义;默认上游预算20MiB。原件保留不改,处理副本在成功或失败后清理。
- 通话时间采用北京时间,模型解释今天/昨天等;模糊范围需客服确认,不能自动随便取一天。时段缺钟点时早上08:00、中午12:00、下午15:00、晚上20:00、睡前22:00,明确标记估算并要求审阅。
- 同值不同测量保留不同记录;重复提及同一事件才合并。默认钟点相同不自动去重。相同诊单+音频SHA256+模型复用原任务,换文件名、上传ID或通话时间不绕过未知请求防重发;日期错误在审阅中修正,已采纳任务不重新写入。
- 字段、字典、身份锁、phonePlain和dailyRecord权限均在服务端校验。未提及不等于正常/无,不自动生成诊断或处方。病历当前值与历史记录分开选择。
- 草稿有版本和不可变来源证据。冲突刷新最新快照并取消选择,保留用户编辑供重新确认;不静默覆盖。原病历表单有未保存修改时不允许被录音结果覆盖。
- 确认写入使用一个事务(单次READ COMMITTED,不更改连接默认),锁定任务与真实记录,审计同事务,重复确认幂等。存在不明确的值可不采纳,不要求全部接受。
## 配置与运行前检查
1. 核对实际数据库字段/表前缀,先在线备份;经发布授权后应用 `server/sql/2026_09_29_followup_audio.sql`。SQL使用现有 `zyt_` 前缀,可重复执行;新增四表及血糖时间来源字段,不改旧数据。不得把测试库模拟schema当作生产已核验。
2. 使用 `server/.env.followup-audio.example` 配置明确的驱动、模型和凭据。`dify` 可复用现有 `[prescription_ai]` base URL/profile凭据;`openai_audio` 必须显式配置自己的地址、密钥和模型。不会自动切换协议/供应商或回退为纯文本。不要把生产数据库凭据复制到本地测试环境,不要把API密钥放前端或提交Git。
3. PHP8.2已做本地验证;需要curl/fileinfo/openssl、可执行FFmpeg/FFprobe。Web/worker用户都必须可读写同一个私有录音目录,目录不能放在public或公开存储域名下。部署多节点需共享私有存储和稳定加密密钥(至少32字符,离线备份),不要依赖各节点自动生成不同runtime key。
4. 反向代理/PHP单请求上限至少容纳2MiB分片及表单开销;不要将500MiB整个请求交给PHP上传。短期处理副本也要计入磁盘容量。
5. Dify存储副本/缓存的保留与删除策略另行核验;本系统90天删除不代表Dify侧已删除。现实现没有通用Dify远端删除凭证或删除API,不能作此承诺。
## 合成音频能力门禁
本地生成器仅接收输出目录,不接受患者录音;使用macOS `say`(默认Tingting)和FFmpeg/FFprobe。Linux消费者不需要say;可安全转移已生成合成夹具及清单。不要重新生成已有manifest或重发状态未确认的探针。
现成合成夹具:`/private/tmp/zyt-followup-audio-synthetic-gate/manifest.json`(60/900/3598秒,独立首尾口令和事实;预期答案只在本地manifest,不能放进提示词)。需要重建时使用新的输出目录:
```sh
cd /Users/long/.codex/worktrees/followup-audio/zyt
python3 scripts/generate_followup_audio_fixtures.py --output /private/tmp/followup-audio-new-synthetic-gate
cd server
php think followup-audio:probe --synthetic --manifest /private/tmp/zyt-followup-audio-synthetic-gate/manifest.json --profile qwen --case all
# 仅当另一个profile也准备供客服使用时,再单独验证openai。
```
必须核实真实音频被读取、首尾事实和数值/否定/时间关系、未截断长录音,再用获准的代表性脱敏口音样例人工回听评估。上传成功、HTTP200或纯文本回复都不是通过。探针有状态文件:已通过的case复用;结果未知先核对原Dify任务/账单,禁止自动重发。不要删除未知状态来强制重试。
只有验证通过的profile可加入 `VERIFIED_PROFILES`,且必须将本次报告的 `application_fingerprint` 写入对应 `QWEN_VERIFIED_FINGERPRINT` / `OPENAI_VERIFIED_FINGERPRINT`;人工核验通过后才设置 `AUDIO_VERIFIED=true`,经授权发布后再设 `ENABLED=true`。默认 `timestamp_verified=false`,不把LLM编出的毫秒位置当成ASR对齐。
## 独立消费者、清理与故障处理
```sh
# cwd为部署目录的server;用Supervisor/systemd管理,不在网页请求内跑模型。
php think followup-audio:work
php think followup-audio:work --once
php think followup-audio:cleanup
```
- 初始全局并发1,可通过CONCURRENCY配置1–8;独立数据库租约/互斥,不占用原处方队列。
- 600秒租约高于240秒请求预算,处理过程中续租。权限撤销、患者重绑、旧worker令牌均不得继续上传/回写。
- `needs_reconciliation` 表示请求可能已经被接收,不能自动/手动再次调用;请核对已保存上游IDs、任务和账单。现版本不提供绕过此状态的“强制重试”按钮。
- 经确认且允许重试的本地失败保留已有成果。模型不支持音频、结构校验失败或能力未验证,不得成功落诊单。
- 将cleanup纳入目标环境已批准的定时任务(本轮未安装定时任务)。90天起点为上传创建时间;清除原件、完整转写及可还原全文的分析副本,保留正式记录和必要采纳审计;活动租约不被清理,清理部分失败退出非零,便于监控。
- 关注队列等待时间、needs_reconciliation、失败码、租约恢复、磁盘和清理errors;日志不得包含录音内容、完整病历或凭据。
## 本地检查与回退
已有验证:真正隔离MySQL并发claim/create/apply、权限撤回/转派、单事务故障回滚;真实HTTP multipart和媒体处理;实际Vue组件测试;浏览器合成数据完成任务详情→草稿→确认采纳→刷新。完整网页构建通过,未执行发布脚本。全量vue-tsc在同一生成声明环境下基线和修改后均60条诊断,本功能文件0条,新诊断签名0。
```sh
cd /Users/long/.codex/worktrees/followup-audio/zyt
FOLLOWUP_AUDIO_TEST_ALLOW_DISPOSABLE=1 FOLLOWUP_AUDIO_TEST_MYSQL_PORT=23316 FOLLOWUP_AUDIO_TEST_MYSQL_PASSWORD="$TEST_MYSQL_PASSWORD" php server/tests/FollowupAudioCoreTest.php
node --test admin/tests/followup-audio.test.cjs
node admin/scripts/verify-daily-records.cjs
```
数据库命令只允许一次性本地测试容器,禁止换为线上端口。测试容器密码通过专用环境变量注入,不读取业务 .env。
发布回退先关闭入口并停止本功能消费者,保留旧静态资源和数据库备份。新增表/列应保留以保护审计;源码回退脚本只恢复源码,**不撤销已写入病历**。正式记录若需恢复,必须按审核轨迹和当前版本另做受控补偿,不能整库回滚覆盖其他人的新数据。
主交付四角色及源码回退验证位于 `/Users/long/Work/zyt/artifacts/followup-audio-20260929/`;补充研究、局部检查与未通过的真实模型门禁保留在工作副本 `artifacts/followup-audio-implementation/`。
## 2026-09-29 页面重整与提炼补测
- 页面改为“紧凑录音列表 → 摘要和分类结果表 → 单项核对弹窗”。上传和原文默认收起,已写入记录用只读文本;窄屏固定核对操作列,日期/估算标记仍可见。
- 在真实诊单抽屉组件、1440×1000视口、相同4项合成数据下,常驻输入控件从25个减至4个复选框,内容滚动高度从2802px减至852px;上传、取消单项编辑、分类不丢选择、草稿与确认写入均做了浏览器合成接口验证。它不是生产/真实模型识别证据。
- 独立补测发现并修复:临床语义候选不再因空字段而默认采纳;对家属/提问/否定/纠正等上下文强制人工复核。该规则是保守防守,不证明语言语义识别准确。
- 饮食早餐/午餐/晚餐提炼别名映射到实际`*_foods`字段,审阅读回、审计、现有日常表单编辑和提交保持一致,未选餐食及图片不清空;CSV合法值`0`不再被`empty()`抹去;医院诊断选项使用现有页面的三个静态枚举。
- 补测通过30条规则、16条防守和5条跨层检查,以及真实隔离MySQL113项检查。9个模型语义案例仍标注NOT_VERIFIED;真实Dify最新探针仍CONFIG_MISSING。不得把这些本地测试描述为真实ASR、方言或一小时录音识别已通过。
- 本次完整补测账本见工作副本`artifacts/followup-audio-implementation/extraction-acceptance-20260929.md`和`.json`,保留修复前结果、修复后结果及独立回滚证据。主四角色路径保持不变,本次记录追加到原验证记录。
## 2026-10-07:真实样本、本地验收与可配置模型
### 本轮实际结果与边界
- 用户提供的4段MP3均可读取,长度分别约10分52秒、12分25秒、6分54秒、11分39秒。真实 Upload 服务完成分片、重复分片幂等、私有重组、全量 FFmpeg 解码;原始 SHA256 全部不变。验收用本地一次性 SQLite 和合成授权,不代表生产 HTTP/RBAC 验收。
- 新的 opt-in `server/tests/FollowupAudioSampleAcceptanceTest.php` 读取 Git 外0600私有manifest;无参数安全跳过。4段录音与44个独立合成日期候选合计287项检查通过。模拟通话日期为2026-10-07、2026-03-01、2026-01-01、2024-03-01,覆盖普通日、跨月、跨年、闰年和模糊日期;这些候选不是从患者录音识别出来的内容。
- 用户指定的兼容接口 `/models` 可访问。合成短音频按 `input_audio` 发给 `gpt-6.1-sol` 得到 HTTP200,但明确回复未收到可读取音频;`/audio/transcriptions` 请求返回404。新实现的原生能力探针再次以结构化输出契约执行,退出2、`AUDIO_NOT_PROCESSED`。未继续发送15分钟/一小时样本,没有发送4段真实患者录音,没有写入任何正式诊单。
- HTTPS 实测证书与域名不匹配。没有关闭证书校验。HTTP只用于明确获准的合成检查,正式患者处理强制HTTPS,不能靠开启布尔配置绕过。
- 上述结果说明目前所测入口/模型不能完成本功能的音频识别,不等于该服务所有未测模型均不支持。纯文本提炼不能替代语音转写。
- 音频请求格式参考[OpenAI官方音频输入说明](https://developers.openai.com/api/docs/guides/audio-chat-completions),实际服务能力以本轮请求证据为准。
### 模型配置(服务端环境变量,不在客服页面暴露凭据)
当前沿用 `qwen` / `openai` 两个稳定逻辑槽位;槽位不再决定固定品牌/模型,前端显示服务端配置的标签。示例:
```ini
[followup_audio]
ENABLED = false
AUDIO_VERIFIED = false
VERIFIED_PROFILES =
PROFILE = openai
OPENAI_DRIVER = openai_audio
OPENAI_BASE_URL = https://HOST/v1
OPENAI_API_KEY =
OPENAI_MODEL = MODEL
OPENAI_LABEL = 回访分析模型
OPENAI_VERIFIED_FINGERPRINT =
ALLOW_INSECURE_SYNTHETIC = false
```
- API_KEY只通过部署环境或Git忽略的本地`.env`注入;本轮本地`.env`权限0600,未打包/提交。正式配置不要使用文档占位值。
- `DRIVER=dify`选择Dify应用,内部使用哪个模型需在Dify端配置;本地MODEL字段不能改变Dify应用模型。`DRIVER=openai_audio`会将MODEL实际发送到Chat Completions,必须是该服务真正支持音频输入的模型。
- 地址、密钥、driver、model任一变化都会使验证指纹失效;修改配置后重启消费者并重新验证。标签变化不改变提供方身份。不要保留旧指纹作为新模型的验收凭证。
- 新任务将选择时的提供方指纹保存到现有`upstream_ids_json`,不增加数据库schema。消费者、心跳、checkpoint和完成均校验;旧任务缺少指纹或配置漂移不会静默改走新服务。已有结果不自动重分析,相同内容防重规则保持。
- 探针状态保存为 `probe-<profile>-<fingerprint>.json`,旧身份报告保留。未知/已开始的同身份请求不自动重发;失败先核对已有请求ID及响应。不能删除报告来强制重试。
- 需要先修复HTTPS并提供支持音频的模型/转写能力,然后完成短/中/长门禁,再对代表性真实录音人工回听、核对主体/否定/数值及时间。此步骤尚未完成,入口继续关闭。
### 本轮验证记录
ProviderConfig24、OpenAI音频传输47、Dify106、Media41、Probe14、隔离MySQL Core132、Worker20、Endpoint21、Access11、ProviderIntegration20均通过。音频传输单测采用受控响应/回环服务,不是外部ASR准确率;4个真实样本的287项检查只证明本地媒体与独立日期规则。网页未修改,38项录音组件测试回归通过。
完整证据在 `/Users/long/Work/zyt/artifacts/followup-audio-20260929/samples-20261007/`,主四角色路径沿用原交付;本地配置、真实音频和私有manifest都不纳入源码包。
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Create synthetic-only speech fixtures. Never accepts a recording or sends data to a provider.
The random canaries and expected facts live in the local manifest only; the Dify
probe sends the audio, schema and recording time but never this ground truth.
Requires macOS say plus ffmpeg/ffprobe. Refuses to replace an existing manifest.
"""
import argparse
import hashlib
import json
import pathlib
import secrets
import subprocess
import tempfile
def run(command):
return subprocess.run(command, check=True, capture_output=True, text=True).stdout
def duration(path):
return float(run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(path)]))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output", type=pathlib.Path, required=True)
parser.add_argument("--voice", default="Tingting")
args = parser.parse_args()
output = args.output.resolve()
if (output / "manifest.json").exists() or any((output / (case + ".mp3")).exists() for case in ("short", "medium", "long")):
raise SystemExit("Fixture identity already exists; reuse it instead of regenerating or resubmitting.")
output.mkdir(parents=True, exist_ok=True)
output.chmod(0o700)
manifest = {"generator": "followup-audio-synthetic-v1", "synthetic": True,
"recorded_at": "2026-09-29 10:00:00", "speech_revision": "ordinary-dialogue-v2", "fixtures": []}
words = ["紫色海豚", "水晶风车", "绿色蜻蜓", "银色树叶", "蓝色鲸鱼", "金色河流", "红色石榴", "白色云朵"]
with tempfile.TemporaryDirectory(prefix="followup-audio-synthetic-") as temporary:
temp = pathlib.Path(temporary)
# Synthetic provenance stays in the manifest. The speech must not contradict
# the expected task by declaring all reported measurements non-facts.
middle_text = "客服说,电话里的声音还清楚吗?患者说,很清楚。客服说,好的,我们继续聊。患者说,好的,您说吧。"
run(["say", "-v", args.voice, "-r", "190", "-o", str(temp / "middle.aiff"), middle_text])
for case, seconds, systolic, diastolic in (("short", 60, 131, 86), ("medium", 900, 139, 88), ("long", 3598, 147, 91)):
head_canary = "".join(secrets.SystemRandom().sample(words, 3))
tail_canary = "".join(secrets.SystemRandom().sample(words, 3))
while tail_canary == head_canary:
tail_canary = "".join(secrets.SystemRandom().sample(words, 3))
head = f"患者说,我先读三个词,{head_canary}。昨天晚上九点,我测的血压是收缩压一百二十六,舒张压八十二。前天下午两点,我测的餐后血糖是七点二。"
tail = f"患者说,我再补充一次测量。今天早晨七点,我的收缩压是{systolic},舒张压是{diastolic}。最后再读三个词,{tail_canary}。客服说,好的,再见。"
run(["say", "-v", args.voice, "-r", "190", "-o", str(temp / "head.aiff"), head])
run(["say", "-v", args.voice, "-r", "190", "-o", str(temp / "tail.aiff"), tail])
filler_seconds = seconds - duration(temp / "head.aiff") - duration(temp / "tail.aiff")
if filler_seconds <= 0:
raise SystemExit("Speech is longer than short fixture; increase speaking rate or duration")
path = output / (case + ".mp3")
filters = f"[0:a]aresample=16000,aformat=channel_layouts=mono[h];[1:a]aresample=16000,aformat=channel_layouts=mono,atrim=duration={filler_seconds},asetpts=PTS-STARTPTS[m];[2:a]aresample=16000,aformat=channel_layouts=mono[t];[h][m][t]concat=n=3:v=0:a=1[out]"
run(["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-i", str(temp / "head.aiff"),
"-stream_loop", "-1", "-i", str(temp / "middle.aiff"), "-i", str(temp / "tail.aiff"),
"-filter_complex", filters, "-map", "[out]", "-t", str(seconds), "-codec:a", "libmp3lame", "-b:a", "32k", "-y", str(path)])
path.chmod(0o600)
actual = duration(path)
sha = hashlib.file_digest(path.open("rb"), "sha256").hexdigest()
manifest["fixtures"].append({"case": case, "file": path.name, "sha256": sha, "duration_seconds": actual,
"synthetic": True, "generator": manifest["generator"], "expected": {"canaries": [head_canary, tail_canary], "facts": [
{"kind": "blood", "record_date": "2026-09-28", "record_time": "21:00", "values": {"systolic_pressure": 126, "diastolic_pressure": 82}},
{"kind": "blood", "record_date": "2026-09-27", "record_time": "14:00", "values": {"postprandial_blood_sugar": 7.2}},
{"kind": "blood", "record_date": "2026-09-29", "record_time": "07:00", "values": {"systolic_pressure": systolic, "diastolic_pressure": diastolic}},
]}})
print(json.dumps({"case": case, "path": str(path), "duration_seconds": actual, "sha256": sha, "synthetic": True}))
manifest_path = output / "manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
manifest_path.chmod(0o600)
reopened = json.loads(manifest_path.read_text())
assert len(reopened["fixtures"]) == 3
print(json.dumps({"manifest": str(manifest_path), "synthetic": True, "fixtures": 3}))
if __name__ == "__main__":
main()
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
cd "$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)"
php server/tests/IamV2SourceTest.php
php server/tests/IamV2TargetTest.php
php server/tests/IamV2RouteContractTest.php
NODE_PATH=admin/node_modules node server/tests/IamV2UiTest.mjs
php server/tests/IamLoginTransactionTest.php
php server/tests/IamProvisioningTest.php
php server/tests/IamOidcClientTest.php
NODE_PATH=admin/node_modules node server/tests/IamLoginUiContractTest.mjs
php server/tests/AdminDesktopAuthContractTest.php
php server/tests/AdminDesktopSessionBehaviorTest.php
php server/tests/AdminMultiRoleRegressionTest.php
php server/tests/DataScopeMultiRoleTest.php
+106
View File
@@ -0,0 +1,106 @@
# Merge this section into the target environment's existing .env. No credentials are provided here.
# Only dify may reuse existing [prescription_ai] base/key. openai_audio needs MODEL; asr_then_llm needs both stage model/key/base triples.
[followup_audio]
ENABLED = false
PREVIEW_ONLY = false
# Explicit human-reviewed business use, with an exact connection-ready provider fingerprint.
# This never marks AUDIO_VERIFIED true or removes original preview-task markers.
MANUAL_REVIEW_ENABLED = false
# IDs only. Empty or invalid diagnosis allowlist denies preview; admin list never replaces RBAC.
TEST_DIAGNOSIS_IDS =
TEST_ADMIN_IDS =
AUDIO_VERIFIED = false
VERIFIED_PROFILES =
PROFILE = qwen
CONCURRENCY = 1
REQUEST_TIMEOUT = 240
UPSTREAM_MAX_BYTES = 20971520
NORMALIZE_TIMEOUT = 120
FFMPEG = ffmpeg
FFPROBE = ffprobe
# At least 32 characters; keep secret, stable, backed up and identical on web/worker nodes.
# Empty uses the existing prescription_analysis key; never rotate without a data re-encryption plan.
ENCRYPTION_KEY =
# Never enable HTTP for real audio. This switch applies only to the synthetic CLI probe.
ALLOW_INSECURE_SYNTHETIC = false
# Supported drivers: dify, openai_audio, asr_then_llm. openai_audio MODEL is sent in the request.
# Dify selects an application with its key; MODEL does not change the model inside that app.
QWEN_DRIVER = dify
QWEN_BASE_URL =
QWEN_API_KEY =
QWEN_MODEL =
QWEN_LABEL = qwen
QWEN_VERIFIED_FINGERPRINT =
OPENAI_DRIVER = dify
OPENAI_BASE_URL =
OPENAI_API_KEY =
OPENAI_MODEL =
OPENAI_LABEL = openai
OPENAI_VERIFIED_FINGERPRINT =
# Fingerprints must come from all three passing synthetic gates for this exact driver/URL/model/key.
# Any identity change invalidates prior verification; unknown prior requests still require reconciliation.
# Two-stage is opt-in per slot. ASR transcript is canonical; extraction uses text only.
# Mono keeps120s; stereo always isolates both channels on shared fixed windows.
ASR_STEREO_CHUNK_SECONDS = 15
ASR_CHUNK_SECONDS = 120
ASR_REQUEST_TIMEOUT = 240
EXTRACTION_REQUEST_TIMEOUT = 240
# HTTPS required. Enable this only for an operator-established SSH tunnel on literal 127.0.0.1 or [::1].
# This loopback switch never permits other hosts; redirects remain disabled.
QWEN_ALLOW_LOOPBACK_TUNNEL = false
QWEN_ASR_BASE_URL =
QWEN_ASR_API_KEY =
QWEN_ASR_MODEL =
QWEN_EXTRACTION_BASE_URL =
QWEN_EXTRACTION_API_KEY =
QWEN_EXTRACTION_MODEL =
OPENAI_ALLOW_LOOPBACK_TUNNEL = false
OPENAI_ASR_BASE_URL =
OPENAI_ASR_API_KEY =
OPENAI_ASR_MODEL =
OPENAI_EXTRACTION_BASE_URL =
OPENAI_EXTRACTION_API_KEY =
OPENAI_EXTRACTION_MODEL =
# V2 structured extraction; explicit json_schema/json_object/prompt_json, never automatic fallback.
QWEN_EXTRACTION_RESPONSE_FORMAT = json_schema
QWEN_EXTRACTION_MAX_TOKENS = 8192
OPENAI_EXTRACTION_RESPONSE_FORMAT = json_schema
OPENAI_EXTRACTION_MAX_TOKENS = 8192
# Optional vendor extension; leave absent for portable providers. true/false are explicit Qwen choices.
# The local Qwen run exhausted 8192 tokens with thinking=true; false produced JSON, not a quality pass.
# QWEN_EXTRACTION_ENABLE_THINKING = false
# OPENAI_EXTRACTION_ENABLE_THINKING = false
# Synthetic connection readiness only; never sets AUDIO_VERIFIED or allows clinical adoption.
QWEN_PREVIEW_VERIFIED_FINGERPRINT =
OPENAI_PREVIEW_VERIFIED_FINGERPRINT =
# Explicit per-stage protocol. No automatic fallback. Dify uses dedicated App keys only.
QWEN_ASR_PROTOCOL = openai
QWEN_ASR_BINDING_REVISION =
QWEN_EXTRACTION_PROTOCOL = openai
QWEN_EXTRACTION_BINDING_REVISION =
OPENAI_ASR_PROTOCOL = openai
OPENAI_ASR_BINDING_REVISION =
OPENAI_EXTRACTION_PROTOCOL = openai
OPENAI_EXTRACTION_BINDING_REVISION =
# For Dify: ASR_PROTOCOL=dify, EXTRACTION_PROTOCOL=dify_chat, RESPONSE_FORMAT=prompt_json.
# Every Dify stage needs a nonempty BINDING_REVISION. MODEL is expected identity, not sent.
# Dify App owns generation parameters: local max_tokens/response_format/thinking are NOT forwarded.
# Leave EXTRACTION_ENABLE_THINKING absent for Dify; set generation limits in the dedicated App.
# Changing that App requires a new binding revision and fresh preview fingerprint acceptance.
# asr_then_llm only: curl (default) or openssl_stream (explicit verified-TLS child process).
# No automatic transport fallback; changing this requires new fingerprint readiness.
HTTP_TRANSPORT = curl
# Explicit operator authorization for a fixed plaintext text-extraction channel only.
# Copy the exact normalized http://HOST[/path]/v1 base here; no wildcards, encoded/dot paths or redirects.
# Only asr_then_llm + extraction protocol=openai accepts it. ASR and all HTTPS verification stay unchanged.
# HTTP carries transcript and API key without TLS. Leave empty unless that channel was expressly authorized.
# Changes bind a new provider fingerprint; preserve old profiles/tasks rather than replacing their identity.
QWEN_EXTRACTION_HTTP_BASE_OPT_IN =
OPENAI_EXTRACTION_HTTP_BASE_OPT_IN =
+25
View File
@@ -0,0 +1,25 @@
; 企业微信客服(桌面软件 / 手机远程控制台)对接配置
; 把下面的 [WECOM_RPA] 段追加到 server/.env 末尾使用(勿提交真实 .env)。
; php-fpm 每个请求都会重新读取 .env,保存即生效;常驻进程(如 php think run)需重启。
;
; 背景:员工在自己电脑上用客服桌面软件登录 ZYT(终端 7),令牌交给客服后台,
; 由客服后台服务器代查患者、订单。后台令牌默认绑定登录 IP,服务器出口 IP 与员工
; 电脑不同,会被判为「ip地址发生变化,请重新登录」,桌面端表现为「ZYT 患者查询
; 登录已过期」,重新验证后下一次查询仍然失败。
;
; SERVER_IPS:客服后台服务器的公网出口 IP,多个用英文逗号或空格分隔,逐个精确匹配
; (IPv4/IPv6 字面量,不支持网段)。以 ZYT 看到的来源 IP(REMOTE_ADDR)为准,
; 可在 ZYT 访问日志里核对客服后台请求的来源地址;出口 IP 变更后须同步修改。
; 只有终端 7(桌面)/ 9(手机控制台)的令牌、且请求来自这些 IP 时才跳过登录 IP
; 绑定;网页后台、APP 等其他终端令牌不受影响,菜单权限照常校验。
; 留空或不配置 = 保持原有 IP 绑定行为。
;
; 生产环境客服后台出口 IP(2026-09 核对):123.14.175.249
; 即生产 .env 中填写:SERVER_IPS = 123.14.175.249
;
; 注意:本文件和 .env 都按 INI 解析,注释请用分号开头;以 # 开头且带等号的行
; 会被当成配置键读入。也可以不写分区,在所有 [分区] 之前写顶层键
; WECOM_RPA_SERVER_IPS,效果相同。
[WECOM_RPA]
SERVER_IPS =
@@ -28,7 +28,10 @@ class DesktopController extends BaseAdminController
if (empty($identity) || empty($identity['admin_id'])) {
return $this->fail('登录已失效,请重新登录');
}
if ((int)($identity['terminal'] ?? 0) !== AdminTerminalEnum::WECOM_RPA) {
// 桌面软件(7)和客服后台代登的手机控制台(9)都用这个接口换身份;
// 返回真实终端,客服后台据此区分两种会话,桌面令牌不能冒充手机令牌。
$terminal = (int)($identity['terminal'] ?? 0);
if (!in_array($terminal, AdminTerminalEnum::wecomRpaTerminals(), true)) {
return $this->fail('当前登录令牌不属于企业微信客服桌面端');
}
@@ -59,7 +62,7 @@ class DesktopController extends BaseAdminController
'nickname' => $name !== '' ? $name : $account,
'mobile' => '',
'avatar' => (string)$admin['avatar'],
'terminal' => AdminTerminalEnum::WECOM_RPA,
'terminal' => $terminal,
'expire_time' => (int)($identity['expire_time'] ?? 0),
'status' => 'active',
'account_type' => 'admin',
@@ -0,0 +1,245 @@
<?php
declare(strict_types=1);
namespace app\adminapi\controller;
use RuntimeException;
use think\facade\Config;
use think\facade\Db;
use app\adminapi\service\iam\IamOidcClient;
use app\adminapi\service\iam\v2\{IamV2Client, IamV2Source, IamV2Manager, IamV2Flow, IamV2Target};
/** Every endpoint authorizes itself. Never relies on legacy unregistered-route allow rules. */
final class IamV2Controller extends BaseAdminController
{
public array $notNeedLogin = ['status', 'introspect', 'checkSession', 'revocation', 'launchContinue', 'selfCallback', 'passwordContinue', 'targetConfig', 'targetPrepare', 'targetCallback', 'targetExchange', 'targetReset'];
private function invokeV2(callable $fn)
{
try {
if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); }
$action = strtolower((string) $this->request->action());
if (in_array($action, ['operation','preflight','batch','retry','selfstart','passwordsetup'], true) && !IamV2Client::feature('management')) { throw new RuntimeException('FEATURE_DISABLED'); }
if (in_array($action, ['launchstart','targetprepare','targetexchange'], true) && !IamV2Client::feature('launch')) { throw new RuntimeException('FEATURE_DISABLED'); }
$reads = ['status','accounts','identities','operationresult','audit','job','targetconfig'];
$read = in_array(strtolower((string) $this->request->action()), $reads, true);
if (($read && !$this->request->isGet()) || (!$read && !$this->request->isPost())) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
return $this->data($fn())->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
} catch (\Throwable $e) {
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
return $this->fail($code, ['error' => ['code' => $code]], 0, 0)->header(['Cache-Control' => 'no-store']);
}
}
private function session(bool $recent = false): array
{
if (!$this->request->isGet()) {
$expected = IamV2Client::origin((string) Config::get('iam.public_url'));
if ((string) $this->request->header('origin') !== $expected) { throw new RuntimeException('INVALID_ORIGIN'); }
}
return IamV2Source::current((string) $this->request->header('token', ''), $recent);
}
private function input(): array { return (array) $this->request->post(); }
private function requestId(): string
{
$key = (string) $this->request->header('idempotency-key', '');
if (!preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $key)) { throw new RuntimeException('INVALID_IDEMPOTENCY_KEY'); }
return 'zyt-' . $key;
}
private function serviceAuth(): void
{
$expected = (string) Config::get('iam.v2_introspection_token', '');
if (!$this->request->isPost() || strlen($expected) < 32 || !hash_equals('Bearer ' . $expected, (string) $this->request->header('authorization', ''))) { throw new RuntimeException('FORBIDDEN'); }
}
public function status()
{
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
return $this->invokeV2(function () {
$token = (string) $this->request->header('token', '');
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
IamV2Source::admin((int) $legacy['admin_id']);
$fresh = false; try { $s = IamV2Source::current($token); $fresh = $s['auth_time'] >= time() - 300; } catch (\Throwable $e) { $s = null; }
$b = (new IamV2Manager())->binding((int) $legacy['admin_id']);
return ['enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'session_ready' => $s !== null, 'reauth_required' => !$fresh,
'management_capabilities' => IamV2Source::capabilities((int) $legacy['admin_id']),
'protected_review_operator' => IamV2Source::reviewOperator((int) $legacy['admin_id']),
'protected_account' => IamV2Source::protectedAccount((int) $legacy['admin_id'])] + $b;
});
}
public function reauth()
{
return $this->invokeV2(function () {
if ((string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
$s = IamV2Source::reauth((string) $this->request->header('token', ''), (string) $this->request->post('password', ''));
return ['expires_at' => $s['auth_time'] + 300];
});
}
public function accounts() { return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false); return (new IamV2Manager())->accounts((array) $this->request->get(), (int) $s['admin_id']); }); }
public function identities()
{
return $this->invokeV2(function () {
$s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
$q = http_build_query(['q' => mb_substr((string) $this->request->get('q', ''), 0, 64), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20], '', '&', PHP_QUERY_RFC3986);
return (new IamV2Client())->call('GET', '/identities?' . $q);
});
}
public function operation() { return $this->invokeV2(fn() => (new IamV2Manager())->operation($this->session(true), $this->input(), $this->requestId())); }
public function operationResult() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'operation', (string) $this->request->param('id'))); }
public function audit()
{
return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
IamV2Source::scope((int) $s['admin_id'], [(int) $this->request->param('id')]);
return (new IamV2Client())->call('GET', '/audit?' . http_build_query(['externalAccountId' => (string) (int) $this->request->param('id'), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20])); });
}
public function preflight() { return $this->invokeV2(fn() => (new IamV2Manager())->preflight($this->session(true), (array) $this->request->post('items', []))); }
public function batch() { return $this->invokeV2(fn() => (new IamV2Manager())->batch($this->session(true), (string) $this->request->post('preview_id'), (array) $this->request->post('indexes', []), $this->requestId())); }
public function job() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'job', (string) $this->request->param('id'))); }
public function retry() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(true), 'job', (string) $this->request->param('id'), true, (array) $this->request->post('indexes', []))); }
public function introspect()
{
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input(); return IamV2Source::introspect((string) ($b['proof'] ?? ''), (string) ($b['purpose'] ?? ''), $b['transactionId'] ?? null); });
}
private function serviceResult(callable $fn)
{
try { if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); } if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); } return json($fn())->header(['Cache-Control' => 'no-store']); }
catch (\Throwable $e) { return json(['active' => false], 403)->header(['Cache-Control' => 'no-store']); }
}
public function checkSession()
{
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input();
return IamV2Source::liveStatus((string) ($b['sessionId'] ?? ''), (int) ($b['sessionVersion'] ?? 0),
(string) ($b['purpose'] ?? ''), (array) ($b['targetLocalIds'] ?? [])); });
}
public function launchStart()
{
return $this->invokeV2(function () { $s = $this->session(); (new IamV2Manager())->assertLinked((int) $s['admin_id']);
IamV2Source::check($s['session_id'], (int) $s['version']);
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('launch', $intent, ['sessionId' => $s['session_id'], 'sessionVersion' => $s['version']]);
setcookie('ZYT_IAM_V2_INTENT', $intent, ['expires' => time() + 300, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
return ['url' => IamV2Client::origin((string) Config::get('iam.erp_url')) . '/iam/launch?source=zyt&intent=' . $intent]; });
}
public function launchContinue()
{
try {
IamV2Source::requirePurpose('launch');
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
$intent = (string) $this->request->get('intent', ''); $cookie = (string) ($_COOKIE['ZYT_IAM_V2_INTENT'] ?? '');
if ($intent === '' || !hash_equals($cookie, $intent)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
$flow = IamV2Flow::take('launch', $intent, $s['session_id']); IamV2Source::check($s['session_id'], (int) $flow['sessionVersion']);
$tx = (string) $this->request->get('transaction_id', '');
$transaction = $client->call('GET', '/launch-transactions/' . rawurlencode($tx));
if (($transaction['sourceApplicationId'] ?? '') !== 'zyt' || ($transaction['targetApplicationId'] ?? '') !== 'zmxy-erp') { throw new RuntimeException('ACCOUNT_MISMATCH'); }
(new IamV2Manager($client))->assertLinked((int) $s['admin_id']);
$grant = $client->call('POST', '/launch-grants', ['transactionId' => $tx, 'proof' => IamV2Source::proof($s, 'launch', [(int) $s['admin_id']], [], $tx)]);
$erpOrigin = IamV2Client::origin((string) Config::get('iam.erp_url'));
$delivery = IamV2Client::https((string) Config::get('iam.erp_callback_url') ?: $erpOrigin . '/api/erp/iam/v2/launch/callback');
if (!in_array($delivery, [$erpOrigin . '/api/erp/iam/v2/launch/callback', $erpOrigin . '/basic-api/api/erp/iam/v2/launch/callback'], true)) { throw new RuntimeException('INVALID_FIXED_URL'); }
if (($grant['deliveryUrl'] ?? '') !== $delivery) { throw new RuntimeException('INVALID_FIXED_URL'); }
return response(IamV2Flow::form($delivery, ['transaction_id' => $tx, 'grant' => $grant['grant']]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=launch_failed')->header(['Cache-Control' => 'no-store']); }
}
private function selfConfig(): array { $c = (array) Config::get('iam'); $c['redirect_uri'] = IamV2Client::origin($c['public_url']) . '/adminapi/iam/v2/self-link/callback'; return $c; }
public function selfStart()
{
return $this->invokeV2(function () { $s = $this->session(true); $a = IamV2Source::admin((int) $s['admin_id']);
if (IamV2Source::protectedAccount((int) $a['id'])) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
$b = (new IamV2Manager())->binding((int) $s['admin_id'], true);
if (($b['binding']['state'] ?? '') === 'verified') { throw new RuntimeException('BINDING_CONFLICT'); }
$state = bin2hex(random_bytes(32)); $nonce = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
IamV2Flow::put('self_link', $state, ['sessionId' => $s['session_id'], 'nonce' => $nonce, 'verifier' => $verifier, 'version' => $b['binding']['version'] ?? null]);
return ['url' => (new IamOidcClient($this->selfConfig()))->authorizationUrl($state, $nonce, $verifier) . '&prompt=login&max_age=300']; });
}
public function selfCallback()
{
try {
IamV2Source::requirePurpose('self_link');
$central = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
$flow = IamV2Flow::take('self_link', (string) $this->request->get('state', ''), $s['session_id']);
$oidc = new IamOidcClient($this->selfConfig()); $oidc->exchange((string) $this->request->get('code', ''), $flow['verifier'], $flow['nonce']);
$proof = IamV2Source::proof($s, 'self_link', [(int) $s['admin_id']], [], null, ['oidcNonce' => $flow['nonce']]);
$body = ['idToken' => $oidc->verifiedIdToken(), 'nonce' => $flow['nonce'], 'proof' => $proof, 'externalAccountId' => (string) $s['admin_id']];
if ($flow['version'] !== null) { $body['expectedVersion'] = (int) $flow['version']; }
$central->call('POST', '/self-link', $body);
(new IamV2Manager($central))->binding((int) $s['admin_id'], true);
return redirect('/admin/user/setting?iam_result=linked')->header(['Cache-Control' => 'no-store']);
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=link_failed')->header(['Cache-Control' => 'no-store']); }
}
public function passwordSetup()
{
return $this->invokeV2(function () { $s = $this->session(true); $b = (new IamV2Manager())->assertLinked((int) $s['admin_id']);
if (!($b['employee']['passwordSetupPending'] ?? false)) { throw new RuntimeException('PASSWORD_ALREADY_SET'); }
$result = (new IamV2Client())->call('POST', '/password-setup', ['proof' => IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']])]);
$url = parse_url((string) ($result['url'] ?? '')); $portal = parse_url(IamV2Client::origin((string) Config::get('iam.portal_url')));
if (!$url || ($url['scheme'] ?? '') !== 'https' || ($url['host'] ?? '') !== $portal['host'] || ($url['port'] ?? 443) !== ($portal['port'] ?? 443) || isset($url['user']) || isset($url['pass']) || ($url['path'] ?? '') !== '/portal/password-setup') { throw new RuntimeException('INVALID_FIXED_URL'); }
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('password_setup', $intent, ['sessionId' => $s['session_id'], 'requestId' => $result['requestId']], 900);
setcookie('ZYT_IAM_PASSWORD_INTENT', $intent, ['expires' => time() + 900, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
return $result; });
}
public function passwordContinue()
{
try {
IamV2Source::requirePurpose('password_setup');
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
$f = IamV2Flow::take('password_setup', (string) ($_COOKIE['ZYT_IAM_PASSWORD_INTENT'] ?? ''), $s['session_id']);
$id = (string) $this->request->get('request_id', ''); $state = (string) $this->request->get('state', '');
if ($id !== $f['requestId'] || !preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $state)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
$proof = IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']], [], $id, ['state' => $state]);
$url = IamV2Client::origin((string) Config::get('iam.portal_url')) . '/portal/password-setup/authorize';
return response(IamV2Flow::form($url, ['request_id' => $id, 'state' => $state, 'proof' => $proof]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=password_failed'); }
}
private function targetOrigin(): void
{
if (!$this->request->isPost() || (string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
}
public function targetConfig()
{
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
return $this->invokeV2(function () {
$source = (string) $this->request->get('source', 'iam-portal');
return ['enabled' => IamV2Client::feature('launch'), 'global_enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'restart_url' => IamV2Client::origin((string) Config::get('iam.portal_url')) . ($source === 'iam-admin' ? '/admin' : '/portal')];
});
}
public function targetPrepare()
{
return $this->invokeV2(function () { $this->targetOrigin();
$out = (new IamV2Target())->prepare((string) $this->request->post('source', ''), (string) $this->request->post('intent', ''),
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
setcookie(IamV2Target::COOKIE, $out['browser'], ['expires' => time() + 300, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
return ['url' => $out['url']];
});
}
public function targetCallback()
{
try {
if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
$out = (new IamV2Target())->callback((string) $this->request->post('transaction_id', ''), (string) $this->request->post('grant', ''),
(string) ($_COOKIE[IamV2Target::COOKIE] ?? ''), (string) $this->request->header('origin', ''));
return redirect('/admin/iam/launch?' . http_build_query($out))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
} catch (\Throwable $e) {
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
return redirect('/admin/iam/launch?iam_error=' . rawurlencode($code))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
}
}
public function targetExchange()
{
return $this->invokeV2(function () { $this->targetOrigin();
return (new IamV2Target())->exchange((string) $this->request->post('ticket', ''), (string) ($_COOKIE[IamV2Target::COOKIE] ?? ''),
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
});
}
public function targetReset()
{
return $this->invokeV2(function () { $this->targetOrigin();
IamV2Source::revokeSession((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
setcookie(IamV2Source::COOKIE, '', ['expires' => 1, 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
setcookie(IamV2Target::COOKIE, '', ['expires' => 1, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
return ['reset' => true];
});
}
public function revocation()
{
return $this->serviceResult(fn() => \app\adminapi\service\iam\v2\IamV2Events::accept(
(string) $this->request->getContent(), (string) $this->request->header('x-iam-signature', ''),
(string) $this->request->header('x-iam-event-id', ''), (string) Config::get('iam.v2_event_secret', '')));
}
}
@@ -38,7 +38,15 @@ class LoginController extends BaseAdminController
public function account()
{
$params = (new LoginValidate())->post()->goCheck();
return $this->data((new LoginLogic())->login($params));
$result = (new LoginLogic())->login($params);
// Enroll only a genuinely checked password, never the debug bypass.
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
$a = \think\facade\Db::name('admin')->where('account', $params['account'])->find();
if ($a && hash_equals((string) $a['password'], create_password((string) $params['password'], \think\facade\Config::get('project.unique_identification')))) {
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'password');
}
}
return $this->data($result);
}
/**
@@ -158,6 +166,9 @@ class LoginController extends BaseAdminController
public function logout()
{
//退出登录情况特殊,只有成功的情况,也不需要token验证
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
\app\adminapi\service\iam\v2\IamV2Source::revokeSession((string) ($_COOKIE[\app\adminapi\service\iam\v2\IamV2Source::COOKIE] ?? ''));
}
(new LoginLogic())->logout($this->adminInfo);
return $this->success();
}
@@ -4,19 +4,19 @@ declare(strict_types=1);
namespace app\adminapi\controller\qywx;
use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\qywx\CustomerLists;
use app\adminapi\logic\auth\AuthLogic;
use app\adminapi\logic\qywx\CustomerLogic;
use app\adminapi\validate\qywx\CustomerValidate;
use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\qywx\CustomerLists;
use app\adminapi\logic\auth\AuthLogic;
use app\adminapi\logic\qywx\CustomerLogic;
use app\adminapi\validate\qywx\CustomerValidate;
/**
* 企业微信客户管理控制器
*/
class CustomerController extends BaseAdminController
{
private const DELETE_PERMISSION = 'qywx.customer/delete';
class CustomerController extends BaseAdminController
{
private const DELETE_PERMISSION = 'qywx.customer/delete';
/**
* @notes 客户列表
*/
@@ -28,34 +28,34 @@ class CustomerController extends BaseAdminController
/**
* @notes 同步企业微信客户
*/
public function sync()
{
public function sync()
{
$result = CustomerLogic::triggerBackgroundSync();
if ($result === false) {
return $this->fail(CustomerLogic::getError());
}
$msg = is_array($result) && isset($result['message']) ? (string) $result['message'] : '已提交同步';
return $this->success($msg, $result);
}
/**
* @notes 删除一条本地企业微信客户同步记录
*/
public function delete()
{
// 显式鉴权,避免权限菜单迁移漏执行时被通用中间件当成“未受控 URI”放行。
if (!$this->canDeleteCustomer()) {
return $this->fail('权限不足,无法删除企业微信客户');
}
$params = (new CustomerValidate())->post()->goCheck('delete');
if (!CustomerLogic::deleteCustomer((int) $params['id'])) {
return $this->fail(CustomerLogic::getError());
}
return $this->success('删除成功');
}
return $this->success($msg, $result);
}
/**
* @notes 删除一条本地企业微信客户同步记录
*/
public function delete()
{
// 显式鉴权,避免权限菜单迁移漏执行时被通用中间件当成“未受控 URI”放行。
if (!$this->canDeleteCustomer()) {
return $this->fail('权限不足,无法删除企业微信客户');
}
$params = (new CustomerValidate())->post()->goCheck('delete');
if (!CustomerLogic::deleteCustomer((int) $params['id'])) {
return $this->fail(CustomerLogic::getError());
}
return $this->success('删除成功');
}
/**
* @notes 获取统计信息
@@ -105,22 +105,22 @@ class CustomerController extends BaseAdminController
/**
* @notes 保存同步设置
*/
public function saveSyncSettings()
public function saveSyncSettings()
{
$params = (new CustomerValidate())->post()->goCheck('syncSettings');
$result = CustomerLogic::saveSyncSettings($params);
if ($result === false) {
return $this->fail(CustomerLogic::getError());
}
return $this->success('保存成功');
}
private function canDeleteCustomer(): bool
{
if ((int) ($this->adminInfo['root'] ?? 0) === 1) {
return true;
}
return in_array(self::DELETE_PERMISSION, AuthLogic::getAuthByAdminId($this->adminId), true);
}
}
return $this->success('保存成功');
}
private function canDeleteCustomer(): bool
{
if ((int) ($this->adminInfo['root'] ?? 0) === 1) {
return true;
}
return in_array(self::DELETE_PERMISSION, AuthLogic::getAuthByAdminId($this->adminId), true);
}
}
@@ -22,6 +22,7 @@ use app\adminapi\logic\tcm\DiagnosisLogic;
use app\adminapi\logic\tcm\PatientAiReportLogic;
use app\adminapi\logic\tcm\TrackingNoteLogic;
use app\adminapi\service\AssistantSseProtocol;
use app\adminapi\service\AssistantSseTiming;
use app\adminapi\validate\tcm\DiagnosisValidate;
use app\common\model\Order;
use app\common\model\WechatChatRecord;
@@ -930,6 +931,7 @@ class DiagnosisController extends BaseAdminController
*/
public function aiAssistantStream()
{
$timing = new AssistantSseTiming();
// 登录由全局中间件完成;请求校验、旧助手权限与 DataScope 必须全部
// 在任何 SSE header / start 事件之前完成,失败时仍返回标准 JSON。
$params = (new DiagnosisValidate())->post()->goCheck('aiAssistant');
@@ -938,17 +940,18 @@ class DiagnosisController extends BaseAdminController
(string) $params['task'],
(string) ($params['prompt'] ?? ''),
$this->adminId,
$this->adminInfo
$this->adminInfo,
$timing
);
if ($prepared === null) {
return $this->fail(DiagnosisAiLogic::getError());
}
$this->runAssistantSse($prepared);
$this->runAssistantSse($prepared, $timing);
}
/** @param array<string,mixed> $prepared */
private function runAssistantSse(array $prepared): void
private function runAssistantSse(array $prepared, AssistantSseTiming $timing): void
{
while (ob_get_level() > 0) {
ob_end_clean();
@@ -984,7 +987,7 @@ class DiagnosisController extends BaseAdminController
return !connection_aborted();
};
$emit('start', [
$startEmitted = $emit('start', [
'task' => (string) ($prepared['task'] ?? ''),
'model_key' => (string) ($prepared['profile'] ?? ''),
'diagnosis_id' => (int) ($prepared['diagnosis_id'] ?? 0),
@@ -995,14 +998,37 @@ class DiagnosisController extends BaseAdminController
: [],
'message' => '已连接,正在生成…',
]);
$sseStartedAt = hrtime(true);
$firstDeltaMs = null;
$timing->log('sse_start', ['status' => $startEmitted ? 'ok' : 'disconnected']);
try {
$result = DiagnosisAiLogic::streamPreparedAssistant(
$prepared,
static fn (string $delta): bool => $emit('delta', ['text' => $delta]),
static fn (): bool => connection_aborted() === 1
static function (string $delta) use ($emit, $timing, $sseStartedAt, &$firstDeltaMs): bool {
$observedAtMs = $firstDeltaMs === null && $delta !== ''
? AssistantSseTiming::elapsedMs($sseStartedAt)
: null;
$accepted = $emit('delta', ['text' => $delta]);
if ($accepted && $observedAtMs !== null) {
$firstDeltaMs = $observedAtMs;
$timing->log('first_delta', [
'duration_ms' => $firstDeltaMs,
'delta_bytes' => strlen($delta),
]);
}
return $accepted;
},
static fn (): bool => connection_aborted() === 1,
$timing
);
if (connection_aborted()) {
$timing->log('sse_done', [
'duration_ms' => AssistantSseTiming::elapsedMs($sseStartedAt),
'first_delta_observed' => $firstDeltaMs !== null,
'first_delta_ms' => $firstDeltaMs,
'status' => 'disconnected',
]);
exit;
}
if ($result === null) {
@@ -1013,14 +1039,22 @@ class DiagnosisController extends BaseAdminController
} else {
$emit('done', $result);
}
$timing->log('sse_done', [
'duration_ms' => AssistantSseTiming::elapsedMs($sseStartedAt),
'first_delta_observed' => $firstDeltaMs !== null,
'first_delta_ms' => $firstDeltaMs,
'status' => $result === null ? 'error' : 'ok',
]);
} catch (\Throwable $e) {
\think\facade\Log::warning('diagnosis ai assistant sse failed ' . json_encode([
'diagnosis_id' => (int) ($prepared['diagnosis_id'] ?? 0),
'profile' => (string) ($prepared['profile'] ?? ''),
'task' => (string) ($prepared['task'] ?? ''),
'admin_id' => (int) ($prepared['admin_id'] ?? 0),
'exception_class' => get_class($e),
'trace_id' => $timing->id(),
], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE));
$timing->log('sse_done', [
'duration_ms' => AssistantSseTiming::elapsedMs($sseStartedAt),
'first_delta_observed' => $firstDeltaMs !== null,
'first_delta_ms' => $firstDeltaMs,
'status' => 'exception',
]);
$emit('error', [
'code' => 'AI_ASSISTANT_FAILED',
'message' => 'AI 助手暂时不可用,请稍后重试',
@@ -0,0 +1,179 @@
<?php
declare(strict_types=1);
namespace app\adminapi\controller\tcm;
use app\adminapi\controller\BaseAdminController;
use app\adminapi\logic\tcm\FollowupAudioLogic as Logic;
use app\common\service\followupaudio\FollowupAudioAccess as Access;
use app\common\service\followupaudio\FollowupAudioStream;
use app\common\service\followupaudio\FollowupAudioUpload as Upload;
use DomainException;
final class FollowupAudioController extends BaseAdminController
{
public function capabilities()
{
return $this->handle(false, ['diagnosis_id'], fn (array $p): array =>
Logic::capabilities($this->positive($p, 'diagnosis_id'), $this->adminId, $this->adminInfo));
}
public function uploadSession()
{
return $this->handle(true, ['diagnosis_id', 'file_name', 'total_bytes'], function (array $p): array {
Logic::requireEnabled(true);
return Upload::createSession($this->positive($p, 'diagnosis_id'), $this->textValue($p, 'file_name', 240),
$this->positive($p, 'total_bytes'), $this->adminId, $this->adminInfo);
});
}
public function uploadChunk()
{
return $this->handle(true, ['upload_id', 'index'], function (array $p): array {
Logic::requireEnabled(true);
$index = $p['index'] ?? null;
if (!(is_int($index) || is_string($index)) || !preg_match('/^\d{1,5}$/D', (string) $index)) {
throw new DomainException('录音分片序号无效');
}
$file = $this->request->file('file');
if (!$file instanceof \think\file\UploadedFile || !$file->isValid()) {
throw new DomainException('录音分片上传失败,请检查文件大小限制');
}
return Upload::putChunk($this->textValue($p, 'upload_id', 64), (int) $index,
$file->getPathname(), $this->adminId, $this->adminInfo);
});
}
public function uploadComplete()
{
return $this->handle(true, ['upload_id'], function (array $p): array {
Logic::requireEnabled(true);
return Upload::complete($this->textValue($p, 'upload_id', 64), $this->adminId, $this->adminInfo);
});
}
public function create()
{
return $this->handle(true, ['diagnosis_id', 'upload_id', 'recorded_at', 'model_key', 'channel_roles'], fn (array $p): array =>
Logic::create([
'diagnosis_id' => $this->positive($p, 'diagnosis_id'),
'upload_id' => $this->textValue($p, 'upload_id', 64),
'recorded_at' => $this->textValue($p, 'recorded_at', 19),
'model_key' => $this->textValue($p, 'model_key', 16),
// Preserve raw JSON type and exact enum, including null/whitespace rejection.
'channel_roles' => array_key_exists('channel_roles', $p) ? $p['channel_roles'] : 'unconfirmed',
], $this->adminId, $this->adminInfo), true);
}
public function lists()
{
return $this->handle(false, ['diagnosis_id'], fn (array $p): array =>
Logic::lists($this->positive($p, 'diagnosis_id'), $this->adminId, $this->adminInfo));
}
public function detail()
{
return $this->handle(false, ['id'], fn (array $p): array =>
Logic::detail($this->positive($p, 'id'), $this->adminId, $this->adminInfo));
}
public function saveDraft()
{
return $this->handle(true, ['id', 'version', 'items', 'channel_roles'], fn (array $p): array =>
Logic::saveDraft($this->positive($p, 'id'), $this->positive($p, 'version'),
$this->items($p), $this->adminId, $this->adminInfo,
array_key_exists('channel_roles', $p) ? $this->textValue($p, 'channel_roles', 20) : null), true);
}
public function apply()
{
return $this->handle(true, ['id', 'version', 'items'], fn (array $p): array =>
Logic::apply($this->positive($p, 'id'), $this->positive($p, 'version'),
$this->items($p), $this->adminId, $this->adminInfo), true);
}
public function delete()
{
return $this->handle(true, ['id', 'version'], fn (array $p): array =>
Logic::delete($this->positive($p, 'id'), $this->positive($p, 'version'), $this->adminId, $this->adminInfo));
}
public function reextract()
{
return $this->handle(true, ['id', 'version', 'channel_roles'], fn (array $p): array =>
Logic::reextract($this->positive($p, 'id'), $this->positive($p, 'version'),
$p['channel_roles'] ?? null, $this->adminId, $this->adminInfo), true);
}
public function retry()
{
return $this->handle(true, ['id'], fn (array $p): array =>
Logic::retry($this->positive($p, 'id'), $this->adminId, $this->adminInfo));
}
public function audio()
{
return $this->handle(false, ['id'], function (array $p): FollowupAudioStream {
$task = Access::task($this->positive($p, 'id'), $this->adminId, $this->adminInfo);
$upload = Upload::session((string) $task['upload_id']);
return new FollowupAudioStream(Upload::path($upload), (string) $upload['extension']);
});
}
private function handle(bool $post, array $allowed, callable $handler, bool $typedJson = false)
{
if ($post ? !$this->request->isPost() : !$this->request->isGet()) {
return $this->fail('请求方式错误');
}
// Review JSON carries strict booleans/integers and exact source evidence. Global trim
// would stringify scalars and alter quotations; keep all explicit validators below.
$params = $post ? $this->request->post('', null, $typedJson ? null : '') : $this->request->get();
if (array_diff(array_keys($params), $allowed) !== []) {
return $this->fail('请求包含不支持的字段');
}
try {
$this->adminInfo = Access::actor($this->adminId);
$result = $handler($params);
return $result instanceof \think\Response ? $result : $this->data($result);
} catch (DomainException $e) {
if (str_contains($e->getMessage(), 'FOLLOWUP_AUDIO_STALE_REVIEW')) {
return $this->fail('病历或日常记录已发生变化,请重新审阅差异后确认', [
'code' => 'FOLLOWUP_AUDIO_STALE_REVIEW',
]);
}
return $this->fail($e->getMessage());
} catch (\Throwable $e) {
// Never expose raw SQL, audio paths, transcripts, provider responses or keys.
return $this->fail('回访录音服务暂不可用,请联系管理员检查部署');
}
}
private function positive(array $p, string $key): int
{
$raw = $p[$key] ?? null;
if (!(is_int($raw) || is_string($raw)) || !preg_match('/^[1-9]\d{0,17}$/D', (string) $raw)) {
throw new DomainException('记录标识或版本无效');
}
return (int) $raw;
}
private function textValue(array $p, string $key, int $max): string
{
$raw = $p[$key] ?? '';
if (!is_string($raw) || strlen($raw) > $max) {
throw new DomainException('文本参数无效');
}
return trim($raw);
}
private function items(array $p): array
{
$items = $p['items'] ?? null;
if (!is_array($items) || !array_is_list($items) || count($items) > 500
|| strlen(json_encode($items, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)) > 2097152) {
throw new DomainException('审阅项目无效或数量超限');
}
return $items;
}
}
@@ -21,6 +21,7 @@ use app\common\service\pharmacy\PharmacyUploadPermissionAlias;
use app\common\service\qywx\QywxPromotionOperatorAccess;
use app\common\{
cache\AdminAuthCache,
enum\AdminTerminalEnum,
service\JsonService
};
use think\helper\Str;
@@ -47,7 +48,13 @@ class AuthMiddleware
return $next($request);
}
if ($request->adminInfo['login_ip'] != request()->ip()) {
// 登录 IP 绑定;客服后台服务器代查患者/订单的例外见 isTrustedRpaServerRequest
if ($request->adminInfo['login_ip'] != request()->ip()
&& !self::isTrustedRpaServerRequest(
(array) $request->adminInfo,
request()->ip(),
env('wecom_rpa.server_ips', '')
)) {
return JsonService::fail('ip地址发生变化,请重新登录', [], -1);
}
@@ -73,6 +80,20 @@ class AuthMiddleware
// 当前访问路径
$accessUri = strtolower($request->controller() . '/' . $request->action());
// This group must never use the legacy unregistered-route bypass.
if (str_starts_with($accessUri, 'tcm.followupaudio/')) {
$allowed = ['capabilities', 'uploadsession', 'uploadchunk', 'uploadcomplete',
'create', 'lists', 'detail', 'savedraft', 'apply', 'retry', 'audio', 'delete', 'reextract'];
$action = substr($accessUri, strlen('tcm.followupaudio/'));
$uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
if (in_array($action, $allowed, true) && in_array('tcm.diagnosis/edit', $uris, true)
&& in_array('tcm.diagnosis/followupaudio', $uris, true)
&& ($action !== 'delete' || in_array('tcm.followupaudio/delete', $uris, true))) {
return $next($request); // The service also checks the current patient scope and daily permissions.
}
return JsonService::fail('权限不足,无法访问或操作');
}
// 获客助手的子接口多数不是独立菜单权限。整组动作统一绑定页面权限,
// 共享操作人的动态页面权限也必须先经过这一层,再由业务层校验具体方案。
if (str_starts_with($accessUri, 'firstvisit.wecompromotion/')) {
@@ -122,6 +143,29 @@ class AuthMiddleware
}, $data);
}
/**
* 企业微信客服桌面软件(7)/ 手机控制台(9)的令牌会交给客服后台,由客服后台服务器
* 代查患者、订单;服务器出口 IP 与员工电脑登录时绑定的 IP 不同,按原规则每次都会被判为
* 「ip地址发生变化」。DesktopController::session 出于同一原因已免登录。
* 这里只在「RPA 终端令牌 + 请求来自 .env [WECOM_RPA] SERVER_IPS 配置的客服后台服务器 IP」
* 时跳过 IP 绑定,网页端/APP 等其他终端令牌仍保留 IP 保护;未配置时与原逻辑完全一致。
* 只跳过 IP 校验,后续菜单权限校验照常执行,客服后台拿到的仍只是该账号角色允许的数据。
*
* @param mixed $configured 逗号/空白分隔的 IP 列表,逐个精确匹配(IPv4/IPv6 字面量)
*/
public static function isTrustedRpaServerRequest(array $adminInfo, string $ip, $configured): bool
{
if (!in_array((int) ($adminInfo['terminal'] ?? 0), AdminTerminalEnum::wecomRpaTerminals(), true)) {
return false;
}
if ($ip === '' || !is_string($configured)) {
return false;
}
$trustedIps = preg_split('/[\s,]+/', trim($configured), -1, PREG_SPLIT_NO_EMPTY) ?: [];
return in_array($ip, $trustedIps, true);
}
/**
* 日常记录权限域:前端统一收口到 tcm.diagnosis/dailyRecord,
* 但待办/跟踪备注接口仍保留历史路由名,故在鉴权层做精确别名映射。
@@ -69,6 +69,22 @@ class LoginMiddleware
}
}
// Active requests compensate missed central revocations within a 30-second cache window.
// Local-only unlinked accounts and disabled installations keep their original behavior.
if ($adminInfo && !$isNotNeedLogin && \app\adminapi\service\iam\v2\IamV2Client::enabled()) {
try { \app\adminapi\service\iam\v2\IamV2Target::compensate((string) $token); }
catch (\Throwable $e) { return JsonService::fail('统一身份授权已失效或暂时不可用,请重新验证', [], 0); }
$binding = \think\facade\Db::name('iam_v2_binding')->where('admin_id', $adminInfo['admin_id'])->find();
if ($binding && $binding['state'] !== 'unlinked') {
try {
$b = (new \app\adminapi\service\iam\v2\IamV2Manager())->binding((int) $adminInfo['admin_id']);
if (($b['binding']['state'] ?? '') !== 'verified' || !($b['access']['allowed'] ?? false) || ($b['employee']['status'] ?? '') !== 'active') {
return JsonService::fail('统一账号关联已失效,请重新登录', [], -1);
}
} catch (\Throwable $e) { return JsonService::fail('统一身份服务暂时不可用,请稍后重试', [], 0); }
}
}
//给request赋值,用于控制器
$request->adminInfo = $adminInfo;
$request->adminId = $adminInfo['admin_id'] ?? 0;
+6 -2
View File
@@ -222,6 +222,10 @@ class LoginLogic extends BaseLogic
// 设置 token
$adminInfo = AdminTokenService::setToken($admin->id, $terminal, $admin->multipoint_login);
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
\app\adminapi\service\iam\v2\IamV2Source::enroll($adminInfo['token'], 'wecom');
}
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
$avatar = FileService::getFileUrl($avatar);
@@ -279,8 +283,8 @@ class LoginLogic extends BaseLogic
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
curl_close($ch);
+304 -163
View File
@@ -10,6 +10,9 @@ use app\common\logic\BaseLogic;
use app\common\model\tcm\Diagnosis;
use app\common\model\tcm\DiagnosisAiReport;
use app\common\service\DifyChatService;
use app\common\service\NihaixiaClinicalSkill;
use app\common\service\TcmAncientBooksReference;
use app\adminapi\service\AssistantSseTiming;
use think\facade\Db;
use think\facade\Log;
@@ -21,11 +24,11 @@ class DiagnosisAiLogic extends BaseLogic
/** @var string Safe machine-readable code for the current assistant request. */
private static $assistantErrorCode = 'AI_ASSISTANT_FAILED';
private const PROMPT_VERSION = 'patient-context-case-explain-v2';
private const PROMPT_VERSION = 'patient-context-case-explain-nihaixia-ancient-v4';
private const ASSISTANT_PROMPT_VERSION = 'patient-context-assistant-v2';
private const ASSISTANT_PROMPT_VERSION = 'patient-context-assistant-nihaixia-ancient-v4';
private const ANALYSIS_PROMPT_VERSION = 'patient-context-analysis-v2';
private const ANALYSIS_PROMPT_VERSION = 'patient-context-analysis-nihaixia-ancient-v5';
private const MAX_ASSISTANT_PROMPT_LENGTH = 500;
@@ -53,6 +56,8 @@ class DiagnosisAiLogic extends BaseLogic
private const PERMISSION_ASSISTANT = 'tcm.diagnosis/aiassistant';
private const PERMISSION_GENERATE_PRESCRIPTION = 'tcm.diagnosis/aigenerateprescription';
private const PATIENT_OPTIONS_DEFAULT_PAGE_SIZE = 20;
private const PATIENT_OPTIONS_MAX_PAGE_SIZE = 50;
@@ -355,72 +360,117 @@ class DiagnosisAiLogic extends BaseLogic
string $task,
string $prompt,
int $adminId,
array $adminInfo
array $adminInfo,
?AssistantSseTiming $timing = null
): ?array {
self::$assistantErrorCode = 'AI_ASSISTANT_FAILED';
$diagnosis = self::loadAuthorizedDiagnosis(
$diagnosisId,
$adminId,
$adminInfo,
self::PERMISSION_ASSISTANT,
'权限不足,无法使用诊单 AI 助手'
);
if ($diagnosis === null) {
return null;
}
$prepareStartedAt = hrtime(true);
$aggregateMs = 0;
$compactionMs = 0;
$sourceBytes = 0;
$queryBytes = 0;
$attachmentCount = 0;
$compactionAttempted = false;
$status = 'error';
try {
self::$assistantErrorCode = 'AI_ASSISTANT_FAILED';
$task = strtolower(trim($task));
if (!isset(self::ASSISTANT_TASKS[$task])) {
self::setError('不支持的 AI 助手任务');
return null;
}
if ($task === 'prescription_generate'
&& !self::hasPermission($adminId, $adminInfo, self::PERMISSION_GENERATE_PRESCRIPTION)) {
self::setError('权限不足,无法使用 AI 生成处方');
return null;
}
$task = strtolower(trim($task));
if (!isset(self::ASSISTANT_TASKS[$task])) {
self::setError('不支持的 AI 助手任务');
return null;
}
$prompt = self::cleanText($prompt, self::MAX_ASSISTANT_PROMPT_LENGTH, true);
if ($task === 'custom' && $prompt === '') {
self::setError('请输入要咨询的问题');
return null;
}
$diagnosis = self::loadAuthorizedDiagnosis(
$diagnosisId,
$adminId,
$adminInfo,
self::PERMISSION_ASSISTANT,
'权限不足,无法使用诊单 AI 助手'
);
if ($diagnosis === null) {
return null;
}
$context = self::buildCaseContext($diagnosis, $adminId, $adminInfo);
if ($context['case_lines'] === []) {
self::setError('患者纵向资料为空或聚合失败,无法使用 AI 助手');
return null;
}
$prompt = self::cleanText($prompt, self::MAX_ASSISTANT_PROMPT_LENGTH, true);
if ($task === 'custom' && $prompt === '') {
self::setError('请输入要咨询的问题');
return null;
}
$profile = self::selectAssistantProfile($task, $prompt);
$modelConfig = self::modelConfigs()[$profile] ?? [];
$model = trim((string) ($modelConfig['name'] ?? ''));
$modelLabel = trim((string) ($modelConfig['label'] ?? $profile));
if ($model === '') {
self::setError('AI 模型服务尚未完整配置');
return null;
}
$aggregateStartedAt = hrtime(true);
$context = self::buildCaseContext($diagnosis, $adminId, $adminInfo);
$aggregateMs = AssistantSseTiming::elapsedMs($aggregateStartedAt);
$sourceBytes = strlen((string) ($context['case_text'] ?? ''));
$attachmentCount = count(is_array($context['files'] ?? null) ? $context['files'] : []);
if ($context['case_lines'] === []) {
self::setError('患者纵向资料为空或聚合失败,无法使用 AI 助手');
return null;
}
if (!self::fitContextForPrompt($context, $profile)) {
return null;
}
$profile = self::selectAssistantProfile($task, $prompt);
$modelConfig = self::modelConfigs()[$profile] ?? [];
$model = trim((string) ($modelConfig['name'] ?? ''));
$modelLabel = trim((string) ($modelConfig['label'] ?? $profile));
if ($model === '') {
self::setError('AI 模型服务尚未完整配置');
return null;
}
return [
'diagnosis_id' => $diagnosisId,
'profile' => $profile,
'model_name' => $model,
'model_label' => $modelLabel,
'task' => $task,
'inputs' => self::buildUpstreamInputs(
$compactionAttempted = $sourceBytes > self::MAX_PROMPT_SOURCE_BYTES;
$compactionStartedAt = hrtime(true);
if (!self::fitContextForPrompt($context, $profile, $timing)) {
$compactionMs = $compactionAttempted ? AssistantSseTiming::elapsedMs($compactionStartedAt) : 0;
return null;
}
$compactionMs = $compactionAttempted ? AssistantSseTiming::elapsedMs($compactionStartedAt) : 0;
$query = self::buildAssistantPrompt($context, $task, $prompt);
$inputs = self::buildUpstreamInputs(
$context,
'病例问诊助手',
self::ASSISTANT_PROMPT_VERSION
),
'query' => self::buildAssistantPrompt($context, $task, $prompt),
'user' => 'admin-diagnosis-assistant-' . $adminId,
'admin_id' => $adminId,
'files' => is_array($context['files'] ?? null) ? $context['files'] : [],
'context_scope' => (string) ($context['context_scope'] ?? 'patient_longitudinal'),
'context_version' => (string) ($context['context_version'] ?? self::ASSISTANT_PROMPT_VERSION),
'source_summary' => is_array($context['source_summary'] ?? null) ? $context['source_summary'] : [],
'source_diagnosis_ids' => is_array($context['source_diagnosis_ids'] ?? null)
? $context['source_diagnosis_ids']
: [],
];
);
$knowledgeSource = NihaixiaClinicalSkill::knowledgeSource();
$queryBytes = strlen($query);
$status = 'ok';
return [
'diagnosis_id' => $diagnosisId,
'profile' => $profile,
'model_name' => $model,
'model_label' => $modelLabel,
'task' => $task,
'inputs' => $inputs,
'query' => $query,
'knowledge_source' => $knowledgeSource,
'user' => 'admin-diagnosis-assistant-' . $adminId,
'admin_id' => $adminId,
'files' => is_array($context['files'] ?? null) ? $context['files'] : [],
'context_scope' => (string) ($context['context_scope'] ?? 'patient_longitudinal'),
'context_version' => (string) ($context['context_version'] ?? self::ASSISTANT_PROMPT_VERSION),
'source_summary' => is_array($context['source_summary'] ?? null) ? $context['source_summary'] : [],
'source_diagnosis_ids' => is_array($context['source_diagnosis_ids'] ?? null)
? $context['source_diagnosis_ids']
: [],
];
} finally {
if ($timing !== null) {
$timing->log('prepare', [
'duration_ms' => AssistantSseTiming::elapsedMs($prepareStartedAt),
'aggregate_ms' => $aggregateMs,
'compaction_ms' => $compactionMs,
'source_bytes' => $sourceBytes,
'query_bytes' => $queryBytes,
'attachment_count' => $attachmentCount,
'compaction_attempted' => $compactionAttempted,
'status' => $status,
]);
}
}
}
/**
@@ -432,74 +482,42 @@ class DiagnosisAiLogic extends BaseLogic
public static function streamPreparedAssistant(
array $prepared,
callable $onDelta,
?callable $shouldAbort = null
?callable $shouldAbort = null,
?AssistantSseTiming $timing = null
): ?array {
$diagnosisId = (int) ($prepared['diagnosis_id'] ?? 0);
$profile = (string) ($prepared['profile'] ?? '');
$adminId = (int) ($prepared['admin_id'] ?? 0);
$deliveredDelta = false;
$forwardDelta = static function (string $delta) use (&$deliveredDelta, $onDelta) {
$deltaCount = 0;
$deltaBytes = 0;
$retryAttempted = false;
$retryMs = 0;
$status = 'error';
$upstreamStartedAt = hrtime(true);
$forwardDelta = static function (string $delta) use (&$deliveredDelta, &$deltaCount, &$deltaBytes, $onDelta) {
$accepted = $onDelta($delta);
if ($accepted !== false) {
$deliveredDelta = true;
++$deltaCount;
$deltaBytes += strlen($delta);
}
return $accepted;
};
try {
$result = DifyChatService::streamChat(
$profile,
is_array($prepared['inputs'] ?? null) ? $prepared['inputs'] : [],
(string) ($prepared['query'] ?? ''),
(string) ($prepared['user'] ?? ''),
$forwardDelta,
$shouldAbort,
is_array($prepared['files'] ?? null) ? $prepared['files'] : []
);
} catch (\Throwable $e) {
self::logAssistantFailure(
$diagnosisId,
$profile,
$adminId,
$e,
(string) ($prepared['task'] ?? '')
);
self::$assistantErrorCode = 'UPSTREAM_UNAVAILABLE';
self::setError('AI 助手暂时不可用,请稍后重试');
return null;
}
if (empty($result['ok'])) {
self::logAssistantUpstreamError(
$diagnosisId,
$profile,
$adminId,
(string) ($prepared['task'] ?? ''),
is_array($result) ? $result : []
);
// Some Dify-compatible gateways accept blocking chat but reject or
// incompletely terminate streaming responses. Before any delta has
// reached the doctor it is safe to make one blocking compatibility
// attempt; after a delta, retrying could duplicate clinical text.
$streamErrorCode = strtoupper(trim((string) ($result['error_code'] ?? '')));
if (
!$deliveredDelta
&& in_array(
$streamErrorCode,
['UPSTREAM_REJECTED', 'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE'],
true
)
) {
try {
$result = DifyChatService::chat(
$profile,
is_array($prepared['inputs'] ?? null) ? $prepared['inputs'] : [],
(string) ($prepared['query'] ?? ''),
(string) ($prepared['user'] ?? ''),
is_array($prepared['files'] ?? null) ? $prepared['files'] : []
);
} catch (\Throwable $e) {
try {
$result = DifyChatService::streamChat(
$profile,
is_array($prepared['inputs'] ?? null) ? $prepared['inputs'] : [],
(string) ($prepared['query'] ?? ''),
(string) ($prepared['user'] ?? ''),
$forwardDelta,
$shouldAbort,
is_array($prepared['files'] ?? null) ? $prepared['files'] : []
);
} catch (\Throwable $e) {
if ($timing === null) {
self::logAssistantFailure(
$diagnosisId,
$profile,
@@ -508,7 +526,14 @@ class DiagnosisAiLogic extends BaseLogic
(string) ($prepared['task'] ?? '')
);
}
if (empty($result['ok'])) {
$status = 'exception';
self::$assistantErrorCode = 'UPSTREAM_UNAVAILABLE';
self::setError('AI 助手暂时不可用,请稍后重试');
return null;
}
if (empty($result['ok'])) {
if ($timing === null) {
self::logAssistantUpstreamError(
$diagnosisId,
$profile,
@@ -517,10 +542,72 @@ class DiagnosisAiLogic extends BaseLogic
is_array($result) ? $result : []
);
}
// Some Dify-compatible gateways accept blocking chat but reject or
// incompletely terminate streaming responses. Before any delta has
// reached the doctor it is safe to make one blocking compatibility
// attempt; after a delta, retrying could duplicate clinical text.
$streamErrorCode = strtoupper(trim((string) ($result['error_code'] ?? '')));
if (
!$deliveredDelta
&& in_array(
$streamErrorCode,
['UPSTREAM_REJECTED', 'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE'],
true
)
) {
$retryAttempted = true;
$retryStartedAt = hrtime(true);
try {
$result = DifyChatService::chat(
$profile,
is_array($prepared['inputs'] ?? null) ? $prepared['inputs'] : [],
(string) ($prepared['query'] ?? ''),
(string) ($prepared['user'] ?? ''),
is_array($prepared['files'] ?? null) ? $prepared['files'] : []
);
} catch (\Throwable $e) {
if ($timing === null) {
self::logAssistantFailure(
$diagnosisId,
$profile,
$adminId,
$e,
(string) ($prepared['task'] ?? '')
);
}
}
$retryMs = AssistantSseTiming::elapsedMs($retryStartedAt);
if (empty($result['ok'])) {
if ($timing === null) {
self::logAssistantUpstreamError(
$diagnosisId,
$profile,
$adminId,
(string) ($prepared['task'] ?? ''),
is_array($result) ? $result : []
);
}
}
}
}
$formatted = self::formatAssistantResult($prepared, $result);
$status = $formatted === null ? 'error' : 'ok';
return $formatted;
} finally {
if ($timing !== null) {
$timing->log('upstream_done', [
'duration_ms' => AssistantSseTiming::elapsedMs($upstreamStartedAt),
'retry_ms' => $retryMs,
'retry_attempted' => $retryAttempted,
'delta_count' => $deltaCount,
'delta_bytes' => $deltaBytes,
'status' => $status,
'error_code' => $status !== 'ok' ? self::getAssistantErrorCode() : '',
]);
}
}
return self::formatAssistantResult($prepared, $result);
}
/**
@@ -551,6 +638,8 @@ class DiagnosisAiLogic extends BaseLogic
$payload = [
'diagnosis_id' => (int) ($prepared['diagnosis_id'] ?? 0),
'answer' => $content,
'knowledge_source' => NihaixiaClinicalSkill::knowledgeSource(),
'ancient_book_sources' => is_array($result['ancient_book_sources'] ?? null) ? $result['ancient_book_sources'] : [],
'model_key' => (string) ($prepared['profile'] ?? ''),
'model_label' => (string) ($prepared['model_label'] ?? ''),
'model_name' => (string) ($prepared['model_name'] ?? ''),
@@ -783,48 +872,54 @@ class DiagnosisAiLogic extends BaseLogic
return null;
}
try {
$result = DifyChatService::chat(
$profile,
self::buildUpstreamInputs(
$context,
'诊单结构化分析',
self::ANALYSIS_PROMPT_VERSION
),
self::buildAnalysisPrompt($context),
'admin-diagnosis-analysis-' . $adminId,
is_array($context['files'] ?? null) ? $context['files'] : []
);
} catch (\Throwable $e) {
Log::warning('diagnosis ai analysis upstream call failed', [
'diagnosis_id' => $diagnosisId,
'profile' => $profile,
'admin_id' => $adminId,
'exception_class' => get_class($e),
]);
self::setError('AI智能分析暂时不可用,请稍后重试');
return null;
}
$inputs = self::buildUpstreamInputs($context, '诊单结构化分析', self::ANALYSIS_PROMPT_VERSION);
$prompt = self::buildAnalysisPrompt($context);
$files = is_array($context['files'] ?? null) ? $context['files'] : [];
$analysis = null;
for ($attempt = 0; $attempt < 2; $attempt++) {
try {
$result = DifyChatService::chat(
$profile,
$inputs,
$attempt === 0 ? $prompt : self::buildAnalysisRepairPrompt($prompt),
'admin-diagnosis-analysis-' . $adminId,
$files
);
} catch (\Throwable $e) {
Log::warning('diagnosis ai analysis upstream call failed', [
'diagnosis_id' => $diagnosisId,
'profile' => $profile,
'admin_id' => $adminId,
'exception_class' => get_class($e),
]);
self::setError('AI智能分析暂时不可用,请稍后重试');
return null;
}
if (empty($result['ok'])) {
self::setError('AI智能分析暂时不可用,请稍后重试');
return null;
if (empty($result['ok'])) {
self::setError('AI智能分析暂时不可用,请稍后重试');
return null;
}
$analysis = self::parseAnalysisResponse((string) ($result['content'] ?? ''));
if ($analysis !== null) {
break;
}
}
$analysis = self::parseAnalysisResponse((string) ($result['content'] ?? ''));
if ($analysis === null) {
self::setError('AI返回的分析结构不符合要求,请重试');
return null;
}
return array_merge($analysis, [
'knowledge_source' => NihaixiaClinicalSkill::knowledgeSource(),
'ancient_book_sources' => is_array($result['ancient_book_sources'] ?? null) ? $result['ancient_book_sources'] : [],
'diagnosis_id' => $diagnosisId,
'model_key' => $profile,
'model_label' => $modelLabel,
'model_name' => $modelName,
'generated_at' => date('Y-m-d H:i:s'),
'context_scope' => (string) ($context['context_scope'] ?? 'patient_longitudinal'),
'context_version' => (string) ($context['context_version'] ?? self::ANALYSIS_PROMPT_VERSION),
'context_version' => self::ANALYSIS_PROMPT_VERSION,
'source_summary' => is_array($context['source_summary'] ?? null)
? $context['source_summary']
: [],
@@ -938,7 +1033,8 @@ class DiagnosisAiLogic extends BaseLogic
$modelLabel,
$content,
(string) ($result['message_id'] ?? ''),
$adminId
$adminId,
is_array($result['ancient_book_sources'] ?? null) ? $result['ancient_book_sources'] : []
);
} catch (\Throwable $e) {
Log::warning('diagnosis ai report persist failed', [
@@ -1035,7 +1131,7 @@ class DiagnosisAiLogic extends BaseLogic
$context = self::buildCaseContext($diagnosis, $adminId, $adminInfo);
return [
'diagnosis_id' => $id,
'report' => self::formatReportRow($report->toArray(), $context['fingerprint']),
'report' => self::formatReportRow($report->toArray(), $context['fingerprint'], $context),
'can_edit' => self::hasPermission($adminId, $adminInfo, self::PERMISSION_EDIT),
'can_refresh' => self::hasPermission($adminId, $adminInfo, self::PERMISSION_REFRESH),
];
@@ -1442,6 +1538,13 @@ PROMPT;
PROMPT;
}
private static function buildAnalysisRepairPrompt(string $originalPrompt): string
{
return $originalPrompt . "\n\n格式校验提醒:请重新独立作答,只输出一个可解析的 JSON 对象,且仅有 diagnosis_advice、risk_assessment、treatment_advice 三个键。"
. '前后不要解释、代码块或参考资料版本标识;两个建议字段各不超过 500 字;risk_assessment 最多 5 项,'
. '每项仅有 label(不超过 80 字)与小写 level(high、medium、low)。资料不足时说明缺口,不能编造风险或处方。';
}
/**
* 让患者纵向资料适配单次上游请求的体积上限。
*
@@ -1450,7 +1553,11 @@ PROMPT;
*
* @param array<string,mixed> $context
*/
private static function fitContextForPrompt(array &$context, string $profile): bool
private static function fitContextForPrompt(
array &$context,
string $profile,
?AssistantSseTiming $timing = null
): bool
{
$caseText = (string) ($context['case_text'] ?? '');
if ($caseText === '' || strlen($caseText) <= self::MAX_PROMPT_SOURCE_BYTES) {
@@ -1460,12 +1567,12 @@ PROMPT;
try {
$compacted = PatientAiReportLogic::compactSourceForPrompt($profile, $caseText);
} catch (\Throwable $e) {
Log::warning('diagnosis ai context compaction failed', [
'diagnosis_id' => (int) ($context['diagnosis_id'] ?? 0),
'profile' => $profile,
'source_bytes' => strlen($caseText),
'exception_class' => get_class($e),
]);
if ($timing === null) {
Log::warning('diagnosis ai context compaction failed', [
'source_bytes' => strlen($caseText),
'exception_class' => get_class($e),
]);
}
self::setError('患者纵向资料过大,AI 分片读取失败,请稍后重试');
return false;
}
@@ -1593,7 +1700,8 @@ PROMPT;
string $modelLabel,
string $content,
string $messageId,
int $adminId
int $adminId,
array $ancientBookSources = []
): int {
$now = time();
$row = [
@@ -1603,6 +1711,7 @@ PROMPT;
'model_label' => self::cleanText($modelLabel, 50),
'report_content' => $content,
'message_id' => self::cleanText($messageId, 191),
'ancient_book_sources_json' => json_encode(TcmAncientBooksReference::localizeSources($ancientBookSources), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '[]',
'prompt_version' => self::PROMPT_VERSION,
'case_fingerprint' => (string) $context['fingerprint'],
'generated_by' => $adminId,
@@ -1618,6 +1727,7 @@ PROMPT;
'model_label',
'report_content',
'message_id',
'ancient_book_sources_json',
'prompt_version',
'case_fingerprint',
'generated_by',
@@ -1658,7 +1768,8 @@ PROMPT;
if (isset($rowsByModel[$modelKey])) {
$reports[] = self::formatReportRow(
$rowsByModel[$modelKey],
(string) $context['fingerprint']
(string) $context['fingerprint'],
$context
);
}
}
@@ -1691,11 +1802,14 @@ PROMPT;
* @param array<string,mixed> $row
* @return array<string,mixed>
*/
private static function formatReportRow(array $row, string $currentFingerprint): array
private static function formatReportRow(array $row, string $currentFingerprint, array $context = []): array
{
$content = (string) ($row['report_content'] ?? '');
$generatedTime = (int) ($row['generated_time'] ?? 0);
$editedTime = (int) ($row['edited_time'] ?? 0);
// The fingerprint includes the source summary and diagnosis IDs. Reuse
// current provenance only while it still matches the saved report.
$sameSources = hash_equals($currentFingerprint, (string) ($row['case_fingerprint'] ?? ''));
return [
'id' => (int) ($row['id'] ?? 0),
@@ -1706,13 +1820,16 @@ PROMPT;
'content' => $content,
'report' => self::parseReport($content),
'message_id' => (string) ($row['message_id'] ?? ''),
'knowledge_source' => NihaixiaClinicalSkill::knowledgeSourceForPromptVersion((string) ($row['prompt_version'] ?? '')),
'ancient_book_sources' => self::decodeAncientBookSources($row['ancient_book_sources_json'] ?? ''),
'prompt_version' => (string) ($row['prompt_version'] ?? ''),
'case_fingerprint' => (string) ($row['case_fingerprint'] ?? ''),
'prescription_fingerprint' => (string) ($row['case_fingerprint'] ?? ''),
'is_stale' => !hash_equals(
$currentFingerprint,
(string) ($row['case_fingerprint'] ?? '')
),
'is_stale' => !$sameSources,
'source_summary' => $sameSources && is_array($context['source_summary'] ?? null)
? $context['source_summary'] : [],
'source_diagnosis_ids' => $sameSources && is_array($context['source_diagnosis_ids'] ?? null)
? array_values(array_map('intval', $context['source_diagnosis_ids'])) : [],
'generated_by' => (int) ($row['generated_by'] ?? 0),
'generated_time' => $generatedTime,
'generated_at' => $generatedTime > 0 ? date('Y-m-d H:i:s', $generatedTime) : '',
@@ -1723,6 +1840,14 @@ PROMPT;
];
}
/** @return list<array<string,mixed>> */
private static function decodeAncientBookSources(mixed $value): array
{
$decoded = is_string($value) ? json_decode($value, true) : null;
return is_array($decoded) && array_is_list($decoded)
? TcmAncientBooksReference::localizeSources($decoded) : [];
}
/** @return array<string,array<string,mixed>> */
private static function modelConfigs(): array
{
@@ -1760,8 +1885,24 @@ PROMPT;
return null;
}
// Qwen occasionally drops letters from this key while keeping the other
// two contract keys intact. Accept only the two observed spellings, and
// never choose between conflicting diagnosis fields.
if (!array_key_exists('diagnosis_advice', $decoded)) {
$aliases = array_intersect(['diagnosis_adive', 'diagnosis_ad'], array_keys($decoded));
if (count($aliases) !== 1) {
return null;
}
$diagnosisField = $decoded[reset($aliases)];
} else {
if (array_key_exists('diagnosis_adive', $decoded) || array_key_exists('diagnosis_ad', $decoded)) {
return null;
}
$diagnosisField = $decoded['diagnosis_advice'];
}
$diagnosisAdvice = self::validatedAnalysisText(
$decoded['diagnosis_advice'] ?? null,
$diagnosisField,
self::MAX_ANALYSIS_ADVICE_LENGTH,
true
);
@@ -277,8 +277,8 @@ class DiagnosisLogic extends BaseLogic
$diagnosis = Diagnosis::findOrEmpty($params['id'])->toArray();
// 处理既往史为数组
if (!empty($diagnosis['past_history'])) {
$diagnosis['past_history'] = explode(',', $diagnosis['past_history']);
if (($diagnosis['past_history'] ?? null) !== null && $diagnosis['past_history'] !== '') {
$diagnosis['past_history'] = explode(',', (string) $diagnosis['past_history']);
} else {
$diagnosis['past_history'] = [];
}
@@ -291,8 +291,8 @@ class DiagnosisLogic extends BaseLogic
];
foreach ($multiSelectFields as $field) {
if (!empty($diagnosis[$field])) {
$diagnosis[$field] = explode(',', $diagnosis[$field]);
if (($diagnosis[$field] ?? null) !== null && $diagnosis[$field] !== '') {
$diagnosis[$field] = explode(',', (string) $diagnosis[$field]);
} else {
$diagnosis[$field] = [];
}
@@ -379,8 +379,8 @@ class DiagnosisLogic extends BaseLogic
}
// 处理既往史为数组
if (!empty($diagnosis['past_history'])) {
$diagnosis['past_history'] = explode(',', $diagnosis['past_history']);
if (($diagnosis['past_history'] ?? null) !== null && $diagnosis['past_history'] !== '') {
$diagnosis['past_history'] = explode(',', (string) $diagnosis['past_history']);
} else {
$diagnosis['past_history'] = [];
}
@@ -393,8 +393,8 @@ class DiagnosisLogic extends BaseLogic
];
foreach ($multiSelectFields as $field) {
if (!empty($diagnosis[$field])) {
$diagnosis[$field] = explode(',', $diagnosis[$field]);
if (($diagnosis[$field] ?? null) !== null && $diagnosis[$field] !== '') {
$diagnosis[$field] = explode(',', (string) $diagnosis[$field]);
} else {
$diagnosis[$field] = [];
}
@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
namespace app\adminapi\logic\tcm;
use app\common\service\followupaudio\FollowupAudioAccess as Access;
use app\common\service\followupaudio\FollowupAudioApply as Apply;
use app\common\service\followupaudio\FollowupAudioFields as Fields;
use app\common\service\followupaudio\FollowupAudioGate as Gate;
use app\common\service\followupaudio\FollowupAudioProviderConfig as ProviderConfig;
use app\common\service\followupaudio\FollowupAudioStore as Store;
use app\common\service\followupaudio\FollowupAudioUpload as Upload;
use DomainException;
use app\common\service\followupaudio\FollowupAudioReextract as Reextract;
final class FollowupAudioLogic
{
public static function capabilities(int $diagnosisId, int $actor, array $info): array
{
$diagnosis = Access::diagnosis($diagnosisId, $actor, $info, false, false);
$scope = Gate::scopeAllowed($diagnosisId, $actor);
$preview = Gate::previewOnly();
$ready = Store::ready();
$enabled = Store::enabled() && $scope;
$verified = Store::verified();
$manualReady = Gate::manualReviewReady();
$daily = Access::canDaily($actor, $info);
return [
'enabled' => $enabled, 'audio_verified' => $verified,
'manual_review_enabled' => Gate::manualReviewEnabled(), 'manual_review_ready' => $manualReady,
'preview_only' => $preview, 'preview_ready' => $preview && $ready, 'test_scope_allowed' => $scope,
'can_upload' => $enabled && $ready, 'can_review' => $enabled && $ready, 'can_apply' => $enabled && ($verified || $manualReady) && !$preview,
'can_daily' => $daily, 'limits' => Upload::limits(),
'models' => $enabled ? ProviderConfig::readyModels() : [],
// No migration/dictionary dependency is introduced when the feature is OFF.
'fields' => $enabled ? self::catalogForActor($diagnosis, $actor, $info) : [],
];
}
public static function requireEnabled(bool $verified = false): void
{
if (!Store::enabled()) {
throw new DomainException('回访录音功能尚未启用');
}
if ($verified && !Store::ready()) {
throw new DomainException('当前服务与模型的音频能力尚未验证,暂不接受真实录音或写入');
}
}
public static function create(array $p, int $actor, array $info): array
{
$channelRoles = Store::validateChannelRoles(array_key_exists('channel_roles', $p) ? $p['channel_roles'] : 'unconfirmed');
self::requireEnabled(true);
Access::diagnosis($p['diagnosis_id'], $actor, $info);
$upload = Upload::owned($p['upload_id'], $actor, $info);
if ((int) $upload['diagnosis_id'] !== $p['diagnosis_id'] || $upload['status'] !== 'complete') {
throw new DomainException('录音与当前诊单不匹配或尚未上传完成');
}
Upload::path($upload);
$date = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $p['recorded_at'], new \DateTimeZone('Asia/Shanghai'));
if (!$date || $date->format('Y-m-d H:i:s') !== $p['recorded_at'] || $date->getTimestamp() > time() + 300) {
throw new DomainException('请填写正确的实际通话时间(北京时间),不能晚于当前时间');
}
if (!in_array($p['model_key'], ['qwen', 'openai'], true) || !Store::ready($p['model_key'])) {
throw new DomainException('所选模型音频能力尚未验证');
}
return Store::create($upload, $p['recorded_at'], $p['model_key'], $actor, $info, $channelRoles);
}
public static function lists(int $diagnosisId, int $actor, array $info): array
{
Access::diagnosis($diagnosisId, $actor, $info);
return ['items' => Store::enabled() ? array_map(static fn (array $task): array =>
self::withDeleteCapability($task, $actor), Store::lists($diagnosisId)) : []];
}
public static function detail(int $id, int $actor, array $info): array
{
Access::task($id, $actor, $info);
return self::protectDetail(Store::detail($id), $actor, $info);
}
public static function saveDraft(int $id, int $version, array $items, int $actor, array $info, ?string $channelRoles = null): array
{
self::requireEnabled();
$task = Access::task($id, $actor, $info);
self::checkDailyItems($task, $items, $actor, $info);
return self::protectDetail(Store::saveDraft($id, $version, $items, $actor, $channelRoles), $actor, $info);
}
public static function apply(int $id, int $version, array $items, int $actor, array $info): array
{
Gate::assertMayApply();
self::requireEnabled(true);
$task = Access::task($id, $actor, $info);
self::checkDailyItems($task, $items, $actor, $info);
return Apply::apply($id, $version, $items, $actor, $info);
}
public static function delete(int $id, int $version, int $actor, array $info): array
{
self::requireEnabled();
return Store::delete($id, $version, $actor, $info);
}
private static function withDeleteCapability(array $summary, int $actor): array
{
$task = Store::task((int) $summary['id']);
$info = Access::actor($actor);
$reason = !Store::enabled() ? '回访录音功能尚未启用' : Access::deleteReason($task, $actor);
if ($reason === '') { $reason = Store::deleteBlockReason($task); }
$reextractReason = (int) $info['root'] !== 1 && (int) $task['actor_id'] !== $actor
? '仅上传者或超级管理员可重新提炼' : Reextract::blockReason($task);
return $summary + ['can_delete' => $reason === '', 'delete_block_reason' => $reason,
'can_reextract' => $reextractReason === '', 'reextract_block_reason' => $reextractReason];
}
public static function reextract(int $id, int $version, $roles, int $actor, array $info): array
{
self::requireEnabled(true);
return self::protectDetail(Reextract::queue($id, $version, $roles, $actor, $info), $actor, $info);
}
public static function retry(int $id, int $actor, array $info): array
{
self::requireEnabled(true);
Access::task($id, $actor, $info);
return Store::retry($id);
}
private static function checkDailyItems(array $task, array $items, int $actor, array $info): void
{
$diagnosis = Access::diagnosis((int) $task['diagnosis_id'], $actor, $info);
$plain = Access::allowed($actor, Access::actor($actor), 'tcm.diagnosis/phonePlain');
foreach ($items as $item) {
if (!is_array($item)) {
throw new DomainException('审阅内容无效');
}
if (!empty($item['selected']) && ($item['kind'] ?? '') === 'diagnosis' && !$plain) {
foreach (['phone', 'id_card'] as $key) {
if ($key === 'id_card' && trim((string) ($diagnosis[$key] ?? '')) === '') {
continue;
}
if (array_key_exists($key, (array) ($item['values'] ?? []))
&& (string) $item['values'][$key] !== (string) ($diagnosis[$key] ?? '')) {
throw new DomainException('无权通过录音修改已有手机号或身份证');
}
}
}
if (!empty($item['selected']) && ($item['kind'] ?? '') !== 'diagnosis') {
Access::diagnosis((int) $task['diagnosis_id'], $actor, $info, true);
// Continue to validate identity suggestions later in this same batch.
}
}
}
private static function catalogForActor(array $diagnosis, int $actor, array $info): array
{
$info = Access::actor($actor);
$catalog = Fields::catalog();
$basic = DiagnosisLogic::canEditPatientBasicInfo((int) $diagnosis['id'], $info);
$plain = Access::allowed($actor, $info, 'tcm.diagnosis/phonePlain');
foreach ($catalog['diagnosis'] as &$field) {
$key = $field['key'];
if ((!$basic && in_array($key, ['patient_name', 'id_card', 'phone', 'gender', 'age'], true))
|| (!$plain && ($key === 'phone' || ($key === 'id_card' && !empty($diagnosis['id_card']))))) {
$field['readonly'] = true;
}
}
unset($field);
return $catalog;
}
private static function protectDetail(array $detail, int $actor, array $info): array
{
$diagnosis = Access::diagnosis((int) $detail['diagnosis_id'], $actor, $info);
$detail['fields'] = self::catalogForActor($diagnosis, $actor, $info);
if (!Access::allowed($actor, Access::actor($actor), 'tcm.diagnosis/phonePlain')) {
foreach ($detail['items'] as &$item) {
foreach (['phone', 'id_card'] as $key) {
$value = (string) ($item['current_values'][$key] ?? '');
if ($value !== '') {
$item['current_values'][$key] = mb_substr($value, 0, 3) . '****' . mb_substr($value, -4);
}
}
}
unset($item);
}
return self::withDeleteCapability($detail, $actor);
}
}
@@ -11,6 +11,8 @@ use app\common\model\auth\AdminDept;
use app\common\model\dept\Dept;
use app\common\model\tcm\PatientAiReport;
use app\common\service\DifyChatService;
use app\common\service\NihaixiaClinicalSkill;
use app\common\service\TcmAncientBooksReference;
use app\common\service\FileService;
use think\facade\Db;
use think\facade\Log;
@@ -41,7 +43,7 @@ class PatientAiReportLogic extends BaseLogic
private const PERMISSION_GENERATE = 'tcm.diagnosis/generatepatientaireport';
private const PROMPT_VERSION = 'patient-longitudinal-report-v2';
private const PROMPT_VERSION = 'patient-longitudinal-report-nihaixia-ancient-v4';
/** @var array<int,string> */
private const MODEL_KEYS = ['qwen', 'openai'];
@@ -246,6 +248,8 @@ class PatientAiReportLogic extends BaseLogic
'source_snapshot' => $sourceJson,
'source_summary_json' => self::encodeJson($sourceSummary),
'source_diagnosis_ids_json' => self::encodeJson($diagnosisIds),
'ancient_book_sources_json' => self::encodeJson(TcmAncientBooksReference::localizeSources(
is_array($upstream['ancient_book_sources'] ?? null) ? $upstream['ancient_book_sources'] : [])),
'source_hash' => $sourceHash,
'prompt_version' => self::PROMPT_VERSION,
'message_id' => self::cleanText($upstream['message_id'] ?? '', 191),
@@ -276,6 +280,8 @@ class PatientAiReportLogic extends BaseLogic
'report' => $generatedReport,
'disclaimer' => self::DISCLAIMER,
'source_summary' => $generatedReport['source_summary'] ?? self::emptySourceSummary(),
'source_diagnosis_ids' => $generatedReport['source_diagnosis_ids'] ?? [],
'knowledge_source' => $generatedReport['knowledge_source'] ?? null,
];
}
@@ -988,6 +994,7 @@ class PatientAiReportLogic extends BaseLogic
$chunkCount = count($chunks);
$inputs = self::sourceInputsForUpstream($snapshot['source_summary'] ?? []);
$files = self::collectUpstreamFiles($snapshot);
$ancientBookSources = [];
if ($chunkCount === 1) {
$result = DifyChatService::chat(
@@ -1025,6 +1032,7 @@ class PatientAiReportLogic extends BaseLogic
if (empty($part['ok']) || trim((string) ($part['content'] ?? '')) === '') {
throw new \RuntimeException('Patient evidence chunk analysis failed');
}
$ancientBookSources = self::mergeAncientBookSources($ancientBookSources, $part);
$summaries[] = [
'part' => $index + 1,
'total' => $chunkCount,
@@ -1057,6 +1065,7 @@ class PatientAiReportLogic extends BaseLogic
if (empty($part['ok']) || trim((string) ($part['content'] ?? '')) === '') {
throw new \RuntimeException('Patient evidence reduction failed');
}
$ancientBookSources = self::mergeAncientBookSources($ancientBookSources, $part);
$reduced[] = [
'part' => $index + 1,
'total' => count($summaryChunks),
@@ -1084,11 +1093,49 @@ class PatientAiReportLogic extends BaseLogic
'patient-longitudinal-report'
);
$result['analysis_chunk_count'] = $chunkCount;
$result['ancient_book_sources'] = self::mergeAncientBookSources($ancientBookSources, $result);
$result['analysis_reduction_rounds'] = $reductionRounds;
$result['analyzed_source_bytes'] = strlen($sourceJson);
return $result;
}
/** @param list<array<string,mixed>> $accumulated
* @param array<string,mixed> $response
* @return list<array<string,mixed>>
*/
private static function mergeAncientBookSources(array $accumulated, array $response): array
{
$sources = $response['ancient_book_sources'] ?? [];
if (!is_array($sources)) {
return $accumulated;
}
$seen = [];
foreach ($accumulated as $source) {
$seen[self::ancientBookSourceKey($source)] = true;
}
foreach ($sources as $source) {
if (!is_array($source)) {
continue;
}
$key = self::ancientBookSourceKey($source);
if (isset($seen[$key])) {
continue;
}
$seen[$key] = true;
$accumulated[] = $source;
if (count($accumulated) >= 12) {
break;
}
}
return TcmAncientBooksReference::localizeSources($accumulated);
}
private static function ancientBookSourceKey(array $source): string
{
return (string) ($source['commit'] ?? '') . "\0" . (string) ($source['path'] ?? '')
. "\0" . (string) ($source['line'] ?? '');
}
/** @param array<string,mixed> $snapshot */
private static function buildPrompt(array $snapshot): string
{
@@ -1427,6 +1474,8 @@ class PatientAiReportLogic extends BaseLogic
'report' => $generatedReport,
'disclaimer' => self::DISCLAIMER,
'source_summary' => is_array($newest) ? ($newest['source_summary'] ?? self::emptySourceSummary()) : self::emptySourceSummary(),
'source_diagnosis_ids' => is_array($newest) ? ($newest['source_diagnosis_ids'] ?? []) : [],
'knowledge_source' => is_array($newest) ? ($newest['knowledge_source'] ?? null) : null,
];
}
@@ -1465,6 +1514,10 @@ class PatientAiReportLogic extends BaseLogic
'disclaimer' => self::DISCLAIMER,
'source_hash' => (string) ($row['source_hash'] ?? ''),
'source_summary' => $sourceSummary !== [] ? $sourceSummary : self::emptySourceSummary(),
'source_diagnosis_ids' => self::decodeJsonArray($row['source_diagnosis_ids_json'] ?? ''),
'knowledge_source' => NihaixiaClinicalSkill::knowledgeSourceForPromptVersion((string) ($row['prompt_version'] ?? '')),
'ancient_book_sources' => TcmAncientBooksReference::localizeSources(
self::decodeJsonArray($row['ancient_book_sources_json'] ?? '')),
'prompt_version' => (string) ($row['prompt_version'] ?? ''),
'version' => max((int) ($row['version'] ?? 1), 1),
'generated_time' => $generatedTime,
@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace app\adminapi\logic\tcm;
use app\common\model\auth\Admin;
use app\common\service\NihaixiaClinicalSkill;
use app\common\service\TcmAncientBooksReference;
use app\common\service\prescriptionai\PrescriptionAiAccess as Access;
use app\common\service\prescriptionai\PrescriptionAiCipher as Cipher;
use app\common\service\prescriptionai\PrescriptionAiDoctorSnapshot as DoctorSnapshot;
@@ -298,6 +300,9 @@ final class PrescriptionAiLogic
}
foreach ($results as $result) {
$body = $full ? (new Cipher())->decrypt($result['body_cipher'], 'result:' . $result['batch_id'] . ':' . $result['model_key']) : [];
if ($full) {
$body = self::localizeSourceMetadata($body);
}
unset($result['body_cipher']);
$result['score'] = $result['score'] === null ? null : (float) $result['score'];
$result['herb_score'] = $result['herb_score'] === null ? null : (float) $result['herb_score'];
@@ -321,6 +326,15 @@ final class PrescriptionAiLogic
return $map;
}
/** Existing encrypted results may still contain repository links. */
private static function localizeSourceMetadata(array $body): array
{
$body['knowledge_source'] = NihaixiaClinicalSkill::localizeKnowledgeSource($body['knowledge_source'] ?? null);
$body['ancient_book_sources'] = TcmAncientBooksReference::localizeSources(
is_array($body['ancient_book_sources'] ?? null) ? $body['ancient_book_sources'] : []);
return $body;
}
private static function formatBatch(array $batch, array $models, ?array $rx = null): array
{
$validity = $batch['validity'];
@@ -16,7 +16,7 @@ use think\facade\Log;
*/
class PrescriptionLibraryAiLogic extends BaseLogic
{
private const PROMPT_VERSION = 'rx-explain-v1';
private const PROMPT_VERSION = 'rx-explain-nihaixia-v2';
private const MAX_REPORT_LENGTH = 12000;
@@ -4,6 +4,8 @@ namespace app\adminapi\logic\tcm;
use app\common\logic\BaseLogic;
use app\common\model\tcm\TrackingNote;
use app\common\model\tcm\Diagnosis;
use think\facade\Db;
/**
* 诊单跟踪备注 Logic
@@ -36,27 +38,12 @@ class TrackingNoteLogic extends BaseLogic
return false;
}
$today = date('Y-m-d');
$time = date('H:i');
$line = "[{$time}] {$newContent}";
$existing = TrackingNote::where('diagnosis_id', $diagnosisId)
->where('note_date', $today)
->whereNull('delete_time')
->find();
if ($existing) {
$prev = trim((string) ($existing->content ?? ''));
$existing->content = $prev !== '' ? ($prev . "\n" . $line) : $line;
$existing->save();
} else {
TrackingNote::create([
'diagnosis_id' => $diagnosisId,
'admin_id' => $adminId,
'note_date' => $today,
'content' => $line,
]);
}
// Legacy entry point deliberately ignores any client-supplied note_date.
// It shares the diagnosis lock with historical appends to avoid lost updates.
$today = (new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('Y-m-d');
Db::transaction(static function () use ($diagnosisId, $today, $newContent, $adminId): void {
self::appendLocked($diagnosisId, $today, $newContent, $adminId);
});
return true;
} catch (\Exception $e) {
@@ -65,6 +52,75 @@ class TrackingNoteLogic extends BaseLogic
}
}
/**
* Explicit historical-date append for trusted application services.
*
* Caller MUST authorize diagnosis + daily-record scope and hold an active
* transaction. This method never starts/commits one: task, note and audit writes
* must roll back together. The diagnosis lock serializes the missing-row case
* with legacy appends; the note lock protects read-modify-write.
*
* @return int Actual tracking_note id (existing row or newly inserted row).
* @throws \DomainException Invalid inputs; database exceptions propagate.
*/
public static function appendForDate(int $diagnosisId, string $noteDate, string $content, int $actorId): int
{
if ($diagnosisId <= 0 || $actorId <= 0) {
throw new \DomainException('诊单或操作人缺失');
}
$content = trim($content);
if ($content === '') {
throw new \DomainException('备注内容不能为空');
}
return self::appendLocked($diagnosisId, self::normalizeNoteDate($noteDate), $content, $actorId);
}
private static function normalizeNoteDate(string $value): string
{
$value = trim($value);
$zone = new \DateTimeZone('Asia/Shanghai');
$date = \DateTimeImmutable::createFromFormat('!Y-m-d', $value, $zone);
if (!preg_match('/^[1-9]\d{3}-\d{2}-\d{2}$/D', $value) || !$date || $date->format('Y-m-d') !== $value) {
throw new \DomainException('跟踪备注日期无效,请使用 YYYY-MM-DD');
}
if ($value > (new \DateTimeImmutable('now', $zone))->format('Y-m-d')) {
throw new \DomainException('跟踪备注日期不能晚于今天');
}
return $value;
}
private static function appendLocked(int $diagnosisId, string $noteDate, string $content, int $actorId): int
{
$diagnosis = Diagnosis::where('id', $diagnosisId)->whereNull('delete_time')->lock(true)->find();
if (!$diagnosis) {
throw new \DomainException('诊单不存在');
}
$existing = TrackingNote::where('diagnosis_id', $diagnosisId)
->where('note_date', $noteDate)
->lock(true)
->find();
// The table's diagnosis/date unique key includes soft-deleted rows.
// Never resurrect a deleted note or silently replace its historic content.
if ($existing && $existing->delete_time !== null) {
throw new \DomainException('当日跟踪备注已删除,请先核实');
}
$time = (new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('H:i');
$line = "[{$time}] {$content}";
if ($existing) {
$previous = trim((string) ($existing->content ?? ''));
$existing->content = $previous !== '' ? $previous . "\n" . $line : $line;
$existing->save();
return (int) $existing->id;
}
$record = TrackingNote::create([
'diagnosis_id' => $diagnosisId,
'admin_id' => $actorId,
'note_date' => $noteDate,
'content' => $line,
]);
return (int) $record->id;
}
/**
* 按 diagnosis_id 获取跟踪备注列表(note_date DESC)
*
+30
View File
@@ -0,0 +1,30 @@
<?php
use think\facade\Route;
// Explicit method/path mapping; controller also fails closed for every v2 capability.
Route::get('iam/v2/status', 'IamV2/status');
Route::post('iam/v2/reauth', 'IamV2/reauth');
Route::get('iam/v2/accounts', 'IamV2/accounts');
Route::get('iam/v2/identities', 'IamV2/identities');
Route::post('iam/v2/operations', 'IamV2/operation');
Route::get('iam/v2/operations/:id', 'IamV2/operationResult');
Route::get('iam/v2/accounts/:id/audit', 'IamV2/audit');
Route::post('iam/v2/batch/preflight', 'IamV2/preflight');
Route::post('iam/v2/batch', 'IamV2/batch');
Route::get('iam/v2/jobs/:id', 'IamV2/job');
Route::post('iam/v2/jobs/:id/retry', 'IamV2/retry');
Route::post('iam/v2/proofs/introspect', 'IamV2/introspect');
Route::post('iam/v2/sessions/check', 'IamV2/checkSession');
Route::post('iam/v2/events/revocation', 'IamV2/revocation');
Route::post('iam/v2/launch/start', 'IamV2/launchStart');
Route::get('iam/v2/launch/continue', 'IamV2/launchContinue');
Route::post('iam/v2/self-link/start', 'IamV2/selfStart');
Route::get('iam/v2/self-link/callback', 'IamV2/selfCallback');
Route::post('iam/v2/password-setup', 'IamV2/passwordSetup');
Route::get('iam/v2/password-continue', 'IamV2/passwordContinue');
// ZYT as a target for the same person's IAM admin/portal session only.
Route::get('iam/v2/launch/config', 'IamV2/targetConfig');
Route::post('iam/v2/launch/prepare', 'IamV2/targetPrepare');
Route::post('iam/v2/launch/callback', 'IamV2/targetCallback');
Route::post('iam/v2/launch/exchange', 'IamV2/targetExchange');
Route::post('iam/v2/launch/reset', 'IamV2/targetReset');
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use think\facade\Log;
/** A request-local, patient-free timing record for the diagnosis assistant SSE path. */
final class AssistantSseTiming
{
private const PHASES = ['prepare', 'sse_start', 'first_delta', 'upstream_done', 'sse_done'];
private const NUMBER_FIELDS = [
'duration_ms', 'aggregate_ms', 'compaction_ms', 'retry_ms',
'source_bytes', 'query_bytes', 'attachment_count',
'delta_bytes', 'delta_count', 'first_delta_ms',
];
private const BOOLEAN_FIELDS = ['compaction_attempted', 'retry_attempted', 'first_delta_observed'];
private const ERROR_CODES = [
'AI_ASSISTANT_FAILED', 'UPSTREAM_UNAVAILABLE', 'UPSTREAM_REJECTED',
'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE', 'UPSTREAM_TIMEOUT',
'CONFIG_DISABLED', 'INVALID_PROFILE', 'CONFIG_MISSING', 'CONFIG_INVALID',
'CURL_UNAVAILABLE', 'SKILL_UNAVAILABLE', 'CLIENT_DISCONNECTED',
'STREAM_DELIVERY_FAILED', 'REQUEST_BUILD_FAILED', 'CURL_INIT_FAILED',
'UPSTREAM_BUSY', 'INVALID_RESPONSE',
];
private string $traceId;
public function __construct()
{
$this->traceId = bin2hex(random_bytes(16));
}
public function id(): string
{
return $this->traceId;
}
public static function elapsedMs(int $startedAt): int
{
return max(0, (int) floor((hrtime(true) - $startedAt) / 1000000));
}
/**
* Only a fixed set of numeric and boolean metadata reaches the log. In particular,
* arbitrary prompt text, patient identifiers, URLs and credentials are discarded.
*
* @param array<string,mixed> $metrics
* @return array<string,int|bool|string>
*/
public function event(string $phase, array $metrics = []): array
{
$event = [
'trace_id' => $this->traceId,
'phase' => in_array($phase, self::PHASES, true) ? $phase : 'upstream_done',
];
foreach (self::NUMBER_FIELDS as $field) {
if (isset($metrics[$field]) && is_int($metrics[$field])) {
$event[$field] = max(0, $metrics[$field]);
}
}
foreach (self::BOOLEAN_FIELDS as $field) {
if (isset($metrics[$field]) && is_bool($metrics[$field])) {
$event[$field] = $metrics[$field];
}
}
if (isset($metrics['status']) && in_array($metrics['status'], ['ok', 'error', 'exception', 'disconnected'], true)) {
$event['status'] = $metrics['status'];
}
if (isset($metrics['error_code']) && in_array($metrics['error_code'], self::ERROR_CODES, true)) {
$event['error_code'] = $metrics['error_code'];
}
return $event;
}
/** @param array<string,mixed> $metrics */
public function log(string $phase, array $metrics = []): void
{
try {
Log::info('diagnosis ai assistant timing ' . json_encode($this->event($phase, $metrics)));
} catch (\Throwable $ignored) {
// Telemetry must never interrupt the clinical request.
}
}
}
@@ -41,6 +41,11 @@ final class IamAccountProvisioner
if (($context['shouldCreateLocalAccount'] ?? null) !== true) {
return IamLoginService::boundAdminId($context, $subject, $config['application_id']);
}
// A local tombstone blocks auto-creation, not an explicitly reviewed newer central binding.
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
$tombstone = Db::name('iam_v2_binding')->where('subject', $subject)->where('state', 'revoked')->find();
if ($tombstone) { throw new RuntimeException('IAM_BINDING_REVOKED'); }
}
if (($context['externalAccountId'] ?? null) !== '') {
throw new RuntimeException('统一账号绑定状态不一致');
}
@@ -67,7 +67,7 @@ final class IamLoginService
$claims = $this->client->exchange($code, $transaction['verifier'], $transaction['nonce']);
$this->verifiedAdmin($claims['sub']);
$ticket = bin2hex(random_bytes(32));
$this->transactions->put('ticket', $ticket, $browser, ['subject' => $claims['sub']], 60);
$this->transactions->put('ticket', $ticket, $browser, ['subject' => $claims['sub'], 'auth_time' => (int) ($claims['auth_time'] ?? 0)], 60);
return $ticket;
}
@@ -79,7 +79,15 @@ final class IamLoginService
$transaction = $this->transactions->consume('ticket', $ticket, $browser);
// Recheck entitlement, binding and local status immediately before issuing the existing business token.
$admin = $this->verifiedAdmin($transaction['subject']);
return (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
// Reconcile/revoke the previous binding generation before minting the new token.
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
(new \app\adminapi\service\iam\v2\IamV2Manager())->assertLinked((int) $admin->id);
}
$result = (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'oidc', true, (int) ($transaction['auth_time'] ?? 0));
}
return $result;
}
public static function boundAdminId(array $context, string $subject, string $applicationId): int
@@ -14,6 +14,13 @@ final class IamOidcClient
private array $config;
private $transport;
private ?array $discovery = null;
private ?string $verifiedToken = null;
public function verifiedIdToken(): string
{
if ($this->verifiedToken === null) { throw new RuntimeException("IAM token not verified"); }
return $this->verifiedToken;
}
/** Transport signature: (method, url, headers, body): ['status'=>int, 'body'=>string]. */
public function __construct(array $config, ?callable $transport = null)
@@ -102,6 +109,7 @@ final class IamOidcClient
|| (isset($claims['nbf']) && (!is_int($claims['nbf']) || $claims['nbf'] > $now))) {
throw new RuntimeException('IAM ID token claims are invalid');
}
$this->verifiedToken = $response['id_token'];
return $claims;
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service\iam\v2;
use RuntimeException;
use think\facade\Config;
/** Dedicated v2 application credential; never falls back to the v1 provisioning token. */
final class IamV2Client
{
public function __construct(private ?array $settings = null, private $transport = null)
{
$this->settings ??= (array) Config::get('iam', []);
if (!self::enabled($this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
self::https((string) ($this->settings['api_url'] ?? ''));
foreach (['public_url', 'erp_url'] as $field) { self::origin((string) ($this->settings[$field] ?? '')); }
if (strlen((string) ($this->settings['v2_token'] ?? '')) < 32) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
}
public static function enabled(?array $settings = null): bool
{
$settings ??= (array) Config::get('iam', []);
return filter_var($settings['v2_enabled'] ?? false, FILTER_VALIDATE_BOOL);
}
public static function feature(string $feature, ?array $settings = null): bool
{
$settings ??= (array) Config::get('iam', []);
if (!in_array($feature, ['management', 'launch'], true)) { return false; }
return self::enabled($settings) && filter_var($settings['v2_' . $feature . '_enabled'] ?? false, FILTER_VALIDATE_BOOL);
}
public static function https(string $url): string
{
$p = parse_url($url);
if (!$p || ($p['scheme'] ?? '') !== 'https' || empty($p['host']) || isset($p['user']) || isset($p['pass'])
|| isset($p['fragment']) || isset($p['query']) || preg_match('/[\x00-\x20\x7f\\\\]/', $url)) { throw new RuntimeException('INVALID_FIXED_URL'); }
return rtrim($url, '/');
}
public static function origin(string $url): string
{
$url = self::https($url);
if ((parse_url($url, PHP_URL_PATH) ?? '') !== '') { throw new RuntimeException('INVALID_FIXED_URL'); }
return $url;
}
public function call(string $method, string $path, array $body = [], ?string $key = null): array
{
if (!preg_match('#^/[a-zA-Z0-9/_?=&%.:-]+$#D', $path) || str_contains($path, '..')) { throw new RuntimeException('INVALID_PATH'); }
$url = rtrim($this->settings['api_url'], '/') . '/internal/v2/applications/' . rawurlencode($this->settings['application_id'] ?? 'zyt') . $path;
$management = preg_match('#^/(identities|operations|audit|batch|jobs)(/|[?]|$)#D', $path) === 1;
$credential = (string) ($this->settings[$management ? 'v2_management_token' : 'v2_token'] ?? '');
if (strlen($credential) < 32 || preg_match('/[\r\n]/', $credential)
|| ($management && hash_equals((string) $this->settings['v2_token'], $credential))) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
$headers = ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $credential];
if ($method !== 'GET') {
$headers[] = 'X-Request-ID: ' . bin2hex(random_bytes(16));
$headers[] = 'Idempotency-Key: ' . ($key ?? bin2hex(random_bytes(24)));
}
$data = $method === 'GET' ? '' : json_encode($body, JSON_THROW_ON_ERROR);
if ($this->transport) { $r = ($this->transport)($method, $url, $headers, $data); }
else {
$c = curl_init($url); $response = '';
curl_setopt_array($c, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 10,
CURLOPT_WRITEFUNCTION => static function ($c, $chunk) use (&$response) {
if (strlen($response) + strlen($chunk) > 2097152) { return 0; } $response .= $chunk; return strlen($chunk);
}]);
$ok = curl_exec($c); $r = ['status' => curl_getinfo($c, CURLINFO_RESPONSE_CODE), 'body' => $ok === false ? '' : $response]; curl_close($c);
}
$result = json_decode($r['body'] ?? '', true);
if (!is_array($result)) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
$operationEnvelope = isset($result['id']) && is_string($result['id'])
&& in_array($result['status'] ?? '', ['pending', 'succeeded', 'failed', 'conflict'], true)
&& preg_match('#^/(operations|jobs|batch)(/|$)#D', $path);
if (($r['status'] ?? 0) < 200 || $r['status'] >= 300 || (isset($result['error']) && !$operationEnvelope)) {
$code = $result['error']['code'] ?? 'SERVICE_UNAVAILABLE';
throw new RuntimeException(preg_match('/^[A-Z_]{3,64}$/D', $code) ? $code : 'SERVICE_UNAVAILABLE');
}
return $result;
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service\iam\v2;
use RuntimeException;
use think\facade\Db;
final class IamV2Events
{
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null, ?callable $refresh = null, ?callable $locate = null, ?callable $generation = null): array
{
if (strlen($raw) > 65536 || strlen($secret) < 32 || !hash_equals('sha256=' . hash_hmac('sha256', $raw, $secret), $signature)) { throw new RuntimeException('FORBIDDEN'); }
$event = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
if (empty($event['employeeId']) || $eventId === '' || strlen($eventId) > 128 || $eventId !== ($event['id'] ?? '') || !in_array('zyt', (array) ($event['applicationIds'] ?? []), true)) { throw new RuntimeException('INVALID_EVENT'); }
$occurredAt = (string) ($event['occurredAt'] ?? '');
if (!preg_match('/^\d{4}-\d{2}-\d{2}T.*(Z|[+-][0-9]{2}:[0-9]{2})$/D', $occurredAt)) { throw new RuntimeException('INVALID_EVENT'); }
$stamp = strtotime($occurredAt);
if (!$stamp || $stamp > time() + 60) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
$customRevoke = $revoke !== null;
$revoke ??= fn(int $id) => IamV2Manager::revoke($id);
$refresh ??= fn(int $id) => (new IamV2Manager())->binding($id, true);
$generation ??= $customRevoke ? fn(int $id, int $upper) => $revoke($id) : fn(int $id, int $upper) => IamV2Source::revokeGeneration($id, $upper, (string) $event['employeeId']);
$locate ??= static function (array $event): array {
if (($event['eventType'] ?? '') === 'binding_revoked' && isset($event['externalAccountId'])) {
if (!is_string($event['externalAccountId']) || !preg_match('/^[1-9][0-9]{0,9}$/D', $event['externalAccountId'])) { throw new RuntimeException('INVALID_EVENT'); }
return [(int) $event['externalAccountId']];
}
$reply = (new IamV2Client())->call('GET', '/bindings?' . http_build_query(['employeeId' => $event['employeeId'], 'page' => 1, 'pageSize' => 100], '', '&', PHP_QUERY_RFC3986));
if (($reply['total'] ?? 0) > 100) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
$ids = [];
foreach ($reply['items'] ?? [] as $item) {
if (($item['binding']['employeeId'] ?? '') !== $event['employeeId'] || ($item['binding']['applicationId'] ?? '') !== 'zyt') { throw new RuntimeException('INVALID_RESPONSE'); }
$external = (string) ($item['binding']['externalAccountId'] ?? '');
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $external)) { throw new RuntimeException('INVALID_RESPONSE'); }
$ids[] = (int) $external;
}
return $ids;
};
return Db::transaction(function () use ($event, $eventId, $raw, $revoke, $refresh, $locate, $generation) {
$existing = Db::name('iam_v2_event')->where('event_id', $eventId)->lock(true)->find();
if ($existing) {
if (!hash_equals($existing['digest'], hash('sha256', $raw))) { throw new RuntimeException('INVALID_EVENT'); }
return ['accepted' => true, 'duplicate' => true];
}
Db::name('iam_v2_event')->insert(['event_id' => $eventId, 'digest' => hash('sha256', $raw), 'received_at' => time()]);
$rows = Db::name('iam_v2_binding')->where('employee_id', (string) $event['employeeId'])->lock(true)->select()->toArray();
if (!$rows && ($event['eventType'] ?? '') !== 'source_binding_revoked') {
foreach ($locate($event) as $id) {
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
if (!$row) { $refresh($id); $row = Db::name('iam_v2_binding')->where('admin_id', $id)->find(); }
if ($row) { $rows[] = $row; }
}
}
foreach ($rows as $row) {
$bindingEvent = ($event['eventType'] ?? '') === 'binding_revoked'
|| in_array($event['reason'] ?? '', ['iam.v2.unbind', 'iam.v2.rebind'], true);
// ZYT is source-only in this rollout; target-derived revocation belongs to ERP.
if (($event['eventType'] ?? '') === 'source_binding_revoked') { continue; }
$upper = isset($event['bindingVersion']) ? (int) $event['bindingVersion'] : null;
if ($bindingEvent && $upper !== null && ($upper < (int) $row['version'] || $row['employee_id'] !== $event['employeeId'])) { $generation((int) $row['admin_id'], $upper); continue; }
if (!$bindingEvent || $upper === null) {
// Durable outbox delivery may be old. Current central state wins over a stale generic event.
// A failed lookup rolls back event receipt, so the durable outbox can retry.
$current = $refresh((int) $row['admin_id']);
if (($current['binding']['state'] ?? '') === 'verified' && ($current['employee']['status'] ?? '') === 'active'
&& ($current['access']['allowed'] ?? false)) { continue; }
}
$updates = ['checked_at' => 0];
// Personnel disable/entitlement events invalidate sessions, not the binding itself.
// A versioned binding event carries the OLD generation as its revocation upper bound.
if ($bindingEvent && $upper !== null && $upper > 0) {
$updates['state'] = 'revoked'; $updates['version'] = max((int) $row['version'], $upper);
}
Db::name('iam_v2_binding')->where('admin_id', $row['admin_id'])->update($updates);
if ($bindingEvent && $upper !== null) { $generation((int) $row['admin_id'], $upper); }
else { $revoke((int) $row['admin_id']); }
}
return ['accepted' => true];
});
}
}

Some files were not shown because too many files have changed in this diff Show More